Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset6b338834ef4ed6033dd5bbba9b0f45a80261a45b741bbaf883512e0b5907215a
Authorolim7t <omichallat+github@gmail.com> · 2015-09-29 17:05 -07:00
Committerolim7t <omichallat+github@gmail.com> · 2015-09-29 17:05 -07:00
Parents2ec008046b58, 5559fecca376

Browse the files at this changeset

23 files changed

added build.yaml +21 −0
@@ -0,0 +1,21 @@
1+java:
2+ - openjdk6
3+ - oraclejdk7
4+ - oraclejdk8
5+os:
6+ - ubuntu/trusty64
7+cassandra:
8+ - 1.2
9+ - 2.0
10+build:
11+ - type: maven
12+ version: 3.2.5
13+ goals: clean compile test --fail-never -Plong
14+ properties: |
15+ com.datastax.driver.TEST_BASE_NODE_WAIT=120
16+ com.datastax.driver.NEW_NODE_DELAY_SECONDS=100
17+ cassandra.version=$CCM_CASSANDRA_VERSION
18+ ccm.java.home=$CCM_JAVA_HOME
19+ - xunit:
20+ - "**/target/surefire-reports/TEST-*.xml"
21+ - "**/target/failsafe-reports/TEST-*.xml"
added doxyfile +336 −0
@@ -0,0 +1,336 @@
1+# Doxyfile 1.8.10
2+
3+#---------------------------------------------------------------------------
4+# Project related configuration options
5+#---------------------------------------------------------------------------
6+DOXYFILE_ENCODING = UTF-8
7+PROJECT_NAME = "DataStax Java Driver"
8+PROJECT_NUMBER =
9+PROJECT_BRIEF =
10+PROJECT_LOGO =
11+OUTPUT_DIRECTORY =
12+CREATE_SUBDIRS = NO
13+ALLOW_UNICODE_NAMES = NO
14+OUTPUT_LANGUAGE = English
15+BRIEF_MEMBER_DESC = YES
16+REPEAT_BRIEF = YES
17+ABBREVIATE_BRIEF = "The $name class" \
18+ "The $name widget" \
19+ "The $name file" \
20+ is \
21+ provides \
22+ specifies \
23+ contains \
24+ represents \
25+ a \
26+ an \
27+ the
28+ALWAYS_DETAILED_SEC = NO
29+INLINE_INHERITED_MEMB = NO
30+FULL_PATH_NAMES = NO
31+STRIP_FROM_PATH =
32+STRIP_FROM_INC_PATH =
33+SHORT_NAMES = NO
34+JAVADOC_AUTOBRIEF = NO
35+QT_AUTOBRIEF = NO
36+MULTILINE_CPP_IS_BRIEF = NO
37+INHERIT_DOCS = YES
38+SEPARATE_MEMBER_PAGES = NO
39+TAB_SIZE = 4
40+ALIASES = "throws=\par Throws\n" \
41+ "test_assumptions=\par Test Assumptions\n" \
42+ "note=\par Note\n" \
43+ "test_category=\par Test Category\n" \
44+ "jira_ticket=\par JIRA Ticket\n" \
45+ "expected_result=\par Expected Result\n" \
46+ "since=\par Since\n" \
47+ "param=\par Parameters\n" \
48+ "return=\par Return\n" \
49+ "expected_errors=\par Expected Errors\n"
50+TCL_SUBST =
51+OPTIMIZE_OUTPUT_FOR_C = NO
52+OPTIMIZE_OUTPUT_JAVA = YES
53+OPTIMIZE_FOR_FORTRAN = NO
54+OPTIMIZE_OUTPUT_VHDL = NO
55+EXTENSION_MAPPING =
56+MARKDOWN_SUPPORT = YES
57+AUTOLINK_SUPPORT = YES
58+BUILTIN_STL_SUPPORT = NO
59+CPP_CLI_SUPPORT = NO
60+SIP_SUPPORT = NO
61+IDL_PROPERTY_SUPPORT = YES
62+DISTRIBUTE_GROUP_DOC = NO
63+GROUP_NESTED_COMPOUNDS = NO
64+SUBGROUPING = YES
65+INLINE_GROUPED_CLASSES = NO
66+INLINE_SIMPLE_STRUCTS = NO
67+TYPEDEF_HIDES_STRUCT = NO
68+LOOKUP_CACHE_SIZE = 0
69+#---------------------------------------------------------------------------
70+# Build related configuration options
71+#---------------------------------------------------------------------------
72+EXTRACT_ALL = NO
73+EXTRACT_PRIVATE = NO
74+EXTRACT_PACKAGE = NO
75+EXTRACT_STATIC = NO
76+EXTRACT_LOCAL_CLASSES = YES
77+EXTRACT_LOCAL_METHODS = NO
78+EXTRACT_ANON_NSPACES = NO
79+HIDE_UNDOC_MEMBERS = NO
80+HIDE_UNDOC_CLASSES = NO
81+HIDE_FRIEND_COMPOUNDS = NO
82+HIDE_IN_BODY_DOCS = NO
83+INTERNAL_DOCS = NO
84+CASE_SENSE_NAMES = NO
85+HIDE_SCOPE_NAMES = NO
86+HIDE_COMPOUND_REFERENCE= NO
87+SHOW_INCLUDE_FILES = YES
88+SHOW_GROUPED_MEMB_INC = NO
89+FORCE_LOCAL_INCLUDES = NO
90+INLINE_INFO = YES
91+SORT_MEMBER_DOCS = YES
92+SORT_BRIEF_DOCS = NO
93+SORT_MEMBERS_CTORS_1ST = NO
94+SORT_GROUP_NAMES = NO
95+SORT_BY_SCOPE_NAME = NO
96+STRICT_PROTO_MATCHING = NO
97+GENERATE_TODOLIST = YES
98+GENERATE_TESTLIST = YES
99+GENERATE_BUGLIST = YES
100+GENERATE_DEPRECATEDLIST= YES
101+ENABLED_SECTIONS =
102+MAX_INITIALIZER_LINES = 30
103+SHOW_USED_FILES = YES
104+SHOW_FILES = YES
105+SHOW_NAMESPACES = YES
106+FILE_VERSION_FILTER =
107+LAYOUT_FILE =
108+CITE_BIB_FILES =
109+#---------------------------------------------------------------------------
110+# Configuration options related to warning and progress messages
111+#---------------------------------------------------------------------------
112+QUIET = NO
113+WARNINGS = YES
114+WARN_IF_UNDOCUMENTED = YES
115+WARN_IF_DOC_ERROR = YES
116+WARN_NO_PARAMDOC = NO
117+WARN_FORMAT = "$file:$line: $text"
118+WARN_LOGFILE =
119+#---------------------------------------------------------------------------
120+# Configuration options related to the input files
121+#---------------------------------------------------------------------------
122+INPUT = ./driver-core/src/test
123+INPUT_ENCODING = UTF-8
124+FILE_PATTERNS = *.java
125+RECURSIVE = YES
126+EXCLUDE = @Test
127+EXCLUDE_SYMLINKS = NO
128+EXCLUDE_PATTERNS =
129+EXCLUDE_SYMBOLS =
130+EXAMPLE_PATH =
131+EXAMPLE_PATTERNS = *
132+EXAMPLE_RECURSIVE = NO
133+IMAGE_PATH =
134+INPUT_FILTER =
135+FILTER_PATTERNS =
136+FILTER_SOURCE_FILES = NO
137+FILTER_SOURCE_PATTERNS =
138+USE_MDFILE_AS_MAINPAGE =
139+#---------------------------------------------------------------------------
140+# Configuration options related to source browsing
141+#---------------------------------------------------------------------------
142+SOURCE_BROWSER = NO
143+INLINE_SOURCES = NO
144+STRIP_CODE_COMMENTS = YES
145+REFERENCED_BY_RELATION = NO
146+REFERENCES_RELATION = NO
147+REFERENCES_LINK_SOURCE = YES
148+SOURCE_TOOLTIPS = YES
149+USE_HTAGS = NO
150+VERBATIM_HEADERS = YES
151+CLANG_ASSISTED_PARSING = NO
152+CLANG_OPTIONS =
153+#---------------------------------------------------------------------------
154+# Configuration options related to the alphabetical class index
155+#---------------------------------------------------------------------------
156+ALPHABETICAL_INDEX = YES
157+COLS_IN_ALPHA_INDEX = 5
158+IGNORE_PREFIX =
159+#---------------------------------------------------------------------------
160+# Configuration options related to the HTML output
161+#---------------------------------------------------------------------------
162+GENERATE_HTML = YES
163+HTML_OUTPUT = html
164+HTML_FILE_EXTENSION = .html
165+HTML_HEADER =
166+HTML_FOOTER =
167+HTML_STYLESHEET =
168+HTML_EXTRA_STYLESHEET =
169+HTML_EXTRA_FILES =
170+HTML_COLORSTYLE_HUE = 220
171+HTML_COLORSTYLE_SAT = 100
172+HTML_COLORSTYLE_GAMMA = 80
173+HTML_TIMESTAMP = YES
174+HTML_DYNAMIC_SECTIONS = NO
175+HTML_INDEX_NUM_ENTRIES = 100
176+GENERATE_DOCSET = NO
177+DOCSET_FEEDNAME = "Doxygen generated docs"
178+DOCSET_BUNDLE_ID = org.doxygen.Project
179+DOCSET_PUBLISHER_ID = org.doxygen.Publisher
180+DOCSET_PUBLISHER_NAME = Publisher
181+GENERATE_HTMLHELP = NO
182+CHM_FILE =
183+HHC_LOCATION =
184+GENERATE_CHI = NO
185+CHM_INDEX_ENCODING =
186+BINARY_TOC = NO
187+TOC_EXPAND = NO
188+GENERATE_QHP = NO
189+QCH_FILE =
190+QHP_NAMESPACE = org.doxygen.Project
191+QHP_VIRTUAL_FOLDER = doc
192+QHP_CUST_FILTER_NAME =
193+QHP_CUST_FILTER_ATTRS =
194+QHP_SECT_FILTER_ATTRS =
195+QHG_LOCATION =
196+GENERATE_ECLIPSEHELP = NO
197+ECLIPSE_DOC_ID = org.doxygen.Project
198+DISABLE_INDEX = NO
199+GENERATE_TREEVIEW = YES
200+ENUM_VALUES_PER_LINE = 4
201+TREEVIEW_WIDTH = 250
202+EXT_LINKS_IN_WINDOW = NO
203+FORMULA_FONTSIZE = 10
204+FORMULA_TRANSPARENT = YES
205+USE_MATHJAX = NO
206+MATHJAX_FORMAT = HTML-CSS
207+MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest
208+MATHJAX_EXTENSIONS =
209+MATHJAX_CODEFILE =
210+SEARCHENGINE = YES
211+SERVER_BASED_SEARCH = NO
212+EXTERNAL_SEARCH = NO
213+SEARCHENGINE_URL =
214+SEARCHDATA_FILE = searchdata.xml
215+EXTERNAL_SEARCH_ID =
216+EXTRA_SEARCH_MAPPINGS =
217+#---------------------------------------------------------------------------
218+# Configuration options related to the LaTeX output
219+#---------------------------------------------------------------------------
220+GENERATE_LATEX = NO
221+LATEX_OUTPUT = latex
222+LATEX_CMD_NAME = latex
223+MAKEINDEX_CMD_NAME = makeindex
224+COMPACT_LATEX = NO
225+PAPER_TYPE = a4
226+EXTRA_PACKAGES =
227+LATEX_HEADER =
228+LATEX_FOOTER =
229+LATEX_EXTRA_STYLESHEET =
230+LATEX_EXTRA_FILES =
231+PDF_HYPERLINKS = YES
232+USE_PDFLATEX = YES
233+LATEX_BATCHMODE = NO
234+LATEX_HIDE_INDICES = NO
235+LATEX_SOURCE_CODE = NO
236+LATEX_BIB_STYLE = plain
237+#---------------------------------------------------------------------------
238+# Configuration options related to the RTF output
239+#---------------------------------------------------------------------------
240+GENERATE_RTF = NO
241+RTF_OUTPUT = rtf
242+COMPACT_RTF = NO
243+RTF_HYPERLINKS = NO
244+RTF_STYLESHEET_FILE =
245+RTF_EXTENSIONS_FILE =
246+RTF_SOURCE_CODE = NO
247+#---------------------------------------------------------------------------
248+# Configuration options related to the man page output
249+#---------------------------------------------------------------------------
250+GENERATE_MAN = NO
251+MAN_OUTPUT = man
252+MAN_EXTENSION = .3
253+MAN_SUBDIR =
254+MAN_LINKS = NO
255+#---------------------------------------------------------------------------
256+# Configuration options related to the XML output
257+#---------------------------------------------------------------------------
258+GENERATE_XML = NO
259+XML_OUTPUT = xml
260+XML_PROGRAMLISTING = YES
261+#---------------------------------------------------------------------------
262+# Configuration options related to the DOCBOOK output
263+#---------------------------------------------------------------------------
264+GENERATE_DOCBOOK = NO
265+DOCBOOK_OUTPUT = docbook
266+DOCBOOK_PROGRAMLISTING = NO
267+#---------------------------------------------------------------------------
268+# Configuration options for the AutoGen Definitions output
269+#---------------------------------------------------------------------------
270+GENERATE_AUTOGEN_DEF = NO
271+#---------------------------------------------------------------------------
272+# Configuration options related to the Perl module output
273+#---------------------------------------------------------------------------
274+GENERATE_PERLMOD = NO
275+PERLMOD_LATEX = NO
276+PERLMOD_PRETTY = YES
277+PERLMOD_MAKEVAR_PREFIX =
278+#---------------------------------------------------------------------------
279+# Configuration options related to the preprocessor
280+#---------------------------------------------------------------------------
281+ENABLE_PREPROCESSING = YES
282+MACRO_EXPANSION = NO
283+EXPAND_ONLY_PREDEF = NO
284+SEARCH_INCLUDES = YES
285+INCLUDE_PATH =
286+INCLUDE_FILE_PATTERNS =
287+PREDEFINED =
288+EXPAND_AS_DEFINED =
289+SKIP_FUNCTION_MACROS = YES
290+#---------------------------------------------------------------------------
291+# Configuration options related to external references
292+#---------------------------------------------------------------------------
293+TAGFILES =
294+GENERATE_TAGFILE =
295+ALLEXTERNALS = NO
296+EXTERNAL_GROUPS = YES
297+EXTERNAL_PAGES = YES
298+PERL_PATH = /usr/bin/perl
299+#---------------------------------------------------------------------------
300+# Configuration options related to the dot tool
301+#---------------------------------------------------------------------------
302+CLASS_DIAGRAMS = YES
303+MSCGEN_PATH =
304+DIA_PATH =
305+HIDE_UNDOC_RELATIONS = YES
306+HAVE_DOT = NO
307+DOT_NUM_THREADS = 0
308+DOT_FONTNAME = Helvetica
309+DOT_FONTSIZE = 10
310+DOT_FONTPATH =
311+CLASS_GRAPH = YES
312+COLLABORATION_GRAPH = YES
313+GROUP_GRAPHS = YES
314+UML_LOOK = NO
315+UML_LIMIT_NUM_FIELDS = 10
316+TEMPLATE_RELATIONS = NO
317+INCLUDE_GRAPH = YES
318+INCLUDED_BY_GRAPH = YES
319+CALL_GRAPH = NO
320+CALLER_GRAPH = NO
321+GRAPHICAL_HIERARCHY = YES
322+DIRECTORY_GRAPH = YES
323+DOT_IMAGE_FORMAT = png
324+INTERACTIVE_SVG = NO
325+DOT_PATH =
326+DOTFILE_DIRS =
327+MSCFILE_DIRS =
328+DIAFILE_DIRS =
329+PLANTUML_JAR_PATH =
330+PLANTUML_INCLUDE_PATH =
331+DOT_GRAPH_MAX_NODES = 50
332+MAX_DOT_GRAPH_DEPTH = 0
333+DOT_TRANSPARENT = NO
334+DOT_MULTI_TARGETS = NO
335+GENERATE_LEGEND = YES
336+DOT_CLEANUP = YES
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +6 −3
@@ -25,6 +25,7 @@
2525 import java.util.concurrent.atomic.AtomicInteger;
2626 import java.util.concurrent.atomic.AtomicReference;
2727
28+import com.google.common.annotations.VisibleForTesting;
2829 import com.google.common.collect.MapMaker;
2930 import com.google.common.util.concurrent.*;
3031 import io.netty.bootstrap.Bootstrap;
@@ -77,10 +78,12 @@
7778 public final InetSocketAddress address;
7879 private final String name;
7980
80- private volatile Channel channel;
81+ @VisibleForTesting
82+ volatile Channel channel;
8183 private final Factory factory;
8284
83- private final Dispatcher dispatcher;
85+ @VisibleForTesting
86+ final Dispatcher dispatcher;
8487
8588 // Used by connection pooling to count how many requests are "in flight" on that connection.
8689 public final AtomicInteger inFlight = new AtomicInteger(0);
@@ -930,7 +933,7 @@
930933 flusher.start();
931934 }
932935
933- private class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
936+ class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
934937
935938 public final StreamIdGenerator streamIdHandler;
936939 private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +3 −1
@@ -22,6 +22,7 @@
2222 import java.util.concurrent.*;
2323 import java.util.concurrent.atomic.AtomicReference;
2424
25+import com.google.common.annotations.VisibleForTesting;
2526 import com.google.common.base.Objects;
2627 import com.google.common.util.concurrent.ListenableFuture;
2728 import org.slf4j.Logger;
@@ -60,7 +61,8 @@
6061 private static final String SELECT_SCHEMA_PEERS = "SELECT peer, rpc_address, schema_version FROM system.peers";
6162 private static final String SELECT_SCHEMA_LOCAL = "SELECT schema_version FROM system.local WHERE key='local'";
6263
63- private final AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
64+ @VisibleForTesting
65+ final AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
6466
6567 private final Cluster.Manager cluster;
6668
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +31 −5
@@ -46,7 +46,7 @@
4646 final AtomicReference<ListenableFuture<?>> future = new AtomicReference<ListenableFuture<?>>();
4747 AbstractReconnectionHandler handler;
4848
49- @BeforeMethod(groups = "unit")
49+ @BeforeMethod(groups = {"unit", "short"})
5050 public void setup() {
5151 executor = Executors.newScheduledThreadPool(2);
5252 schedule = new MockReconnectionSchedule();
@@ -65,7 +65,7 @@
6565 };
6666 }
6767
68- @AfterMethod(groups = "unit")
68+ @AfterMethod(groups = {"unit", "short"})
6969 public void tearDown() {
7070 if (future.get() != null)
7171 future.get().cancel(false);
@@ -115,10 +115,9 @@
115115 }
116116
117117 @Test(groups = "unit")
118- public void should_stop_if_cancelled_between_attempts() {
119- handler.start();
120-
118+ public void should_stop_if_cancelled_before_first_attempt() {
121119 schedule.delay = 10 * 1000; // give ourselves time to cancel
120+ handler.start();
122121 schedule.tick();
123122
124123 future.get().cancel(false);
@@ -130,6 +129,33 @@
130129 assertThat(future.get().isCancelled()).isTrue();
131130 }
132131
132+ @Test(groups = "short")
133+ public void should_stop_if_cancelled_between_attempts() {
134+ handler.start();
135+
136+ // Force a failed reconnect.
137+ schedule.tick();
138+ work.nextReconnect = ReconnectBehavior.THROW_EXCEPTION;
139+ // Tick work, should trigger the barrier in tryReconnect.
140+ work.tick();
141+
142+ // Tick schedule, should cause nextDelayMs to proceed, reconnect handler will call reschedule.
143+ schedule.delay = 3000;
144+ schedule.tick();
145+
146+ // At this point the reconnect should be scheduled but not executed yet, cancel the future.
147+ future.get().cancel(false);
148+
149+ // Should block until scheduler runs, detects cancel and exits.
150+ waitForCompletion();
151+
152+ assertThat(work.success).isFalse();
153+ // Should have had 1 failed attempt, no second attempt since cancelled.
154+ assertThat(work.tries).isEqualTo(1);
155+ // The future will be marked null once it is detected as cancelled.
156+ assertThat(future.get()).isNull();
157+ }
158+
133159 @Test(groups = "unit")
134160 public void should_complete_if_cancelled_during_successful_reconnect() throws InterruptedException {
135161 handler.start();
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +26 −25
@@ -25,12 +25,11 @@
2525
2626 import com.google.common.collect.ImmutableList;
2727 import com.google.common.collect.ImmutableList.Builder;
28-import org.mockito.Mockito;
2928
3029 import static org.mockito.Mockito.mock;
31-import static org.testng.Assert.*;
32-
33-import com.datastax.driver.core.policies.ExponentialReconnectionPolicy;
30+import static org.testng.Assert.assertEquals;
31+import static org.testng.Assert.assertNotNull;
32+import static org.testng.Assert.assertTrue;
3433
3534 /**
3635 * Base class for replication strategy tests. Currently only supports testing
@@ -40,25 +39,27 @@
4039
4140 private static final Token.Factory partitioner = Token.getFactory("Murmur3Partitioner");
4241
42+ private static final Cluster.Manager mockManager = mock(Cluster.Manager.class);
43+
4344 protected static class HostMock extends Host {
44- private final String address;
45+ private final InetSocketAddress address;
4546
46- private HostMock(String address, Cluster.Manager manager) throws UnknownHostException {
47- super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.DefaultConvictionPolicy.Factory(), manager);
47+ private HostMock(InetSocketAddress address, Cluster.Manager manager) {
48+ super(address, new ConvictionPolicy.DefaultConvictionPolicy.Factory(), manager);
4849 this.address = address;
4950 }
5051
51- private HostMock(String address, String dc, String rack, Cluster.Manager manager) throws UnknownHostException {
52+ private HostMock(InetSocketAddress address, String dc, String rack, Cluster.Manager manager) {
5253 this(address, manager);
5354 this.setLocationInfo(dc, rack);
5455 }
5556
5657 @Override
5758 public String toString() {
58- return address;
59+ return address.getHostName();
5960 }
6061
61- public String getMockAddress() {
62+ public InetSocketAddress getMockAddress() {
6263 return address;
6364 }
6465
@@ -84,24 +85,16 @@
8485 * Convenience method to quickly create a mock host by a given address.
8586 * Specified address must be accessible, otherwise a RuntimeException is thrown
8687 */
87- protected static HostMock host(String address) {
88- try {
89- return new HostMock(address, mock(Cluster.Manager.class));
90- } catch (UnknownHostException ex) {
91- throw new RuntimeException(ex); //wrap to avoid declarations
92- }
88+ protected static HostMock host(InetSocketAddress address) {
89+ return new HostMock(address, mockManager);
9390 }
9491
9592 /**
9693 * Convenience method to quickly create a mock host by the given address
9794 * located in the given datacenter/rack
9895 */
99- protected static HostMock host(String address, String dc, String rack) {
100- try {
101- return new HostMock(address, dc, rack, mock(Cluster.Manager.class));
102- } catch (UnknownHostException ex) {
103- throw new RuntimeException(ex); //wrap to avoid declarations
104- }
96+ protected static HostMock host(InetSocketAddress address, String dc, String rack) {
97+ return new HostMock(address, dc, rack, mockManager);
10598 }
10699
107100 /**
@@ -117,7 +110,7 @@
117110 * if created by the <code>host(...)</code> methods. Returns null if
118111 * given host is not a mock.
119112 */
120- protected static String mockAddress(Host host) {
113+ protected static InetSocketAddress mockAddress(Host host) {
121114 HostMock mock = asMock(host);
122115 return mock == null ? null : mock.getMockAddress();
123116 }
@@ -138,7 +131,7 @@
138131 * Asserts that the replica map for a given token contains the expected list of replica hosts.
139132 * Hosts are checked in order, replica placement should be an ordered set
140133 */
141- protected static void assertReplicaPlacement(Map<Token, Set<Host>> replicaMap, Token token, String... expected) {
134+ protected static void assertReplicaPlacement(Map<Token, Set<Host>> replicaMap, Token token, InetSocketAddress... expected) {
142135 Set<Host> replicaSet = replicaMap.get(token);
143136 assertNotNull(replicaSet);
144137 assertReplicasForToken(replicaSet, expected);
@@ -147,7 +140,7 @@
147140 /**
148141 * Checks if a given ordered set of replicas matches the expected list of replica hosts
149142 */
150- protected static void assertReplicasForToken(Set<Host> replicaSet, String... expected) {
143+ protected static void assertReplicasForToken(Set<Host> replicaSet, InetSocketAddress... expected) {
151144 final String message = "Contents of replica set: " + replicaSet + " do not match expected hosts: " + Arrays.toString(expected);
152145 assertEquals(replicaSet.size(), expected.length, message);
153146
@@ -161,4 +154,12 @@
161154 assertTrue(match, message);
162155 }
163156 }
157+
158+ protected static InetSocketAddress socketAddress(String address) {
159+ try {
160+ return new InetSocketAddress(InetAddress.getByName(address), 9042);
161+ } catch(UnknownHostException ex) {
162+ throw new RuntimeException(ex);
163+ }
164+ }
164165 }
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +13 −12
@@ -53,10 +53,10 @@
5353
5454 public static final String IP_PREFIX;
5555
56- private static final String CASSANDRA_VERSION_REGEXP = "\\d\\.\\d\\.\\d+(-\\w+)?";
57- static final File CASSANDRA_DIR;
5856 static final String CASSANDRA_VERSION;
5957
58+ static final String CASSANDRA_INSTALL_ARGS;
59+
6060 public static final String DEFAULT_CLIENT_TRUSTSTORE_PASSWORD = "cassandra1sfun";
6161 public static final String DEFAULT_CLIENT_TRUSTSTORE_PATH = "/client.truststore";
6262
@@ -89,13 +89,15 @@
8989 private static final String CCM_COMMAND;
9090
9191 static {
92- String version = System.getProperty("cassandra.version");
93- if (version.matches(CASSANDRA_VERSION_REGEXP)) {
94- CASSANDRA_DIR = null;
95- CASSANDRA_VERSION = "-v " + version;
92+ CASSANDRA_VERSION = System.getProperty("cassandra.version");
93+ String installDirectory = System.getProperty("cassandra.directory");
94+ String branch = System.getProperty("cassandra.branch");
95+ if (installDirectory != null && !installDirectory.trim().isEmpty()) {
96+ CASSANDRA_INSTALL_ARGS = "--install-dir=" + new File(installDirectory).getAbsolutePath();
97+ } else if(branch != null && !branch.trim().isEmpty()) {
98+ CASSANDRA_INSTALL_ARGS = "-v git:" + branch;
9699 } else {
97- CASSANDRA_DIR = new File(version);
98- CASSANDRA_VERSION = "";
100+ CASSANDRA_INSTALL_ARGS = "-v " + CASSANDRA_VERSION;
99101 }
100102
101103 String ip_prefix = System.getProperty("ipprefix");
@@ -286,7 +288,6 @@
286288 logger.debug("Executing: " + fullCommand);
287289 CommandLine cli = CommandLine.parse(fullCommand);
288290 Executor executor = new DefaultExecutor();
289- executor.setWorkingDirectory(CASSANDRA_DIR);
290291
291292 LogOutputStream outStream = new LogOutputStream() {
292293 @Override protected void processLine(String line, int logLevel) {
@@ -596,7 +597,7 @@
596597 private final String clusterName;
597598 private Integer[] nodes = { 1 };
598599 private boolean start = true;
599- private String cassandraVersion = CASSANDRA_VERSION;
600+ private String cassandraInstallArgs = CASSANDRA_INSTALL_ARGS;
600601 private String[] startOptions = new String[0];
601602 private Map<String, String> cassandraConfiguration = Maps.newHashMap();
602603
@@ -636,7 +637,7 @@
636637
637638 /** Defaults to system property cassandra.version */
638639 public Builder withCassandraVersion(String cassandraVersion) {
639- this.cassandraVersion = "-v " + cassandraVersion;
640+ this.cassandraInstallArgs = "-v " + cassandraVersion;
640641 return this;
641642 }
642643
@@ -665,7 +666,7 @@
665666 StringBuilder result = new StringBuilder(CCM_COMMAND + " create");
666667 result.append(" " + clusterName);
667668 result.append(" -i" + IP_PREFIX);
668- result.append(" " + cassandraVersion);
669+ result.append(" " + cassandraInstallArgs);
669670 if (nodes.length > 0)
670671 result.append(" -n " + Joiner.on(":").join(nodes));
671672 if (startOptions.length > 0)
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +8 −4
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
18+import com.google.common.collect.Iterators;
19+import org.assertj.core.api.AbstractAssert;
20+
1921 import java.util.Iterator;
2022 import java.util.Set;
2123 import java.util.TreeSet;
2224
2325 import static org.assertj.core.api.Assertions.assertThat;
2426
25-import com.google.common.collect.Iterators;
26-import org.assertj.core.api.AbstractAssert;
27-
2827 public class ClusterAssert extends AbstractAssert<ClusterAssert, Cluster> {
2928 protected ClusterAssert(Cluster actual) {
3029 super(actual, ClusterAssert.class);
@@ -42,6 +41,11 @@
4241 return this;
4342 }
4443
44+ public ClusterAssert hasOpenControlConnection() {
45+ assertThat(actual.manager.controlConnection.isOpen()).isTrue();
46+ return this;
47+ }
48+
4549 public HostAssert host(int hostNumber) {
4650 // TODO at some point this won't work anymore if we have assertions that wait for a node to
4751 // join the cluster, e.g. assertThat(cluster).node(3).comesUp().
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +1 −1
@@ -154,7 +154,7 @@
154154 * @test_category connection
155155 * @expected_result Cluster closes within 1 second.
156156 */
157- @Test(groups = "unit")
157+ @Test(groups = "short")
158158 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
159159 Cluster cluster = Cluster.builder()
160160 .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +10 −0
@@ -41,6 +41,16 @@
4141 return this;
4242 }
4343
44+ public HostAssert isUp() {
45+ assertThat(actual.isUp()).isTrue();
46+ return this;
47+ }
48+
49+ public HostAssert isDown() {
50+ assertThat(actual.isUp()).isFalse();
51+ return this;
52+ }
53+
4454 public HostAssert isAtDistance(HostDistance expected) {
4555 LoadBalancingPolicy loadBalancingPolicy = cluster.manager.loadBalancingPolicy();
4656 assertThat(loadBalancingPolicy.distance(actual)).isEqualTo(expected);
added driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java +118 −0
@@ -0,0 +1,118 @@
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.datastax.driver.core.policies.ConstantReconnectionPolicy;
19+import com.google.common.util.concurrent.Uninterruptibles;
20+import org.testng.annotations.AfterMethod;
21+import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import java.net.InetSocketAddress;
25+
26+import static com.datastax.driver.core.Assertions.assertThat;
27+import static com.datastax.driver.core.HostDistance.LOCAL;
28+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
29+import static java.util.concurrent.TimeUnit.SECONDS;
30+
31+import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
32+
33+public class HostConnectionPoolMultiTest {
34+
35+ private SCassandraCluster scassandra;
36+
37+ private Cluster cluster;
38+
39+ @BeforeMethod(groups={"short", "long"})
40+ private void setUp() {
41+ scassandra = new SCassandraCluster(2);
42+ }
43+
44+ @AfterMethod(groups={"short", "long"})
45+ private void tearDown() {
46+ if(cluster != null) {
47+ cluster.close();
48+ }
49+ scassandra.stop();
50+ }
51+
52+ private void createCluster(int core, int max) {
53+ PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, core, max);
54+ SocketOptions socketOptions = new SocketOptions().setReadTimeoutMillis(1000);
55+ cluster = Cluster.builder()
56+ .addContactPoint(CCMBridge.ipOfNode(1))
57+ .withQueryOptions(nonDebouncingQueryOptions())
58+ .withPoolingOptions(poolingOptions)
59+ .withSocketOptions(socketOptions)
60+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
61+ .build();
62+ cluster.connect();
63+ }
64+
65+ /**
66+ * Ensures that if all connections fail to a host on pool init that the host is marked down.
67+ *
68+ * @jira_ticket JAVA-544
69+ * @test_category connection:connection_pool
70+ * @since 2.0.11
71+ */
72+ @Test(groups="short")
73+ public void should_mark_host_down_if_all_connections_fail_on_init() {
74+ // Prevent any connections on node 2.
75+ scassandra.instance(2).currentClient().disableListener();
76+ createCluster(8,8);
77+
78+ // Node 2 should be in a down state while node 1 stays up.
79+ assertThat(cluster).host(2).goesDownWithin(10, SECONDS);
80+ assertThat(cluster).host(1).isUp();
81+
82+ // Node 2 should come up as soon as it is able to reconnect.
83+ scassandra.instance(2).currentClient().enableListener();
84+ assertThat(cluster).host(2).comesUpWithin(2, SECONDS);
85+ }
86+
87+ /**
88+ * Ensures that if the control connection goes down, but the Host bound the control connection
89+ * still has an up pool, the Host should remain up and the Control Connection should be replaced.
90+ *
91+ * @jira_ticket JAVA-544
92+ * @test_category connection:connection_pool
93+ * @since 2.0.11
94+ */
95+ @Test(groups="short")
96+ public void should_replace_control_connection_if_it_goes_down_but_host_remains_up() {
97+ createCluster(1,2);
98+
99+ // Ensure control connection is on node 1.
100+ assertThat(cluster).usesControlHost(1);
101+
102+ // Identify the socket associated with the control connection.
103+ Connection controlConnection = cluster.manager.controlConnection.connectionRef.get();
104+ InetSocketAddress controlSocket = (InetSocketAddress)controlConnection.channel.localAddress();
105+
106+ // Close the control connection.
107+ scassandra.instance(1).currentClient()
108+ .closeConnection(CLOSE, controlSocket);
109+
110+ // Sleep reconnect interval * 2 to allow time to reconnect.
111+ Uninterruptibles.sleepUninterruptibly(2, SECONDS);
112+
113+ // Ensure the control connection was replaced and host 1 remains up.
114+ assertThat(cluster).hasOpenControlConnection()
115+ .host(1).isUp();
116+ assertThat(cluster.manager.controlConnection.connectionRef.get()).isNotEqualTo(controlConnection);
117+ }
118+}
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +898 −223
@@ -15,32 +15,70 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
18+import java.net.InetSocketAddress;
19+import java.util.Iterator;
1920 import java.util.List;
2021 import java.util.concurrent.*;
2122 import java.util.concurrent.atomic.AtomicBoolean;
23+import java.util.concurrent.atomic.AtomicReference;
2224
23-import static java.util.concurrent.TimeUnit.MILLISECONDS;
25+import static java.util.Collections.singletonList;
2426 import static java.util.concurrent.TimeUnit.SECONDS;
2527
2628 import com.codahale.metrics.Gauge;
27-import com.google.common.collect.Lists;
29+import com.google.common.util.concurrent.Uninterruptibles;
30+import org.scassandra.cql.PrimitiveType;
31+import org.scassandra.http.client.PrimingRequest;
32+import org.testng.annotations.BeforeClass;
2833 import org.testng.annotations.Test;
2934
30-import static org.assertj.core.api.Assertions.assertThat;
31-import static org.mockito.Mockito.doReturn;
32-import static org.mockito.Mockito.spy;
35+import static com.google.common.collect.Lists.newArrayList;
36+import static org.mockito.Mockito.*;
37+import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
38+import static org.scassandra.http.client.PrimingRequest.then;
3339 import static org.testng.Assert.fail;
3440
35-public class HostConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
36- @Override
37- protected Collection<String> getTableDefinitions() {
38- StringBuilder sb = new StringBuilder("CREATE TABLE Java349 (mykey INT primary key");
39- for (int i = 0; i < 1000; i++) {
40- sb.append(", column").append(i).append(" INT");
41+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
42+
43+import static com.datastax.driver.core.Assertions.assertThat;
44+
45+public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
46+
47+
48+ @BeforeClass(groups={"short", "long"})
49+ public void reinitializeCluster() {
50+ // Don't use the provided cluster, each test will create its own instead.
51+ cluster.close();
52+ }
53+
54+ /**
55+ * Sends 101 requests on pool, asserting that the connection used is in expectedConnections, except for the last request.
56+ */
57+ private List<MockRequest> fillConnectionToThreshold(HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
58+ List<MockRequest> requests = sendRequests(100, pool, expectedConnections);
59+ requests.add(MockRequest.send(pool));
60+ return requests;
61+ }
62+
63+ /**
64+ * Sends count requests on pool.
65+ */
66+ private List<MockRequest> sendRequests(int count, HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
67+ return sendRequests(count, pool, null);
68+ }
69+
70+ /**
71+ * Sends count requests on pool, asserting that the connection used is in expectedConnections.
72+ */
73+ private List<MockRequest> sendRequests(int count, HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
74+ List<MockRequest> requests = newArrayList();
75+ for(int i = 0; i < count; i++) {
76+ MockRequest request = MockRequest.send(pool);
77+ requests.add(request);
78+ if(expectedConnections != null)
79+ assertThat(expectedConnections).contains(request.connection);
4180 }
42- sb.append(")");
43- return Lists.newArrayList(sb.toString());
81+ return requests;
4482 }
4583
4684 @Override
@@ -51,6 +89,31 @@
5189 return builder.withProtocolVersion(versionToUse);
5290 }
5391
92+ /**
93+ * Completes count requests by simulating a successful response.
94+ */
95+ private void completeRequests(int count, List<MockRequest> requests) {
96+ Iterator<MockRequest> requestIt = requests.iterator();
97+ for(int i = 0; i < count; i++) {
98+ if(requestIt.hasNext()) {
99+ MockRequest request = requestIt.next();
100+ request.simulateSuccessResponse();
101+ requestIt.remove();
102+ } else {
103+ break;
104+ }
105+ }
106+ }
107+
108+ /**
109+ * Completes all requests by simulating a successful response.
110+ */
111+ private void completeRequests(List<MockRequest> requests) {
112+ for(MockRequest request : requests) {
113+ request.simulateSuccessResponse();
114+ }
115+ }
116+
54117 /**
55118 * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
56119 * of creating a new connection.
@@ -60,24 +123,24 @@
60123 * @test_category connection:connection_pool
61124 */
62125 @Test(groups = "short")
63- public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException {
64- HostConnectionPool pool = createPool(2, 2);
65-
66- assertThat(pool.connections.size()).isEqualTo(2);
67- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
68-
69- for (int i = 0; i < 256; i++) {
70- Connection connection = pool.borrowConnection(100, MILLISECONDS);
71- assertThat(coreConnections).contains(connection);
72- }
73-
74- boolean timedOut = false;
126+ public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
127+ Cluster cluster = createClusterBuilder().build();
128+ List<MockRequest> requests = newArrayList();
75129 try {
76- pool.borrowConnection(100, MILLISECONDS);
77- } catch (TimeoutException e) {
78- timedOut = true;
130+ HostConnectionPool pool = createPool(cluster, 2, 2);
131+
132+ assertThat(pool.connections.size()).isEqualTo(2);
133+ List<Connection> coreConnections = newArrayList(pool.connections);
134+ requests.addAll(sendRequests(256, pool, coreConnections));
135+
136+ try {
137+ MockRequest.send(pool);
138+ Assertions.fail("Expected a TimeoutException");
139+ } catch (TimeoutException e) { /*expected*/}
140+ } finally {
141+ completeRequests(requests);
142+ cluster.close();
79143 }
80- assertThat(timedOut).isTrue();
81144 }
82145
83146 /**
@@ -89,31 +152,44 @@
89152 * @test_category connection:connection_pool
90153 */
91154 @Test(groups = "short")
92- public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException {
93- HostConnectionPool pool = createPool(1, 2);
94-
95- assertThat(pool.connections.size()).isEqualTo(1);
96- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
97-
98- //
99- for (int i = 0; i < 128; i++) {
100- Connection connection = pool.borrowConnection(100, MILLISECONDS);
101- assertThat(coreConnections).contains(connection);
102- }
103-
104- // Borrow more and ensure the connection returned is a non-core connection.
105- for (int i = 0; i < 128; i++) {
106- Connection connection = pool.borrowConnection(100, MILLISECONDS);
107- assertThat(coreConnections).doesNotContain(connection);
108- }
109-
110- boolean timedOut = false;
155+ public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
156+ Cluster cluster = createClusterBuilder().build();
157+ List<MockRequest> requests = newArrayList();
111158 try {
112- pool.borrowConnection(100, MILLISECONDS);
113- } catch (TimeoutException e) {
114- timedOut = true;
159+ HostConnectionPool pool = createPool(cluster, 1, 2);
160+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
161+ cluster.manager.connectionFactory = factory;
162+
163+ assertThat(pool.connections.size()).isEqualTo(1);
164+ List<Connection> coreConnections = newArrayList(pool.connections);
165+
166+ // Fill enough connections to hit the threshold.
167+ requests.addAll(fillConnectionToThreshold(pool, coreConnections));
168+
169+ // Allow time for new connection to be spawned.
170+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
171+
172+ // Borrow more and ensure the connection returned is a non-core connection.
173+ for (int i = 0; i < 100; i++) {
174+ MockRequest request = MockRequest.send(pool);
175+ assertThat(coreConnections).doesNotContain(request.connection);
176+ requests.add(request);
177+ }
178+
179+ // Fill remaining connections (28 + 28) - 1
180+ requests.addAll(sendRequests(55, pool));
181+
182+ boolean timedOut = false;
183+ try {
184+ MockRequest.send(pool);
185+ } catch (TimeoutException e) {
186+ timedOut = true;
187+ }
188+ assertThat(timedOut).isTrue();
189+ } finally {
190+ completeRequests(requests);
191+ cluster.close();
115192 }
116- assertThat(timedOut).isTrue();
117193 }
118194
119195 /**
@@ -124,22 +200,25 @@
124200 * @test_category connection:connection_pool
125201 */
126202 @Test(groups = "short")
127- public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException {
128- cluster.getConfiguration().getPoolingOptions()
129- .setIdleTimeoutSeconds(20);
130-
131- HostConnectionPool pool = createPool(1, 2);
132- Connection core = pool.connections.get(0);
133-
134- // Fill core connection
135- for (int i = 0; i < 128; i++)
136- assertThat(
137- pool.borrowConnection(100, MILLISECONDS)
138- ).isEqualTo(core);
139-
140- // Reaching 128 on the core connection should have triggered the creation of an extra one
141- TimeUnit.MILLISECONDS.sleep(100);
142- assertThat(pool.connections).hasSize(2);
203+ public void should_add_extra_connection_when_core_full() throws Exception {
204+ Cluster cluster = createClusterBuilder().build();
205+ List<MockRequest> requests = newArrayList();
206+ try {
207+ HostConnectionPool pool = createPool(cluster, 1, 2);
208+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
209+ cluster.manager.connectionFactory = factory;
210+ Connection core = pool.connections.get(0);
211+
212+ // Fill core connection + 1
213+ requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
214+
215+ // Reaching the threshold should have triggered the creation of an extra one
216+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
217+ assertThat(pool.connections).hasSize(2);
218+ } finally {
219+ completeRequests(requests);
220+ cluster.close();
221+ }
143222 }
144223
145224 /**
@@ -151,52 +230,55 @@
151230 * @test_category connection:connection_pool
152231 */
153232 @Test(groups = "long")
154- public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
155- cluster.getConfiguration().getPoolingOptions()
156- .setIdleTimeoutSeconds(20);
157-
158- HostConnectionPool pool = createPool(1, 2);
159- Connection connection1 = pool.connections.get(0);
160-
161- for (int i = 0; i < 101; i++)
162- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
163-
164- TimeUnit.MILLISECONDS.sleep(100);
165- assertThat(pool.connections).hasSize(2);
166- Connection connection2 = pool.connections.get(1);
167-
168- assertThat(connection1.inFlight.get()).isEqualTo(101);
169- assertThat(connection2.inFlight.get()).isEqualTo(0);
170-
171- // Go back under the capacity of 1 connection
172- for (int i = 0; i < 51; i++)
173- pool.returnConnection(connection1);
174-
175- assertThat(connection1.inFlight.get()).isEqualTo(50);
176- assertThat(connection2.inFlight.get()).isEqualTo(0);
177-
178- // Given enough time, one connection gets trashed (and the implementation picks the first one)
179- TimeUnit.SECONDS.sleep(20);
180- assertThat(pool.connections).containsExactly(connection2);
181- assertThat(pool.trash).containsExactly(connection1);
182-
183- // Now borrow enough to go just under the 1 connection threshold
184- for (int i = 0; i < 50; i++)
185- pool.borrowConnection(100, MILLISECONDS);
186-
187- assertThat(pool.connections).containsExactly(connection2);
188- assertThat(pool.trash).containsExactly(connection1);
189- assertThat(connection1.inFlight.get()).isEqualTo(50);
190- assertThat(connection2.inFlight.get()).isEqualTo(50);
191-
192- // Borrowing one more time should resurrect the trashed connection
193- pool.borrowConnection(100, MILLISECONDS);
194- TimeUnit.MILLISECONDS.sleep(100);
195-
196- assertThat(pool.connections).containsExactly(connection2, connection1);
197- assertThat(pool.trash).isEmpty();
198- assertThat(connection1.inFlight.get()).isEqualTo(50);
199- assertThat(connection2.inFlight.get()).isEqualTo(51);
233+ public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
234+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
235+ List<MockRequest> requests = newArrayList();
236+ try {
237+ HostConnectionPool pool = createPool(cluster, 1, 2);
238+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
239+ cluster.manager.connectionFactory = factory;
240+ Connection connection1 = pool.connections.get(0);
241+
242+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
243+
244+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
245+ assertThat(pool.connections).hasSize(2);
246+ Connection connection2 = pool.connections.get(1);
247+
248+ assertThat(connection1.inFlight.get()).isEqualTo(101);
249+ assertThat(connection2.inFlight.get()).isEqualTo(0);
250+
251+ // Go back under the capacity of 1 connection
252+ completeRequests(51, requests);
253+
254+ assertThat(connection1.inFlight.get()).isEqualTo(50);
255+ assertThat(connection2.inFlight.get()).isEqualTo(0);
256+
257+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
258+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
259+ assertThat(pool.connections).containsExactly(connection2);
260+ assertThat(pool.trash).containsExactly(connection1);
261+
262+ // Now borrow enough to go just under the 1 connection threshold
263+ requests.addAll(sendRequests(50, pool));
264+
265+ assertThat(pool.connections).containsExactly(connection2);
266+ assertThat(pool.trash).containsExactly(connection1);
267+ assertThat(connection1.inFlight.get()).isEqualTo(50);
268+ assertThat(connection2.inFlight.get()).isEqualTo(50);
269+
270+ // Borrowing one more time should resurrect the trashed connection
271+ requests.addAll(sendRequests(1, pool));
272+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
273+
274+ assertThat(pool.connections).containsExactly(connection2, connection1);
275+ assertThat(pool.trash).isEmpty();
276+ assertThat(connection1.inFlight.get()).isEqualTo(50);
277+ assertThat(connection2.inFlight.get()).isEqualTo(51);
278+ } finally {
279+ completeRequests(requests);
280+ cluster.close();
281+ }
200282 }
201283
202284 /**
@@ -208,157 +290,674 @@
208290 * @test_category connection:connection_pool
209291 */
210292 @Test(groups = "long")
211- public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
212- cluster.getConfiguration().getPoolingOptions()
213- .setIdleTimeoutSeconds(20);
293+ public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
294+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
295+ List<MockRequest> requests = newArrayList();
296+ try {
297+ HostConnectionPool pool = createPool(cluster, 1, 2);
298+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
299+ cluster.manager.connectionFactory = factory;
300+ Connection connection1 = pool.connections.get(0);
301+
302+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
303+
304+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
305+ reset(factory);
306+ assertThat(pool.connections).hasSize(2);
307+ Connection connection2 = pool.connections.get(1);
308+
309+ assertThat(connection1.inFlight.get()).isEqualTo(101);
310+ assertThat(connection2.inFlight.get()).isEqualTo(0);
311+
312+ // Go back under the capacity of 1 connection
313+ completeRequests(51, requests);
314+
315+ assertThat(connection1.inFlight.get()).isEqualTo(50);
316+ assertThat(connection2.inFlight.get()).isEqualTo(0);
317+
318+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
319+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
320+ assertThat(pool.connections).containsExactly(connection2);
321+ assertThat(pool.trash).containsExactly(connection1);
322+
323+ // Return trashed connection down to 0 inFlight
324+ completeRequests(50, requests);
325+ assertThat(connection1.inFlight.get()).isEqualTo(0);
326+
327+ // Give enough time for trashed connection to be cleaned up from the trash:
328+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
329+ assertThat(pool.connections).containsExactly(connection2);
330+ assertThat(pool.trash).isEmpty();
331+ assertThat(connection1.isClosed()).isTrue();
332+
333+ // Fill the live connection to go over the threshold where a second one is needed
334+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2)));
335+ assertThat(connection2.inFlight.get()).isEqualTo(101);
336+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
337+
338+ // Borrow again to get the new connection
339+ MockRequest request = MockRequest.send(pool);
340+ requests.add(request);
341+ assertThat(request.connection)
342+ .isNotEqualTo(connection2) // should not be the full connection
343+ .isNotEqualTo(connection1); // should not be the previously trashed one
344+ } finally {
345+ completeRequests(requests);
346+ cluster.close();
347+ }
348+ }
349+
350+ /**
351+ * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
352+ *
353+ * @since 2.0.10, 2.1.6
354+ * @jira_ticket JAVA-419
355+ * @test_category connection:connection_pool
356+ */
357+ @Test(groups = "long")
358+ public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
359+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
360+ List<MockRequest> requests = newArrayList();
361+
362+ try {
363+ HostConnectionPool pool = createPool(cluster, 1, 2);
364+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
365+ cluster.manager.connectionFactory = factory;
366+ Connection connection1 = pool.connections.get(0);
367+
368+ // Fill core connection enough to trigger creation of another one
369+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
370+
371+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
372+ assertThat(pool.connections).hasSize(2);
373+
374+ // Return enough times to get back under the threshold where one connection is enough
375+ completeRequests(50, requests);
376+
377+ // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
378+ // It still has in-flight requests so should not get closed.
379+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
380+ assertThat(pool.trash).containsExactly(connection1);
381+ assertThat(connection1.inFlight.get()).isEqualTo(51);
382+ assertThat(connection1.isClosed()).isFalse();
383+
384+ // Consume all inFlight requests on the trashed connection.
385+ completeRequests(51, requests);
386+
387+ // Sleep enough time for the connection to be consider idled and closed.
388+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
389+
390+ // The connection should be now closed.
391+ // The trashed connection should be closed and not in the pool or trash.
392+ assertThat(connection1.isClosed()).isTrue();
393+ assertThat(pool.connections).doesNotContain(connection1);
394+ assertThat(pool.trash).doesNotContain(connection1);
395+ } finally {
396+ completeRequests(requests);
397+ cluster.close();
398+ }
399+ }
400+
401+ /**
402+ * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
403+ * the connection is put in the trash.
404+ *
405+ * @since 2.0.10, 2.1.6
406+ * @jira_ticket JAVA-419
407+ * @test_category connection:connection_pool
408+ */
409+ @Test(groups = "short")
410+ public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
411+ Cluster cluster = createClusterBuilder().build();
412+ List<MockRequest> requests = newArrayList();
413+ try {
414+ HostConnectionPool pool = createPool(cluster, 1, 2);
415+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
416+ cluster.manager.connectionFactory = factory;
417+ Connection core = pool.connections.get(0);
418+
419+ requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
420+
421+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
422+ assertThat(pool.connections).hasSize(2);
423+
424+ // Grab the new non-core connection and replace it with a spy.
425+ Connection extra1 = spy(pool.connections.get(1));
426+ pool.connections.set(1, extra1);
427+
428+ // Borrow 10 times to ensure pool is utilized.
429+ requests.addAll(sendRequests(10, pool));
430+ assertThat(pool.connections).hasSize(2);
431+
432+ // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
433+ // this should cause the connection to be replaced and trashed on returnConnection.
434+ doReturn(0).when(extra1).maxAvailableStreams();
435+
436+ // On returning of the connection, should detect that there are no available streams and trash it.
437+ assertThat(pool.trash).hasSize(0);
438+ pool.returnConnection(extra1);
439+ assertThat(pool.connections).hasSize(1);
440+ assertThat(pool.trash).hasSize(1);
441+ } finally {
442+ completeRequests(requests);
443+ cluster.close();
444+ }
445+ }
446+
447+ /**
448+ * Ensures that if a connection on a host is lost but other connections remain intact in the Pool that the
449+ * host is not marked down.
450+ *
451+ * @jira_ticket JAVA-544
452+ * @test_category connection:connection_pool
453+ * @since 2.0.11
454+ */
455+ @Test(groups="short")
456+ public void should_keep_host_up_when_one_connection_lost() throws Exception {
457+ Cluster cluster = createClusterBuilder().build();
458+ try {
459+ HostConnectionPool pool = createPool(cluster, 2, 2);
460+ Connection core0 = pool.connections.get(0);
461+ Connection core1 = pool.connections.get(1);
462+
463+ // Drop a connection and ensure the host stays up.
464+ currentClient.disableListener();
465+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
466+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
467+
468+ // connection 0 should be down, while connection 1 and the Host should remain up.
469+ assertThat(core0.isClosed()).isTrue();
470+ assertThat(core1.isClosed()).isFalse();
471+ assertThat(pool.connections).doesNotContain(core0);
472+ assertThat(cluster).host(1).hasState(Host.State.UP);
473+ assertThat(cluster).hasOpenControlConnection();
474+ } finally {
475+ cluster.close();
476+ }
477+ }
214478
215- HostConnectionPool pool = createPool(1, 2);
216- Connection connection1 = pool.connections.get(0);
217479
218- for (int i = 0; i < 101; i++)
219- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
480+ /**
481+ * Ensures that if all connections on a host are closed that the host is marked
482+ * down and the control connection is notified of that fact and re-established
483+ * itself.
484+ *
485+ * @jira_ticket JAVA-544
486+ * @test_category connection:connection_pool
487+ * @since 2.0.11
488+ */
489+ @Test(groups="short")
490+ public void should_mark_host_down_when_no_connections_remaining() throws Exception {
491+ int readTimeout = 1000;
492+ int reconnectInterval = 1000;
493+ Cluster cluster = this.createClusterBuilder()
494+ .withSocketOptions(new SocketOptions()
495+ .setConnectTimeoutMillis(readTimeout)
496+ .setReadTimeoutMillis(reconnectInterval))
497+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
498+ try {
499+ cluster.init();
220500
221- TimeUnit.MILLISECONDS.sleep(100);
222- assertThat(pool.connections).hasSize(2);
223- Connection connection2 = pool.connections.get(1);
501+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
502+ cluster.manager.connectionFactory = factory;
224503
225- assertThat(connection1.inFlight.get()).isEqualTo(101);
226- assertThat(connection2.inFlight.get()).isEqualTo(0);
504+ HostConnectionPool pool = createPool(cluster, 8,8);
505+ // copy list to track these connections.
506+ List<Connection> connections = newArrayList(pool.connections);
227507
228- // Go back under the capacity of 1 connection
229- for (int i = 0; i < 51; i++)
230- pool.returnConnection(connection1);
508+ reset(factory);
231509
232- assertThat(connection1.inFlight.get()).isEqualTo(50);
233- assertThat(connection2.inFlight.get()).isEqualTo(0);
510+ // Drop all connections.
511+ currentClient.disableListener();
512+ currentClient.closeConnections(CLOSE);
234513
235- // Given enough time, one connection gets trashed (and the implementation picks the first one)
236- TimeUnit.SECONDS.sleep(20);
237- assertThat(pool.connections).containsExactly(connection2);
238- assertThat(pool.trash).containsExactly(connection1);
514+ // The host should be marked down and the control connection closed.
515+ assertThat(cluster).host(1).goesDownWithin(10, TimeUnit.SECONDS);
516+ assertThat(cluster).hasClosedControlConnection();
239517
240- // Return trashed connection down to 0 inFlight
241- for (int i = 0; i < 50; i++)
242- pool.returnConnection(connection1);
243- assertThat(connection1.inFlight.get()).isEqualTo(0);
518+ // Ensure all connections are closed.
519+ for(Connection connection : connections) {
520+ assertThat(connection.isClosed()).isTrue();
521+ }
244522
245- // Give enough time for trashed connection to be cleaned up from the trash:
246- TimeUnit.SECONDS.sleep(30);
247- assertThat(pool.connections).containsExactly(connection2);
248- assertThat(pool.trash).isEmpty();
249- assertThat(connection1.isClosed()).isTrue();
523+ // Expect a reconnect attempt on host after reconnect interval
524+ // on behalf of the control connection.
525+ verify(factory, timeout(reconnectInterval*2).atLeastOnce()).open(host);
526+
527+ // Sleep for a bit to allow reconnect to fail.
528+ Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
529+
530+ // Ensure control connection is still closed.
531+ assertThat(cluster).hasClosedControlConnection();
532+
533+ // Reenable connectivity.
534+ currentClient.enableListener();
535+
536+ // Reconnect attempt should have been connected for control connection
537+ // and pool.
538+ // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
539+ verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
540+ // 7 attempts for core connections after first initial connection.
541+ verify(factory, timeout(reconnectInterval*2).times(7)).newConnection(any(HostConnectionPool.class));
542+
543+ // Wait some reasonable amount of time for connection to reestablish.
544+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
545+
546+ // Control Connection should now be open.
547+ assertThat(cluster).hasOpenControlConnection();
548+ assertThat(cluster).host(1).hasState(Host.State.UP);
549+ } finally {
550+ cluster.close();
551+ }
552+ }
250553
251- // Fill the live connection to go over the threshold where a second one is needed
252- for (int i = 0; i < 101; i++)
253- assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2);
254- assertThat(connection2.inFlight.get()).isEqualTo(101);
255- TimeUnit.MILLISECONDS.sleep(100);
256554
257- // Borrow again to get the new connection
258- Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
259- assertThat(connection3)
260- .isNotEqualTo(connection2) // should not be the full connection
261- .isNotEqualTo(connection1); // should not be the previously trashed one
555+ /**
556+ * Ensures that if a connection on a host is lost that brings the number of active connections in a pool
557+ * under core connection count that up to core connections are re-established, but only after the
558+ * next reconnect schedule has elapsed.
559+ *
560+ * @jira_ticket JAVA-544
561+ * @test_category connection:connection_pool
562+ * @since 2.0.11
563+ */
564+ @Test(groups="short")
565+ public void should_create_new_connections_when_connection_lost_and_under_core_connections() throws Exception {
566+ int readTimeout = 1000;
567+ int reconnectInterval = 1000;
568+ Cluster cluster = this.createClusterBuilder()
569+ .withSocketOptions(new SocketOptions()
570+ .setConnectTimeoutMillis(readTimeout)
571+ .setReadTimeoutMillis(reconnectInterval))
572+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
573+ List<MockRequest> requests = newArrayList();
574+ try {
575+ cluster.init();
576+
577+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
578+ cluster.manager.connectionFactory = factory;
579+
580+ HostConnectionPool pool = createPool(cluster, 3, 3);
581+ Connection core0 = pool.connections.get(0);
582+ Connection core1 = pool.connections.get(1);
583+ Connection core2 = pool.connections.get(2);
584+
585+ // Drop two core connections.
586+ // Disable new connections initially and we'll eventually reenable it.
587+ currentClient.disableListener();
588+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
589+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core2.channel.localAddress()));
590+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
591+
592+ // Since we have a connection left the host should remain up.
593+ assertThat(cluster).host(1).hasState(Host.State.UP);
594+ assertThat(pool.connections).hasSize(1);
595+
596+ // The borrowed connection should be the open one.
597+ MockRequest request = MockRequest.send(pool);
598+ requests.add(request);
599+ assertThat(request.connection).isEqualTo(core1);
600+
601+ // Should not have tried to create a new core connection since reconnection time had not elapsed.
602+ verify(factory, never()).open(any(HostConnectionPool.class));
603+
604+ // Sleep to elapse the Reconnection Policy.
605+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
606+
607+ // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection.
608+ request = MockRequest.send(pool);
609+ requests.add(request);
610+ assertThat(request.connection).isEqualTo(core1);
611+
612+ // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core.
613+ verify(factory, timeout(reconnectInterval).times(1)).open(any(HostConnectionPool.class));
614+ reset(factory);
615+
616+ // Sleep for reconnect interval to allow reconnection time to elapse.
617+ Uninterruptibles.sleepUninterruptibly((readTimeout + reconnectInterval) * 2, TimeUnit.MILLISECONDS);
618+
619+ // Enable listening so new connections succeed.
620+ currentClient.enableListener();
621+ // Sleep to elapse the Reconnection Policy.
622+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
623+
624+ // Try to borrow a connection, the pool should grow.
625+ requests.add(MockRequest.send(pool));
626+ verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
627+ reset(factory);
628+
629+ // Another core connection should be opened as result of another request to get us up to core connections.
630+ requests.add(MockRequest.send(pool));
631+ verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
632+ reset(factory);
633+
634+ // Sending another request should not grow the pool any more, since we are now at core connections.
635+ requests.add(MockRequest.send(pool));
636+ verify(factory, after((reconnectInterval + readTimeout) * 2).never()).open(any(HostConnectionPool.class));
637+ } finally {
638+ completeRequests(requests);
639+ cluster.close();
640+ }
262641 }
263642
264643 /**
265- * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
644+ * Ensures that if a connection on a host is lost and the number of remaining connections is at
645+ * core connection count that no connections are re-established until after there are enough
646+ * inflight requests to justify creating one and the reconnection interval has elapsed.
266647 *
267- * @since 2.0.10, 2.1.6
268- * @jira_ticket JAVA-419
648+ * @jira_ticket JAVA-544
269649 * @test_category connection:connection_pool
650+ * @since 2.0.11
270651 */
271- @Test(groups = "long")
272- public void should_not_close_trashed_connection_until_no_in_flight()
273- throws ConnectionException, TimeoutException, InterruptedException {
274- cluster.getConfiguration().getPoolingOptions()
275- .setIdleTimeoutSeconds(20);
652+ @Test(groups = "short")
653+ public void should_not_schedule_reconnect_when_connection_lost_and_at_core_connections() throws Exception {
654+ int readTimeout = 1000;
655+ int reconnectInterval = 1000;
656+ Cluster cluster = this.createClusterBuilder()
657+ .withSocketOptions(new SocketOptions()
658+ .setConnectTimeoutMillis(readTimeout)
659+ .setReadTimeoutMillis(reconnectInterval))
660+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
661+ List<MockRequest> requests = newArrayList();
662+ try {
663+ cluster.init();
664+
665+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
666+ cluster.manager.connectionFactory = factory;
667+
668+ HostConnectionPool pool = createPool(cluster, 1, 2);
669+ Connection core0 = pool.connections.get(0);
670+
671+ // Create enough inFlight requests to spawn another connection.
672+ List<MockRequest> core0requests = newArrayList();
673+ for (int i = 0; i < 101; i++) {
674+ MockRequest request = MockRequest.send(pool);
675+ assertThat(request.connection).isEqualTo(core0);
676+ core0requests.add(request);
677+ }
276678
277- HostConnectionPool pool = createPool(1, 2);
278- Connection connection1 = pool.connections.get(0);
679+ // Pool should grow by 1.
680+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
681+ assertThat(pool.connections).hasSize(2);
279682
280- // Fill core connection enough to trigger creation of another one
281- for (int i = 0; i < 110; i++)
282- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
683+ // Reset factory mock as we'll be checking for new open() invokes later.
684+ reset(factory);
283685
284- TimeUnit.MILLISECONDS.sleep(100);
285- assertThat(pool.connections).hasSize(2);
686+ // Grab the new non-core connection.
687+ Connection extra1 = pool.connections.get(1);
286688
287- // Return enough times to get back under the threshold where one connection is enough
288- for (int i = 0; i < 50; i++)
289- pool.returnConnection(connection1);
689+ // Drop a connection and disable listening.
690+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
691+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
692+ currentClient.disableListener();
290693
291- // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
292- // It still has in-flight requests so should not get closed.
293- TimeUnit.SECONDS.sleep(30);
294- assertThat(pool.trash).containsExactly(connection1);
295- assertThat(connection1.inFlight.get()).isEqualTo(60);
296- assertThat(connection1.isClosed()).isFalse();
694+ // Since core0 was closed, all of it's requests should have errored.
695+ for(MockRequest request : core0requests) {
696+ verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
697+ }
297698
298- // Consume all inFlight requests on the trashed connection.
299- while (connection1.inFlight.get() > 0) {
300- pool.returnConnection(connection1);
699+ assertThat(cluster).host(1).hasState(Host.State.UP);
700+
701+ // Create enough inFlight requests to fill connection.
702+ requests.addAll(sendRequests(100, pool, singletonList(extra1)));
703+ assertThat(pool.connections).hasSize(1);
704+
705+ // A new connection should never have been spawned since we didn't max out core.
706+ verify(factory, after(readTimeout).never()).open(any(HostConnectionPool.class));
707+
708+ // Borrow another connection, since we exceed max another connection should be opened.
709+ MockRequest request = MockRequest.send(pool);
710+ requests.add(request);
711+ assertThat(request.connection).isEqualTo(extra1);
712+
713+ // After some time the a connection should attempt to be opened (but will fail).
714+ verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
715+ assertThat(pool.connections).hasSize(1);
716+
717+ // Wait some reasonable amount of time for connection to reestablish then check pool size.
718+ Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
719+ // Reconnecting failed since listening was enabled.
720+ assertThat(pool.connections).hasSize(1);
721+
722+ // Re enable listening then wait for reconnect.
723+ currentClient.enableListener();
724+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
725+
726+ // Borrow another connection, since we exceed max another connection should be opened.
727+ request = MockRequest.send(pool);
728+ requests.add(request);
729+ assertThat(request.connection).isEqualTo(extra1);
730+
731+ // Wait some reasonable amount of time for connection to reestablish then check pool size.
732+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
733+ // Reconnecting should have exceeded and pool will have grown.
734+ assertThat(pool.connections).hasSize(2);
735+
736+ // Borrowed connection should be the newly spawned connection since the other one has some inflight requests.
737+ request = MockRequest.send(pool);
738+ requests.add(request);
739+ assertThat(request.connection).isNotEqualTo(core0).isNotEqualTo(extra1);
740+ } finally {
741+ completeRequests(requests);
742+ cluster.close();
301743 }
744+ }
302745
303- // Sleep enough time for the connection to be consider idled and closed.
304- TimeUnit.SECONDS.sleep(30);
305-
306- // The connection should be now closed.
307- // The trashed connection should be closed and not in the pool or trash.
308- assertThat(connection1.isClosed()).isTrue();
309- assertThat(pool.connections).doesNotContain(connection1);
310- assertThat(pool.trash).doesNotContain(connection1);
746+ /**
747+ * Ensures that if some connections fail on pool init that the host and subsequently the
748+ * control connection is not marked down. The test also ensures that when making requests
749+ * on the pool that connections are brought up to core.
750+ *
751+ * @jira_ticket JAVA-544
752+ * @test_category connection:connection_pool
753+ * @since 2.0.11
754+ */
755+ @Test(groups="short")
756+ public void should_not_mark_host_down_if_some_connections_fail_on_init() throws Exception {
757+ int readTimeout = 1000;
758+ int reconnectInterval = 1000;
759+ Cluster cluster = this.createClusterBuilder()
760+ .withSocketOptions(new SocketOptions()
761+ .setConnectTimeoutMillis(readTimeout)
762+ .setReadTimeoutMillis(reconnectInterval))
763+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
764+ List<MockRequest> requests = newArrayList();
765+ try {
766+ cluster.init();
767+
768+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
769+ cluster.manager.connectionFactory = factory;
770+
771+ // Allow the first 4 connections to establish, but disable after that.
772+ currentClient.disableListener(4);
773+ HostConnectionPool pool = createPool(cluster, 8, 8);
774+
775+ reset(factory);
776+
777+ // Pool size should show all successful connections.
778+ assertThat(pool.connections).hasSize(4);
779+
780+ // Control connection should remain up in addition to to host.
781+ assertThat(cluster).host(1).hasState(Host.State.UP);
782+ assertThat(cluster).hasOpenControlConnection();
783+
784+ // Reenable listener, wait reconnectInterval and then try borrowing a connection.
785+ currentClient.enableListener();
786+
787+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
788+
789+ // Should open up to core connections, however it will only spawn up to 1 connection
790+ // per request, so we need to make enough requests to make up the deficit. Additionally
791+ // we need to wait for connections to be established between requests for the pool
792+ // to spawn new connections (since it only allows one simultaneous creation).
793+ for (int i = 5; i <= 8; i++) {
794+ requests.add(MockRequest.send(pool));
795+ verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
796+ reset(factory);
797+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
798+ assertThat(pool.connections).hasSize(i);
799+ }
800+ } finally {
801+ completeRequests(requests);
802+ cluster.close();
803+ }
311804 }
312805
313806 /**
314- * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
315- * the connection is put in the trash.
807+ * Ensures that if all connections fail on pool init that the host and subsequently the
808+ * control connection is not marked down since the control connection is still active.
809+ * on the pool that a TimeoutException is yielded if we are still in the reconnection window
810+ * according to the ConvictionPolicy.
316811 *
317- * @since 2.0.10, 2.1.6
318- * @jira_ticket JAVA-419
812+ * @jira_ticket JAVA-544
319813 * @test_category connection:connection_pool
814+ * @since 2.0.11
320815 */
321- @Test(groups = "short")
322- public void should_trash_on_returning_connection_with_insufficient_streams()
323- throws ConnectionException, TimeoutException, InterruptedException {
324- HostConnectionPool pool = createPool(1, 2);
325- Connection core = pool.connections.get(0);
816+ @Test(groups = "short", expectedExceptions = TimeoutException.class)
817+ public void should_throw_exception_if_convicted_and_no_connections_available() throws Exception {
818+ int readTimeout = 1000;
819+ int reconnectInterval = 1000;
820+ Cluster cluster = this.createClusterBuilder()
821+ .withSocketOptions(new SocketOptions()
822+ .setConnectTimeoutMillis(readTimeout)
823+ .setReadTimeoutMillis(reconnectInterval))
824+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
825+ try {
826+ // Init cluster so control connection is created.
827+ cluster.init();
828+ assertThat(cluster).hasOpenControlConnection();
829+
830+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
831+ cluster.manager.connectionFactory = factory;
326832
327- for (int i = 0; i < 128; i++)
328- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
833+ // Disable listener so all connections on pool fail.
834+ currentClient.disableListener();
835+ HostConnectionPool pool = createPool(cluster, 8, 8);
329836
330- TimeUnit.MILLISECONDS.sleep(100);
331- assertThat(pool.connections).hasSize(2);
837+ reset(factory);
332838
333- // Grab the new non-core connection and replace it with a spy.
334- Connection extra1 = spy(pool.connections.get(1));
335- pool.connections.set(1, extra1);
839+ // Pool should be empty.
840+ assertThat(pool.connections).hasSize(0);
336841
337- // Borrow 10 times to ensure pool is utilized.
338- for (int i = 0; i < 10; i++) {
339- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1);
842+ // Control connection should stay up with the host.
843+ assertThat(cluster).host(1).hasState(Host.State.UP);
844+ assertThat(cluster).hasOpenControlConnection();
845+
846+ MockRequest.send(pool);
847+ } finally {
848+ cluster.close();
340849 }
850+ }
341851
342- // Return connection, it should not be trashed since it still has 9 inflight requests.
343- pool.returnConnection(extra1);
344- assertThat(pool.connections).hasSize(2);
345852
346- // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
347- // this should cause the connection to be replaced and trashed on returnConnection.
348- doReturn(0).when(extra1).maxAvailableStreams();
853+ /**
854+ * Ensures that if all connections fail on pool init that the host and subsequently the
855+ * control connection is not marked down. The test also ensures that when making requests
856+ * on the pool after the conviction period that all core connections are created.
857+ *
858+ * @jira_ticket JAVA-544
859+ * @test_category connection:connection_pool
860+ * @since 2.0.11
861+ */
862+ @Test(groups="short")
863+ public void should_wait_on_connection_if_not_convicted_and_no_connections_available() throws Exception {
864+ int readTimeout = 1000;
865+ int reconnectInterval = 1000;
866+ Cluster cluster = this.createClusterBuilder()
867+ .withSocketOptions(new SocketOptions()
868+ .setConnectTimeoutMillis(readTimeout)
869+ .setReadTimeoutMillis(reconnectInterval))
870+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
871+ try {
872+ // Init cluster so control connection is created.
873+ cluster.init();
874+ assertThat(cluster).hasOpenControlConnection();
875+
876+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
877+ cluster.manager.connectionFactory = factory;
878+
879+ // Disable listener so all connections on pool fail.
880+ currentClient.disableListener();
881+ HostConnectionPool pool = createPool(cluster, 8, 8);
882+
883+ // Pool should be empty.
884+ assertThat(pool.connections).hasSize(0);
885+
886+ // Control connection should stay up with the host.
887+ assertThat(cluster).host(1).hasState(Host.State.UP);
888+ assertThat(cluster).hasOpenControlConnection();
889+
890+ currentClient.enableListener();
891+
892+ // Wait for reconnectInterval so ConvictionPolicy allows connection to be created.
893+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
894+
895+ reset(factory);
896+ MockRequest request = MockRequest.send(pool);
897+ request.simulateSuccessResponse();
898+
899+ // Should create up to core connections.
900+ verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class));
901+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
902+ assertThat(pool.connections).hasSize(8);
903+ } finally {
904+ cluster.close();
905+ }
906+ }
349907
350- // On returning of the connection, should detect that there are no available streams and trash it.
351- pool.returnConnection(extra1);
352- assertThat(pool.connections).hasSize(1);
908+ /**
909+ * Ensures that if a pool is created with zero core connections that when a request
910+ * is first sent that one and only one connection is created and that it waits on availability
911+ * of that connection and returns it.
912+ *
913+ * @jira_ticket JAVA-544
914+ * @test_category connection:connection_pool
915+ * @since 2.0.11
916+ */
917+ @Test(groups="short")
918+ public void should_wait_on_connection_if_zero_core_connections() throws Exception {
919+ int readTimeout = 1000;
920+ int reconnectInterval = 1000;
921+ Cluster cluster = this.createClusterBuilder()
922+ .withSocketOptions(new SocketOptions()
923+ .setConnectTimeoutMillis(readTimeout)
924+ .setReadTimeoutMillis(reconnectInterval))
925+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
926+ try {
927+ // Init cluster so control connection is created.
928+ cluster.init();
929+ assertThat(cluster).hasOpenControlConnection();
930+
931+ HostConnectionPool pool = createPool(cluster, 0, 2);
932+
933+ // Pool should be empty.
934+ assertThat(pool.connections).hasSize(0);
935+
936+ // Control connection should stay up with the host.
937+ assertThat(cluster).host(1).hasState(Host.State.UP);
938+ assertThat(cluster).hasOpenControlConnection();
939+
940+ // Send a request, this should create a connection.
941+ MockRequest request = MockRequest.send(pool);
942+ request.simulateSuccessResponse();
943+
944+ // Should create up to core connections.
945+ assertThat(pool.connections).hasSize(1);
946+ } finally {
947+ cluster.close();
948+ }
353949 }
354950
355- private HostConnectionPool createPool(int coreConnections, int maxConnections) {
951+ private HostConnectionPool createPool(Cluster cluster, int coreConnections, int maxConnections) {
356952 cluster.getConfiguration().getPoolingOptions()
357- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
358- .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
953+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
954+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
359955 Session session = cluster.connect();
360956 Host host = TestUtils.findHost(cluster, 1);
361- return (HostConnectionPool)((SessionManager)session).pools.get(host);
957+
958+ // Replace the existing pool with a spy pool and return it.
959+ SessionManager sm = ((SessionManager)session);
960+ return sm.pools.get(host);
362961 }
363962
364963 /**
@@ -404,7 +1003,8 @@
4041003 // Insert 100k lines in a newly created 1k columns table
4051004 PreparedStatement insertStatement = session.prepare(generateJava349InsertStatement());
4061005 for (int key = 0; key < numberOfInserts; key++) {
407- session.executeAsync(insertStatement.bind(key)).addListener(progressReporter, progressReportExecutor);
1006+ ResultSetFuture future = session.executeAsync(insertStatement.bind(key));
1007+ future.addListener(progressReporter, progressReportExecutor);
4081008 }
4091009
4101010 // Wait for all inserts to happen and stop connections and progress tracking
@@ -427,6 +1027,81 @@
4271027 sb.append(", ").append(i);
4281028 }
4291029 sb.append(");");
1030+
1031+ PrimingRequest preparedStatementPrime = PrimingRequest.preparedStatementBuilder()
1032+ .withQuery(sb.toString())
1033+ .withThen(then().withVariableTypes(PrimitiveType.INT))
1034+ .build();
1035+ primingClient.prime(preparedStatementPrime);
4301036 return sb.toString();
4311037 }
1038+
1039+ /** Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections). */
1040+ static class MockRequest implements Connection.ResponseCallback {
1041+
1042+ enum State { START, COMPLETED, FAILED, TIMED_OUT }
1043+
1044+ final Connection connection;
1045+ private Connection.ResponseHandler responseHandler;
1046+
1047+ private final AtomicReference<State> state = new AtomicReference<State>(State.START);
1048+
1049+ static MockRequest send(HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
1050+ // Create a MockRequest and spy on it. Create a response handler and add it to the connection's dispatcher.
1051+ MockRequest request = spy(new MockRequest(pool));
1052+ request.responseHandler = new Connection.ResponseHandler(request.connection, request);
1053+ request.connection.dispatcher.add(request.responseHandler);
1054+ return request;
1055+ }
1056+
1057+ private MockRequest(HostConnectionPool pool) throws ConnectionException, TimeoutException, BusyConnectionException {
1058+ connection = pool.borrowConnection(500, TimeUnit.MILLISECONDS);
1059+ }
1060+
1061+ void simulateSuccessResponse() {
1062+ onSet(connection, null, 0, 0);
1063+ }
1064+
1065+ @SuppressWarnings("unused")
1066+ void simulateErrorResponse() {
1067+ onException(connection, null, 0, 0);
1068+ }
1069+
1070+ @SuppressWarnings("unused")
1071+ void simulateTimeout() {
1072+ if (onTimeout(connection, 0, 0))
1073+ responseHandler.cancelHandler();
1074+ }
1075+
1076+ @Override
1077+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
1078+ if (state.compareAndSet(State.START, State.COMPLETED)) {
1079+ connection.release();
1080+ connection.dispatcher.removeHandler(responseHandler, true);
1081+ }
1082+ }
1083+
1084+ @Override
1085+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
1086+ if (state.compareAndSet(State.START, State.FAILED)) {
1087+ connection.release();
1088+ connection.dispatcher.removeHandler(responseHandler, true);
1089+ }
1090+ }
1091+
1092+ @Override
1093+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
1094+ return state.compareAndSet(State.START, State.TIMED_OUT);
1095+ }
1096+
1097+ @Override
1098+ public Message.Request request() {
1099+ return null; // not needed for this test class
1100+ }
1101+
1102+ @Override
1103+ public int retryCount() {
1104+ return 0; // value not important for this test class
1105+ }
1106+ }
4321107 }
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +5 −5
@@ -181,7 +181,7 @@
181181 * Test a wide row of size 1,000,000
182182 * @throws Throwable
183183 */
184- @Test(groups = "long")
184+ @Test(groups = "stress")
185185 @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle reading wide rows well.")
186186 public void wideRows() throws Throwable {
187187 Cluster.Builder builder = Cluster.builder();
@@ -205,7 +205,7 @@
205205 * Test a batch that writes a row of size 10,000
206206 * @throws Throwable
207207 */
208- @Test(groups = "short")
208+ @Test(groups = "stress")
209209 @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle large batches well.")
210210 public void wideBatchRows() throws Throwable {
211211 Cluster.Builder builder = Cluster.builder();
@@ -229,7 +229,7 @@
229229 * Test a wide row of size 1,000,000 consisting of a ByteBuffer
230230 * @throws Throwable
231231 */
232- @Test(groups = "long")
232+ @Test(groups = "stress")
233233 public void wideByteRows() throws Throwable {
234234 Cluster.Builder builder = Cluster.builder();
235235 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -252,7 +252,7 @@
252252 * Test a row with a single extra large text value
253253 * @throws Throwable
254254 */
255- @Test(groups = "short")
255+ @Test(groups = "stress")
256256 public void largeText() throws Throwable {
257257 Cluster.Builder builder = Cluster.builder();
258258 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -275,7 +275,7 @@
275275 * Creates a table with 330 columns
276276 * @throws Throwable
277277 */
278- @Test(groups = "short")
278+ @Test(groups = "stress")
279279 public void wideTable() throws Throwable {
280280 Cluster.Builder builder = Cluster.builder();
281281 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +20 −11
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetSocketAddress;
1819 import java.util.List;
1920 import java.util.Map;
2021 import java.util.Set;
@@ -93,14 +94,14 @@
9394 private static final Token TOKEN18 = token("8000000000000000000");
9495 private static final Token TOKEN19 = token("9000000000000000000");
9596
96- private static final String IP1 = "127.0.0.101";
97- private static final String IP2 = "127.0.0.102";
98- private static final String IP3 = "127.0.0.103";
99- private static final String IP4 = "127.0.0.104";
100- private static final String IP5 = "127.0.0.105";
101- private static final String IP6 = "127.0.0.106";
102- private static final String IP7 = "127.0.0.107";
103- private static final String IP8 = "127.0.0.108";
97+ private static final InetSocketAddress IP1 = socketAddress("127.0.0.101");
98+ private static final InetSocketAddress IP2 = socketAddress("127.0.0.102");
99+ private static final InetSocketAddress IP3 = socketAddress("127.0.0.103");
100+ private static final InetSocketAddress IP4 = socketAddress("127.0.0.104");
101+ private static final InetSocketAddress IP5 = socketAddress("127.0.0.105");
102+ private static final InetSocketAddress IP6 = socketAddress("127.0.0.106");
103+ private static final InetSocketAddress IP7 = socketAddress("127.0.0.107");
104+ private static final InetSocketAddress IP8 = socketAddress("127.0.0.108");
104105
105106 private static final ReplicationStrategy exampleStrategy = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2));
106107
@@ -110,10 +111,11 @@
110111 private static final Map<Token, Host> largeRingTokenToPrimary = Maps.newHashMap();
111112 static {
112113 for (int i = 0; i < 100; i++) {
114+ InetSocketAddress address = socketAddress("127.0.0." + i);
113115 for (int vnodes = 0; vnodes < 256; vnodes++) {
114116 Token token = token("" + ((i * 256) + vnodes));
115117 largeRing.add(token);
116- largeRingTokenToPrimary.put(token, host("127.0.0." + i, DC1, RACK11));
118+ largeRingTokenToPrimary.put(token, host(address, DC1, RACK11));
117119 }
118120 }
119121 }
@@ -591,13 +593,20 @@
591593 .computeTokenToReplicaMap(largeRingTokenToPrimary, largeRing);
592594 assertThat(System.currentTimeMillis() - t1).isLessThan(10000);
593595
596+ InetSocketAddress currNode = null;
597+ InetSocketAddress nextNode;
594598 for (int node = 0; node < 99; node++) { // 100th wraps so doesn't match this, check after
599+ if(currNode == null) {
600+ currNode = socketAddress("127.0.0." + node);
601+ }
602+ nextNode = socketAddress("127.0.0." + (node+1));
595603 for (int vnodes = 0; vnodes < 256; vnodes++) {
596604 Token token = token("" + ((node * 256) + vnodes));
597- assertReplicaPlacement(replicaMap, token, "127.0.0." + node, "127.0.0." + (node + 1));
605+ assertReplicaPlacement(replicaMap, token, currNode, nextNode);
598606 }
607+ currNode = nextNode;
599608 }
600- assertReplicaPlacement(replicaMap, token(""+ 99 * 256), "127.0.0.99", "127.0.0.0");
609+ assertReplicaPlacement(replicaMap, token(""+ 99 * 256), currNode, socketAddress("127.0.0.0"));
601610 }
602611
603612
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +60 −98
@@ -16,23 +16,21 @@
1616 package com.datastax.driver.core;
1717
1818 import org.apache.log4j.Logger;
19+import org.scassandra.http.client.PrimingRequest;
1920 import org.testng.annotations.AfterMethod;
2021 import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.DataProvider;
2123 import org.testng.annotations.Test;
2224
2325 import static org.apache.log4j.Level.DEBUG;
2426 import static org.apache.log4j.Level.INFO;
2527 import static org.assertj.core.api.Assertions.assertThat;
2628 import static org.assertj.core.api.Assertions.fail;
27-import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
28-import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
29-import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
29+import static org.scassandra.http.client.PrimingRequest.Result.*;
3030 import static org.scassandra.http.client.PrimingRequest.queryBuilder;
31+import static org.scassandra.http.client.PrimingRequest.then;
3132
32-import com.datastax.driver.core.exceptions.NoHostAvailableException;
33-import com.datastax.driver.core.exceptions.ReadTimeoutException;
34-import com.datastax.driver.core.exceptions.UnavailableException;
35-import com.datastax.driver.core.exceptions.WriteTimeoutException;
33+import com.datastax.driver.core.exceptions.*;
3634
3735 import static com.datastax.driver.core.QueryLogger.builder;
3836
@@ -49,38 +47,34 @@
4947 private MemoryAppender slowAppender;
5048 private MemoryAppender errorAppender;
5149
52- private QueryLogger queryLogger;
50+ private Cluster cluster = null;
51+ private Session session = null;
52+ private QueryLogger queryLogger = null;
5353
5454 @BeforeMethod(groups = { "short", "unit" })
55- public void startCapturingLogs() {
55+ public void setUp() {
56+ slow.setLevel(INFO);
57+ error.setLevel(INFO);
5658 slow.addAppender(slowAppender = new MemoryAppender());
5759 error.addAppender(errorAppender = new MemoryAppender());
60+
61+ queryLogger = null;
62+
63+ cluster = createClusterBuilder().build();
64+ session = cluster.connect();
5865 }
5966
6067 @AfterMethod(groups = { "short", "unit" })
61- public void stopCapturingLogs() {
68+ public void tearDown() {
6269 slow.setLevel(null);
6370 error.setLevel(null);
6471 slow.removeAppender(slowAppender);
6572 error.removeAppender(errorAppender);
66- }
67-
68- @BeforeMethod(groups = { "short", "unit" })
69- @AfterMethod(groups = { "short", "unit" })
70- public void resetLogLevels() {
71- slow.setLevel(INFO);
72- error.setLevel(INFO);
73- }
7473
75- @BeforeMethod(groups = { "short", "unit" })
76- public void resetQueryLogger() {
7774 queryLogger = null;
78- }
7975
80- @AfterMethod(groups = { "short", "unit" })
81- public void unregisterQueryLogger() {
82- if(cluster != null && queryLogger != null) {
83- cluster.unregister(queryLogger);
76+ if(cluster != null) {
77+ cluster.close();
8478 }
8579 }
8680
@@ -96,7 +90,7 @@
9690 primingClient.prime(
9791 queryBuilder()
9892 .withQuery(query)
99- .withFixedDelay(100)
93+ .withThen(then().withFixedDelay(100L))
10094 .build()
10195 );
10296 // when
@@ -105,7 +99,7 @@
10599 String line = slowAppender.waitAndGet(5000);
106100 assertThat(line)
107101 .contains("Query too slow")
108- .contains("127.0.0.1")
102+ .contains(ip)
109103 .contains(query);
110104 }
111105
@@ -120,7 +114,7 @@
120114 primingClient.prime(
121115 queryBuilder()
122116 .withQuery(query)
123- .withFixedDelay(100)
117+ .withThen(then().withFixedDelay(100L))
124118 .build()
125119 );
126120 // when
@@ -134,74 +128,34 @@
134128 String line = errorAppender.waitAndGet(5000);
135129 assertThat(line)
136130 .contains("Query error")
137- .contains("127.0.0.1")
131+ .contains(ip)
138132 .contains(Integer.toString(scassandra.getBinaryPort()))
139133 .contains(query)
140134 .contains(OperationTimedOutException.class.getName());
141135 }
142136
143- @Test(groups = "short")
144- public void should_log_read_timeout_errors() throws Exception {
145- // given
146- error.setLevel(DEBUG);
147- queryLogger = builder(cluster).build();
148- cluster.register(queryLogger);
149- String query = "SELECT foo FROM bar";
150- primingClient.prime(
151- queryBuilder()
152- .withQuery(query)
153- .withResult(read_request_timeout)
154- .build()
155- );
156- // when
157- try {
158- session.execute(query);
159- fail("Should have thrown ReadTimeoutException");
160- } catch (ReadTimeoutException e) {
161- // ok
162- }
163- // then
164- String line = errorAppender.waitAndGet(5000);
165- assertThat(line)
166- .contains("Query error")
167- .contains("127.0.0.1")
168- .contains(Integer.toString(scassandra.getBinaryPort()))
169- .contains(query)
170- .contains(ReadTimeoutException.class.getName());
171- }
172-
173- @Test(groups = "short")
174- public void should_log_write_timeout_errors() throws Exception {
175- // given
176- error.setLevel(DEBUG);
177- queryLogger = builder(cluster).build();
178- cluster.register(queryLogger);
179- String query = "UPDATE test SET foo = 'bar' where qix = ?";
180- primingClient.prime(
181- queryBuilder()
182- .withQuery(query)
183- .withResult(write_request_timeout)
184- .build()
185- );
186- // when
187- try {
188- session.execute(query);
189- fail("Should have thrown WriteTimeoutException");
190- } catch (WriteTimeoutException e) {
191- // ok
192- }
193- // then
194- String line = errorAppender.waitAndGet(5000);
195- assertThat(line)
196- .contains("Query error")
197- .contains("127.0.0.1")
198- .contains(Integer.toString(scassandra.getBinaryPort()))
199- .contains(query)
200- .contains(WriteTimeoutException.class.getName());
137+ @DataProvider(name="errors")
138+ public static Object[][] createErrors() {
139+ return new Object[][] {
140+ { unavailable, NoHostAvailableException.class, UnavailableException.class },
141+ { write_request_timeout, WriteTimeoutException.class, WriteTimeoutException.class },
142+ { read_request_timeout, ReadTimeoutException.class, ReadTimeoutException.class },
143+ { server_error, NoHostAvailableException.class, ServerError.class },
144+ { protocol_error, ProtocolError.class, ProtocolError.class },
145+ { bad_credentials, AuthenticationException.class, AuthenticationException.class },
146+ { overloaded, NoHostAvailableException.class, OverloadedException.class },
147+ { is_bootstrapping, NoHostAvailableException.class, BootstrappingException.class },
148+ { truncate_error, TruncateException.class, TruncateException.class },
149+ { syntax_error, SyntaxError.class, SyntaxError.class },
150+ { invalid, InvalidQueryException.class, InvalidQueryException.class },
151+ { config_error, InvalidConfigurationInQueryException.class, InvalidConfigurationInQueryException.class },
152+ { already_exists, AlreadyExistsException.class, AlreadyExistsException.class },
153+ { unprepared, DriverInternalError.class, UnpreparedException.class }
154+ };
201155 }
202156
203- @Test(groups = "short")
204- public void should_log_unavailable_errors() throws Exception {
157+ @Test(groups = "short", dataProvider="errors")
158+ public void should_log_exception_from_the_given_result(PrimingRequest.Result result, Class<? extends Exception> expectedException, Class<? extends Exception> loggedException) throws Exception {
205159 // given
206160 error.setLevel(DEBUG);
207161 queryLogger = builder(cluster).build();
@@ -210,28 +164,36 @@
210164 primingClient.prime(
211165 queryBuilder()
212166 .withQuery(query)
213- .withResult(unavailable)
167+ .withThen(then().withResult(result))
214168 .build()
215169 );
216170 // when
217- // when
218171 try {
219172 session.execute(query);
220173 fail("Should have thrown NoHostAvailableException");
221- } catch(NoHostAvailableException e) {
222- // ok
223- Throwable error = e.getErrors().get(hostAddress);
224- assertThat(error).isNotNull();
225- assertThat(error).isInstanceOf(UnavailableException.class);
174+ } catch(Exception e) {
175+ if(e instanceof NoHostAvailableException) {
176+ assertThat(expectedException).isEqualTo(NoHostAvailableException.class);
177+ // ok
178+ Throwable error = ((NoHostAvailableException)e).getErrors().get(hostAddress);
179+ assertThat(error).isNotNull();
180+ if(loggedException.getSuperclass() == DriverInternalError.class) {
181+ assertThat(error).isOfAnyClassIn(DriverException.class);
182+ } else {
183+ assertThat(error).isOfAnyClassIn(loggedException);
184+ }
185+ } else {
186+ assertThat(e).isInstanceOf(expectedException);
187+ }
226188 }
227189 // then
228190 String line = errorAppender.waitAndGet(5000);
229191 assertThat(line)
230192 .contains("Query error")
231- .contains("127.0.0.1")
193+ .contains(ip)
232194 .contains(Integer.toString(scassandra.getBinaryPort()))
233195 .contains(query)
234- .contains(UnavailableException.class.getName());
196+ .contains(loggedException.getName());
235197 }
236198
237199 }
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +4 −0
@@ -123,6 +123,10 @@
123123 activityClient.clearAllRecordedActivity();
124124 }
125125
126+ public Scassandra instance(int node) {
127+ return scassandras.get(node -1);
128+ }
129+
126130 private void primePeers() {
127131 for (int i = 0; i < scassandras.size(); i++)
128132 primePeers(primingClients.get(i), scassandras.get(i));
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +24 −3
@@ -16,9 +16,12 @@
1616 package com.datastax.driver.core;
1717
1818 import java.net.InetSocketAddress;
19+import java.util.Collections;
1920
2021 import org.scassandra.Scassandra;
22+import org.scassandra.ScassandraFactory;
2123 import org.scassandra.http.client.ActivityClient;
24+import org.scassandra.http.client.CurrentClient;
2225 import org.scassandra.http.client.PrimingClient;
2326 import org.slf4j.Logger;
2427 import org.slf4j.LoggerFactory;
@@ -38,6 +41,8 @@
3841 * consider using {@link com.datastax.driver.core.ScassandraTestBase.PerClassCluster} instead.
3942 */
4043 public abstract class ScassandraTestBase {
44+ private static final int BINARY_PORT = 9042;
45+ private static final int ADMIN_PORT = 9052;
4146
4247 private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class);
4348
@@ -49,13 +54,18 @@
4954
5055 protected ActivityClient activityClient;
5156
57+ protected CurrentClient currentClient;
58+
59+ protected static String ip = CCMBridge.IP_PREFIX + "1";
60+
5261 @BeforeClass(groups = { "short", "long" })
5362 public void startScassandra() {
54- scassandra = TestUtils.createScassandraServer();
63+ scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT);
5564 scassandra.start();
5665 primingClient = scassandra.primingClient();
5766 activityClient = scassandra.activityClient();
58- hostAddress = new InetSocketAddress("127.0.0.1", scassandra.getBinaryPort());
67+ currentClient = scassandra.currentClient();
68+ hostAddress = new InetSocketAddress(ip, scassandra.getBinaryPort());
5969 }
6070
6171 @AfterClass(groups = { "short", "long" })
@@ -69,11 +79,12 @@
6979 public void resetClients() {
7080 activityClient.clearAllRecordedActivity();
7181 primingClient.clearAllPrimes();
82+ currentClient.enableListener();
7283 }
7384
7485 protected Cluster.Builder createClusterBuilder() {
7586 Cluster.Builder builder = Cluster.builder()
76- .addContactPoint("127.0.0.1")
87+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
7788 .withPoolingOptions(new PoolingOptions()
7889 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
7990 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
@@ -82,6 +93,16 @@
8293 return builder;
8394 }
8495
96+ /**
97+ * An overrideable method for building on to the Cluster.Builder used for this
98+ * class.
99+ * @param builder
100+ * @return
101+ */
102+ protected Cluster.Builder configure(Cluster.Builder builder) {
103+ return builder;
104+ }
105+
85106 protected Host retrieveSingleHost(Cluster cluster) {
86107 Host host = cluster.getMetadata().getHost(hostAddress);
87108 if(host == null) {
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +22 −1
@@ -18,6 +18,8 @@
1818 import java.net.InetSocketAddress;
1919 import java.util.*;
2020
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
2123 import org.testng.annotations.Test;
2224 import static org.testng.Assert.assertEquals;
2325
@@ -25,6 +27,7 @@
2527 * Test we correctly process and print schema.
2628 */
2729 public class SchemaTest extends CCMBridge.PerClassSingleNodeCluster {
30+ static final Logger logger = LoggerFactory.getLogger(SchemaTest.class);
2831
2932 private static final Map<String, String> cql3 = new HashMap<String, String>();
3033 private static final Map<String, String> compact = new HashMap<String, String>();
@@ -97,6 +100,24 @@
97100 compact.put("compact_dynamic", compactDynamic);
98101 compact.put("compact_composite", compactComposite);
99102
103+ Properties properties = System.getProperties();
104+ String vmVersion = properties.getProperty("java.vm.specification.version");
105+ double javaVersion = 1.6;
106+ if(vmVersion != null) {
107+ try {
108+ javaVersion = Double.parseDouble(vmVersion);
109+ } catch (NumberFormatException e) {
110+ logger.warn("Could not parse java version from {}. Assuming {}.", vmVersion, javaVersion);
111+ }
112+ }
113+
114+ // Ordering of compaction options will be dependent on JDK. See schemaOptionsTest comments for explanation of why this is needed.
115+ String compactionOptions;
116+ if(javaVersion >= 1.8)
117+ compactionOptions = " AND compaction = { 'sstable_size_in_mb' : 15, 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy' }\n";
118+ else
119+ compactionOptions = " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n";
120+
100121 withOptions = String.format("CREATE TABLE %s.with_options (\n"
101122 + " k text,\n"
102123 + " v1 int,\n"
@@ -111,7 +132,7 @@
111132 + " AND bloom_filter_fp_chance = 0.01\n"
112133 + " AND caching = 'ALL'\n"
113134 + " AND comment = 'My awesome table'\n"
114- + " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n"
135+ + compactionOptions
115136 + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 };", keyspace);
116137
117138 List<String> allDefs = new ArrayList<String>();
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java +7 −6
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetSocketAddress;
1819 import java.util.List;
1920 import java.util.Map;
2021 import java.util.Set;
@@ -60,12 +61,12 @@
6061 private static final Token TOKEN18 = token("8000000000000000000");
6162 private static final Token TOKEN19 = token("9000000000000000000");
6263
63- private static final String IP1 = "127.0.0.101";
64- private static final String IP2 = "127.0.0.102";
65- private static final String IP3 = "127.0.0.103";
66- private static final String IP4 = "127.0.0.104";
67- private static final String IP5 = "127.0.0.105";
68- private static final String IP6 = "127.0.0.106";
64+ private static final InetSocketAddress IP1 = socketAddress("127.0.0.101");
65+ private static final InetSocketAddress IP2 = socketAddress("127.0.0.102");
66+ private static final InetSocketAddress IP3 = socketAddress("127.0.0.103");
67+ private static final InetSocketAddress IP4 = socketAddress("127.0.0.104");
68+ private static final InetSocketAddress IP5 = socketAddress("127.0.0.105");
69+ private static final InetSocketAddress IP6 = socketAddress("127.0.0.106");
6970
7071 private static final ReplicationStrategy exampleStrategy = simpleStrategy(3);
7172
modified driver-core/src/test/java/com/datastax/driver/core/TestListener.java +1 −1
@@ -30,7 +30,7 @@
3030 private int test_index = 0;
3131
3232 static {
33- System.out.println("[CCMBridge] Using Cassandra version: " + CCMBridge.CASSANDRA_VERSION);
33+ System.out.println("[CCMBridge] Using Cassandra version: " + CCMBridge.CASSANDRA_VERSION + " (install arguments: " + CCMBridge.CASSANDRA_INSTALL_ARGS + ")");
3434 }
3535
3636 @Override
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +5 −0
@@ -397,6 +397,11 @@
397397 return null;
398398 }
399399
400+ public static HostConnectionPool poolOf(Session session, int hostNumber) {
401+ SessionManager sessionManager = (SessionManager)session;
402+ return sessionManager.pools.get(findHost(session.getCluster(), hostNumber));
403+ }
404+
400405 public static int numberOfLocalCoreConnections(Cluster cluster) {
401406 Configuration configuration = cluster.getConfiguration();
402407 return configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL);
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +3 −3
@@ -69,7 +69,7 @@
6969
7070 static List<InetSocketAddress> nodes;
7171
72- @BeforeClass(groups = "long")
72+ @BeforeClass(groups = "stress")
7373 public void beforeClass() throws Exception {
7474 ccmBridge = CCMBridge.builder("test").withNodes(3).build();
7575 channelMonitor = new SocketChannelMonitor();
@@ -89,7 +89,7 @@
8989 .build();
9090 }
9191
92- @AfterClass(groups = "long")
92+ @AfterClass(groups = "stress")
9393 public void afterClass() {
9494 if(ccmBridge != null) {
9595 ccmBridge.stop();
@@ -125,7 +125,7 @@
125125 * @jira_ticket JAVA-692
126126 * @since 2.0.10, 2.1.6
127127 */
128- @Test(groups = "long")
128+ @Test(groups = "stress")
129129 public void host_state_should_be_maintained_with_timeouts() throws Exception {
130130 // Setup schema and insert records.
131131 Session session = cluster.connect();
modified pom.xml +1 −1
@@ -61,7 +61,7 @@
6161 <testng.version>6.8.8</testng.version>
6262 <assertj.version>1.7.0</assertj.version>
6363 <mockito.version>1.10.8</mockito.version>
64- <scassandra.version>0.9.1</scassandra.version>
64+ <scassandra.version>0.10.0</scassandra.version>
6565 <main.basedir>${project.basedir}</main.basedir>
6666 </properties>
6767