Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 3.0
Changeseteeaba16c0f888dea4c7633fa2d5296bb5fd3455443587ae89472cba9246fda63
Authorolim7t <omichallat+github@gmail.com> · 2015-10-12 11:38 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-10-12 11:38 +02:00
Parents245bc9ff74fb, 98a9d75ec57e

Browse the files at this changeset

26 files changed

added build.yaml +22 −0
@@ -0,0 +1,22 @@
1+java:
2+ - openjdk6
3+ - oraclejdk7
4+ - oraclejdk8
5+os:
6+ - ubuntu/trusty64
7+cassandra:
8+ - 1.2
9+ - 2.0
10+ - 2.1
11+build:
12+ - type: maven
13+ version: 3.2.5
14+ goals: clean compile test --fail-never -Plong
15+ properties: |
16+ com.datastax.driver.TEST_BASE_NODE_WAIT=120
17+ com.datastax.driver.NEW_NODE_DELAY_SECONDS=100
18+ cassandra.version=$CCM_CASSANDRA_VERSION
19+ ccm.java.home=$CCM_JAVA_HOME
20+ - xunit:
21+ - "**/target/surefire-reports/TEST-*.xml"
22+ - "**/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);
@@ -933,7 +936,7 @@
933936 flusher.start();
934937 }
935938
936- private class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
939+ class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
937940
938941 public final StreamIdGenerator streamIdHandler;
939942 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;
@@ -53,7 +54,8 @@
5354 private static final String SELECT_SCHEMA_PEERS = "SELECT peer, rpc_address, schema_version FROM system.peers";
5455 private static final String SELECT_SCHEMA_LOCAL = "SELECT schema_version FROM system.local WHERE key='local'";
5556
56- private final AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
57+ @VisibleForTesting
58+ final AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
5759
5860 private final Cluster.Manager cluster;
5961
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +1 −1
@@ -37,7 +37,7 @@
3737 * With {@code ProtocolVersion#V2} or below, there are at most 128 simultaneous
3838 * requests per connection, so the pool defaults to a variable size. You will
3939 * typically raise the maximum capacity by adding more connections with
40- * {@link #setMaxRequestsPerConnection(HostDistance, int)}.
40+ * {@link #setMaxConnectionsPerHost(HostDistance, int)}.
4141 * <p>
4242 * With {@code ProtocolVersion#V3} or above, there are up to 32768 requests per
4343 * connection, and the pool defaults to a fixed size of 1. You will typically
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +4 −0
@@ -68,6 +68,8 @@
6868
6969 /**
7070 * Sets the connection timeout in milliseconds.
71+ * <p>
72+ * The default value is {@link #DEFAULT_CONNECT_TIMEOUT_MILLIS}.
7173 *
7274 * @param connectTimeoutMillis the timeout to set.
7375 * @return this {@code SocketOptions}.
@@ -120,6 +122,8 @@
120122 * </ul>
121123 * <p>
122124 * Setting a value of 0 disables read timeouts.
125+ * <p>
126+ * The default value is {@link #DEFAULT_READ_TIMEOUT_MILLIS}.
123127 *
124128 * @param readTimeoutMillis the timeout to set.
125129 * @return this {@code SocketOptions}.
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");
@@ -287,7 +289,6 @@
287289 logger.debug("Executing: " + fullCommand);
288290 CommandLine cli = CommandLine.parse(fullCommand);
289291 Executor executor = new DefaultExecutor();
290- executor.setWorkingDirectory(CASSANDRA_DIR);
291292
292293 LogOutputStream outStream = new LogOutputStream() {
293294 @Override protected void processLine(String line, int logLevel) {
@@ -614,7 +615,7 @@
614615 private final String clusterName;
615616 private Integer[] nodes = { 1 };
616617 private boolean start = true;
617- private String cassandraVersion = CASSANDRA_VERSION;
618+ private String cassandraInstallArgs = CASSANDRA_INSTALL_ARGS;
618619 private String[] startOptions = new String[0];
619620 private Map<String, String> cassandraConfiguration = Maps.newHashMap();
620621
@@ -654,7 +655,7 @@
654655
655656 /** Defaults to system property cassandra.version */
656657 public Builder withCassandraVersion(String cassandraVersion) {
657- this.cassandraVersion = "-v " + cassandraVersion;
658+ this.cassandraInstallArgs = "-v " + cassandraVersion;
658659 return this;
659660 }
660661
@@ -683,7 +684,7 @@
683684 StringBuilder result = new StringBuilder(CCM_COMMAND + " create");
684685 result.append(" " + clusterName);
685686 result.append(" -i" + IP_PREFIX);
686- result.append(" " + cassandraVersion);
687+ result.append(" " + cassandraInstallArgs);
687688 if (nodes.length > 0)
688689 result.append(" -n " + Joiner.on(":").join(nodes));
689690 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
@@ -50,6 +88,31 @@
5088 return builder.withProtocolVersion(versionToUse);
5189 }
5290
91+ /**
92+ * Completes count requests by simulating a successful response.
93+ */
94+ private void completeRequests(int count, List<MockRequest> requests) {
95+ Iterator<MockRequest> requestIt = requests.iterator();
96+ for(int i = 0; i < count; i++) {
97+ if(requestIt.hasNext()) {
98+ MockRequest request = requestIt.next();
99+ request.simulateSuccessResponse();
100+ requestIt.remove();
101+ } else {
102+ break;
103+ }
104+ }
105+ }
106+
107+ /**
108+ * Completes all requests by simulating a successful response.
109+ */
110+ private void completeRequests(List<MockRequest> requests) {
111+ for(MockRequest request : requests) {
112+ request.simulateSuccessResponse();
113+ }
114+ }
115+
53116 /**
54117 * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
55118 * of creating a new connection.
@@ -59,24 +122,24 @@
59122 * @test_category connection:connection_pool
60123 */
61124 @Test(groups = "short")
62- public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException {
63- HostConnectionPool pool = createPool(2, 2);
64-
65- assertThat(pool.connections.size()).isEqualTo(2);
66- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
67-
68- for (int i = 0; i < 256; i++) {
69- Connection connection = pool.borrowConnection(100, MILLISECONDS);
70- assertThat(coreConnections).contains(connection);
71- }
72-
73- boolean timedOut = false;
125+ public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
126+ Cluster cluster = createClusterBuilder().build();
127+ List<MockRequest> requests = newArrayList();
74128 try {
75- pool.borrowConnection(100, MILLISECONDS);
76- } catch (TimeoutException e) {
77- timedOut = true;
129+ HostConnectionPool pool = createPool(cluster, 2, 2);
130+
131+ assertThat(pool.connections.size()).isEqualTo(2);
132+ List<Connection> coreConnections = newArrayList(pool.connections);
133+ requests.addAll(sendRequests(256, pool, coreConnections));
134+
135+ try {
136+ MockRequest.send(pool);
137+ Assertions.fail("Expected a TimeoutException");
138+ } catch (TimeoutException e) { /*expected*/}
139+ } finally {
140+ completeRequests(requests);
141+ cluster.close();
78142 }
79- assertThat(timedOut).isTrue();
80143 }
81144
82145 /**
@@ -88,31 +151,44 @@
88151 * @test_category connection:connection_pool
89152 */
90153 @Test(groups = "short")
91- public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException {
92- HostConnectionPool pool = createPool(1, 2);
93-
94- assertThat(pool.connections.size()).isEqualTo(1);
95- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
96-
97- //
98- for (int i = 0; i < 128; i++) {
99- Connection connection = pool.borrowConnection(100, MILLISECONDS);
100- assertThat(coreConnections).contains(connection);
101- }
102-
103- // Borrow more and ensure the connection returned is a non-core connection.
104- for (int i = 0; i < 128; i++) {
105- Connection connection = pool.borrowConnection(100, MILLISECONDS);
106- assertThat(coreConnections).doesNotContain(connection);
107- }
108-
109- boolean timedOut = false;
154+ public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
155+ Cluster cluster = createClusterBuilder().build();
156+ List<MockRequest> requests = newArrayList();
110157 try {
111- pool.borrowConnection(100, MILLISECONDS);
112- } catch (TimeoutException e) {
113- timedOut = true;
158+ HostConnectionPool pool = createPool(cluster, 1, 2);
159+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
160+ cluster.manager.connectionFactory = factory;
161+
162+ assertThat(pool.connections.size()).isEqualTo(1);
163+ List<Connection> coreConnections = newArrayList(pool.connections);
164+
165+ // Fill enough connections to hit the threshold.
166+ requests.addAll(fillConnectionToThreshold(pool, coreConnections));
167+
168+ // Allow time for new connection to be spawned.
169+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
170+
171+ // Borrow more and ensure the connection returned is a non-core connection.
172+ for (int i = 0; i < 100; i++) {
173+ MockRequest request = MockRequest.send(pool);
174+ assertThat(coreConnections).doesNotContain(request.connection);
175+ requests.add(request);
176+ }
177+
178+ // Fill remaining connections (28 + 28) - 1
179+ requests.addAll(sendRequests(55, pool));
180+
181+ boolean timedOut = false;
182+ try {
183+ MockRequest.send(pool);
184+ } catch (TimeoutException e) {
185+ timedOut = true;
186+ }
187+ assertThat(timedOut).isTrue();
188+ } finally {
189+ completeRequests(requests);
190+ cluster.close();
114191 }
115- assertThat(timedOut).isTrue();
116192 }
117193
118194 /**
@@ -123,22 +199,25 @@
123199 * @test_category connection:connection_pool
124200 */
125201 @Test(groups = "short")
126- public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException {
127- cluster.getConfiguration().getPoolingOptions()
128- .setIdleTimeoutSeconds(20);
129-
130- HostConnectionPool pool = createPool(1, 2);
131- Connection core = pool.connections.get(0);
132-
133- // Fill core connection
134- for (int i = 0; i < 128; i++)
135- assertThat(
136- pool.borrowConnection(100, MILLISECONDS)
137- ).isEqualTo(core);
138-
139- // Reaching 128 on the core connection should have triggered the creation of an extra one
140- TimeUnit.MILLISECONDS.sleep(100);
141- assertThat(pool.connections).hasSize(2);
202+ public void should_add_extra_connection_when_core_full() throws Exception {
203+ Cluster cluster = createClusterBuilder().build();
204+ List<MockRequest> requests = newArrayList();
205+ try {
206+ HostConnectionPool pool = createPool(cluster, 1, 2);
207+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
208+ cluster.manager.connectionFactory = factory;
209+ Connection core = pool.connections.get(0);
210+
211+ // Fill core connection + 1
212+ requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
213+
214+ // Reaching the threshold should have triggered the creation of an extra one
215+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
216+ assertThat(pool.connections).hasSize(2);
217+ } finally {
218+ completeRequests(requests);
219+ cluster.close();
220+ }
142221 }
143222
144223 /**
@@ -150,52 +229,55 @@
150229 * @test_category connection:connection_pool
151230 */
152231 @Test(groups = "long")
153- public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
154- cluster.getConfiguration().getPoolingOptions()
155- .setIdleTimeoutSeconds(20);
156-
157- HostConnectionPool pool = createPool(1, 2);
158- Connection connection1 = pool.connections.get(0);
159-
160- for (int i = 0; i < 101; i++)
161- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
162-
163- TimeUnit.MILLISECONDS.sleep(100);
164- assertThat(pool.connections).hasSize(2);
165- Connection connection2 = pool.connections.get(1);
166-
167- assertThat(connection1.inFlight.get()).isEqualTo(101);
168- assertThat(connection2.inFlight.get()).isEqualTo(0);
169-
170- // Go back under the capacity of 1 connection
171- for (int i = 0; i < 51; i++)
172- pool.returnConnection(connection1);
173-
174- assertThat(connection1.inFlight.get()).isEqualTo(50);
175- assertThat(connection2.inFlight.get()).isEqualTo(0);
176-
177- // Given enough time, one connection gets trashed (and the implementation picks the first one)
178- TimeUnit.SECONDS.sleep(20);
179- assertThat(pool.connections).containsExactly(connection2);
180- assertThat(pool.trash).containsExactly(connection1);
181-
182- // Now borrow enough to go just under the 1 connection threshold
183- for (int i = 0; i < 50; i++)
184- pool.borrowConnection(100, MILLISECONDS);
185-
186- assertThat(pool.connections).containsExactly(connection2);
187- assertThat(pool.trash).containsExactly(connection1);
188- assertThat(connection1.inFlight.get()).isEqualTo(50);
189- assertThat(connection2.inFlight.get()).isEqualTo(50);
190-
191- // Borrowing one more time should resurrect the trashed connection
192- pool.borrowConnection(100, MILLISECONDS);
193- TimeUnit.MILLISECONDS.sleep(100);
194-
195- assertThat(pool.connections).containsExactly(connection2, connection1);
196- assertThat(pool.trash).isEmpty();
197- assertThat(connection1.inFlight.get()).isEqualTo(50);
198- assertThat(connection2.inFlight.get()).isEqualTo(51);
232+ public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
233+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
234+ List<MockRequest> requests = newArrayList();
235+ try {
236+ HostConnectionPool pool = createPool(cluster, 1, 2);
237+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
238+ cluster.manager.connectionFactory = factory;
239+ Connection connection1 = pool.connections.get(0);
240+
241+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
242+
243+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
244+ assertThat(pool.connections).hasSize(2);
245+ Connection connection2 = pool.connections.get(1);
246+
247+ assertThat(connection1.inFlight.get()).isEqualTo(101);
248+ assertThat(connection2.inFlight.get()).isEqualTo(0);
249+
250+ // Go back under the capacity of 1 connection
251+ completeRequests(51, requests);
252+
253+ assertThat(connection1.inFlight.get()).isEqualTo(50);
254+ assertThat(connection2.inFlight.get()).isEqualTo(0);
255+
256+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
257+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
258+ assertThat(pool.connections).containsExactly(connection2);
259+ assertThat(pool.trash).containsExactly(connection1);
260+
261+ // Now borrow enough to go just under the 1 connection threshold
262+ requests.addAll(sendRequests(50, pool));
263+
264+ assertThat(pool.connections).containsExactly(connection2);
265+ assertThat(pool.trash).containsExactly(connection1);
266+ assertThat(connection1.inFlight.get()).isEqualTo(50);
267+ assertThat(connection2.inFlight.get()).isEqualTo(50);
268+
269+ // Borrowing one more time should resurrect the trashed connection
270+ requests.addAll(sendRequests(1, pool));
271+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
272+
273+ assertThat(pool.connections).containsExactly(connection2, connection1);
274+ assertThat(pool.trash).isEmpty();
275+ assertThat(connection1.inFlight.get()).isEqualTo(50);
276+ assertThat(connection2.inFlight.get()).isEqualTo(51);
277+ } finally {
278+ completeRequests(requests);
279+ cluster.close();
280+ }
199281 }
200282
201283 /**
@@ -207,157 +289,674 @@
207289 * @test_category connection:connection_pool
208290 */
209291 @Test(groups = "long")
210- public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
211- cluster.getConfiguration().getPoolingOptions()
212- .setIdleTimeoutSeconds(20);
292+ public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
293+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
294+ List<MockRequest> requests = newArrayList();
295+ try {
296+ HostConnectionPool pool = createPool(cluster, 1, 2);
297+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
298+ cluster.manager.connectionFactory = factory;
299+ Connection connection1 = pool.connections.get(0);
300+
301+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
302+
303+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
304+ reset(factory);
305+ assertThat(pool.connections).hasSize(2);
306+ Connection connection2 = pool.connections.get(1);
307+
308+ assertThat(connection1.inFlight.get()).isEqualTo(101);
309+ assertThat(connection2.inFlight.get()).isEqualTo(0);
310+
311+ // Go back under the capacity of 1 connection
312+ completeRequests(51, requests);
313+
314+ assertThat(connection1.inFlight.get()).isEqualTo(50);
315+ assertThat(connection2.inFlight.get()).isEqualTo(0);
316+
317+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
318+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
319+ assertThat(pool.connections).containsExactly(connection2);
320+ assertThat(pool.trash).containsExactly(connection1);
321+
322+ // Return trashed connection down to 0 inFlight
323+ completeRequests(50, requests);
324+ assertThat(connection1.inFlight.get()).isEqualTo(0);
325+
326+ // Give enough time for trashed connection to be cleaned up from the trash:
327+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
328+ assertThat(pool.connections).containsExactly(connection2);
329+ assertThat(pool.trash).isEmpty();
330+ assertThat(connection1.isClosed()).isTrue();
331+
332+ // Fill the live connection to go over the threshold where a second one is needed
333+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2)));
334+ assertThat(connection2.inFlight.get()).isEqualTo(101);
335+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
336+
337+ // Borrow again to get the new connection
338+ MockRequest request = MockRequest.send(pool);
339+ requests.add(request);
340+ assertThat(request.connection)
341+ .isNotEqualTo(connection2) // should not be the full connection
342+ .isNotEqualTo(connection1); // should not be the previously trashed one
343+ } finally {
344+ completeRequests(requests);
345+ cluster.close();
346+ }
347+ }
348+
349+ /**
350+ * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
351+ *
352+ * @since 2.0.10, 2.1.6
353+ * @jira_ticket JAVA-419
354+ * @test_category connection:connection_pool
355+ */
356+ @Test(groups = "long")
357+ public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
358+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
359+ List<MockRequest> requests = newArrayList();
360+
361+ try {
362+ HostConnectionPool pool = createPool(cluster, 1, 2);
363+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
364+ cluster.manager.connectionFactory = factory;
365+ Connection connection1 = pool.connections.get(0);
366+
367+ // Fill core connection enough to trigger creation of another one
368+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
369+
370+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
371+ assertThat(pool.connections).hasSize(2);
372+
373+ // Return enough times to get back under the threshold where one connection is enough
374+ completeRequests(50, requests);
375+
376+ // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
377+ // It still has in-flight requests so should not get closed.
378+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
379+ assertThat(pool.trash).containsExactly(connection1);
380+ assertThat(connection1.inFlight.get()).isEqualTo(51);
381+ assertThat(connection1.isClosed()).isFalse();
382+
383+ // Consume all inFlight requests on the trashed connection.
384+ completeRequests(51, requests);
385+
386+ // Sleep enough time for the connection to be consider idled and closed.
387+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
388+
389+ // The connection should be now closed.
390+ // The trashed connection should be closed and not in the pool or trash.
391+ assertThat(connection1.isClosed()).isTrue();
392+ assertThat(pool.connections).doesNotContain(connection1);
393+ assertThat(pool.trash).doesNotContain(connection1);
394+ } finally {
395+ completeRequests(requests);
396+ cluster.close();
397+ }
398+ }
399+
400+ /**
401+ * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
402+ * the connection is put in the trash.
403+ *
404+ * @since 2.0.10, 2.1.6
405+ * @jira_ticket JAVA-419
406+ * @test_category connection:connection_pool
407+ */
408+ @Test(groups = "short")
409+ public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
410+ Cluster cluster = createClusterBuilder().build();
411+ List<MockRequest> requests = newArrayList();
412+ try {
413+ HostConnectionPool pool = createPool(cluster, 1, 2);
414+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
415+ cluster.manager.connectionFactory = factory;
416+ Connection core = pool.connections.get(0);
417+
418+ requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
419+
420+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
421+ assertThat(pool.connections).hasSize(2);
422+
423+ // Grab the new non-core connection and replace it with a spy.
424+ Connection extra1 = spy(pool.connections.get(1));
425+ pool.connections.set(1, extra1);
426+
427+ // Borrow 10 times to ensure pool is utilized.
428+ requests.addAll(sendRequests(10, pool));
429+ assertThat(pool.connections).hasSize(2);
430+
431+ // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
432+ // this should cause the connection to be replaced and trashed on returnConnection.
433+ doReturn(0).when(extra1).maxAvailableStreams();
434+
435+ // On returning of the connection, should detect that there are no available streams and trash it.
436+ assertThat(pool.trash).hasSize(0);
437+ pool.returnConnection(extra1);
438+ assertThat(pool.connections).hasSize(1);
439+ assertThat(pool.trash).hasSize(1);
440+ } finally {
441+ completeRequests(requests);
442+ cluster.close();
443+ }
444+ }
445+
446+ /**
447+ * Ensures that if a connection on a host is lost but other connections remain intact in the Pool that the
448+ * host is not marked down.
449+ *
450+ * @jira_ticket JAVA-544
451+ * @test_category connection:connection_pool
452+ * @since 2.0.11
453+ */
454+ @Test(groups="short")
455+ public void should_keep_host_up_when_one_connection_lost() throws Exception {
456+ Cluster cluster = createClusterBuilder().build();
457+ try {
458+ HostConnectionPool pool = createPool(cluster, 2, 2);
459+ Connection core0 = pool.connections.get(0);
460+ Connection core1 = pool.connections.get(1);
461+
462+ // Drop a connection and ensure the host stays up.
463+ currentClient.disableListener();
464+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
465+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
466+
467+ // connection 0 should be down, while connection 1 and the Host should remain up.
468+ assertThat(core0.isClosed()).isTrue();
469+ assertThat(core1.isClosed()).isFalse();
470+ assertThat(pool.connections).doesNotContain(core0);
471+ assertThat(cluster).host(1).hasState(Host.State.UP);
472+ assertThat(cluster).hasOpenControlConnection();
473+ } finally {
474+ cluster.close();
475+ }
476+ }
213477
214- HostConnectionPool pool = createPool(1, 2);
215- Connection connection1 = pool.connections.get(0);
216478
217- for (int i = 0; i < 101; i++)
218- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
479+ /**
480+ * Ensures that if all connections on a host are closed that the host is marked
481+ * down and the control connection is notified of that fact and re-established
482+ * itself.
483+ *
484+ * @jira_ticket JAVA-544
485+ * @test_category connection:connection_pool
486+ * @since 2.0.11
487+ */
488+ @Test(groups="short")
489+ public void should_mark_host_down_when_no_connections_remaining() throws Exception {
490+ int readTimeout = 1000;
491+ int reconnectInterval = 1000;
492+ Cluster cluster = this.createClusterBuilder()
493+ .withSocketOptions(new SocketOptions()
494+ .setConnectTimeoutMillis(readTimeout)
495+ .setReadTimeoutMillis(reconnectInterval))
496+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
497+ try {
498+ cluster.init();
219499
220- TimeUnit.MILLISECONDS.sleep(100);
221- assertThat(pool.connections).hasSize(2);
222- Connection connection2 = pool.connections.get(1);
500+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
501+ cluster.manager.connectionFactory = factory;
223502
224- assertThat(connection1.inFlight.get()).isEqualTo(101);
225- assertThat(connection2.inFlight.get()).isEqualTo(0);
503+ HostConnectionPool pool = createPool(cluster, 8,8);
504+ // copy list to track these connections.
505+ List<Connection> connections = newArrayList(pool.connections);
226506
227- // Go back under the capacity of 1 connection
228- for (int i = 0; i < 51; i++)
229- pool.returnConnection(connection1);
507+ reset(factory);
230508
231- assertThat(connection1.inFlight.get()).isEqualTo(50);
232- assertThat(connection2.inFlight.get()).isEqualTo(0);
509+ // Drop all connections.
510+ currentClient.disableListener();
511+ currentClient.closeConnections(CLOSE);
233512
234- // Given enough time, one connection gets trashed (and the implementation picks the first one)
235- TimeUnit.SECONDS.sleep(20);
236- assertThat(pool.connections).containsExactly(connection2);
237- assertThat(pool.trash).containsExactly(connection1);
513+ // The host should be marked down and the control connection closed.
514+ assertThat(cluster).host(1).goesDownWithin(10, TimeUnit.SECONDS);
515+ assertThat(cluster).hasClosedControlConnection();
238516
239- // Return trashed connection down to 0 inFlight
240- for (int i = 0; i < 50; i++)
241- pool.returnConnection(connection1);
242- assertThat(connection1.inFlight.get()).isEqualTo(0);
517+ // Ensure all connections are closed.
518+ for(Connection connection : connections) {
519+ assertThat(connection.isClosed()).isTrue();
520+ }
243521
244- // Give enough time for trashed connection to be cleaned up from the trash:
245- TimeUnit.SECONDS.sleep(30);
246- assertThat(pool.connections).containsExactly(connection2);
247- assertThat(pool.trash).isEmpty();
248- assertThat(connection1.isClosed()).isTrue();
522+ // Expect a reconnect attempt on host after reconnect interval
523+ // on behalf of the control connection.
524+ verify(factory, timeout(reconnectInterval*2).atLeastOnce()).open(host);
525+
526+ // Sleep for a bit to allow reconnect to fail.
527+ Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
528+
529+ // Ensure control connection is still closed.
530+ assertThat(cluster).hasClosedControlConnection();
531+
532+ // Reenable connectivity.
533+ currentClient.enableListener();
534+
535+ // Reconnect attempt should have been connected for control connection
536+ // and pool.
537+ // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
538+ verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
539+ // 7 attempts for core connections after first initial connection.
540+ verify(factory, timeout(reconnectInterval*2).times(7)).newConnection(any(HostConnectionPool.class));
541+
542+ // Wait some reasonable amount of time for connection to reestablish.
543+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
544+
545+ // Control Connection should now be open.
546+ assertThat(cluster).hasOpenControlConnection();
547+ assertThat(cluster).host(1).hasState(Host.State.UP);
548+ } finally {
549+ cluster.close();
550+ }
551+ }
249552
250- // Fill the live connection to go over the threshold where a second one is needed
251- for (int i = 0; i < 101; i++)
252- assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2);
253- assertThat(connection2.inFlight.get()).isEqualTo(101);
254- TimeUnit.MILLISECONDS.sleep(100);
255553
256- // Borrow again to get the new connection
257- Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
258- assertThat(connection3)
259- .isNotEqualTo(connection2) // should not be the full connection
260- .isNotEqualTo(connection1); // should not be the previously trashed one
554+ /**
555+ * Ensures that if a connection on a host is lost that brings the number of active connections in a pool
556+ * under core connection count that up to core connections are re-established, but only after the
557+ * next reconnect schedule has elapsed.
558+ *
559+ * @jira_ticket JAVA-544
560+ * @test_category connection:connection_pool
561+ * @since 2.0.11
562+ */
563+ @Test(groups="short")
564+ public void should_create_new_connections_when_connection_lost_and_under_core_connections() throws Exception {
565+ int readTimeout = 1000;
566+ int reconnectInterval = 1000;
567+ Cluster cluster = this.createClusterBuilder()
568+ .withSocketOptions(new SocketOptions()
569+ .setConnectTimeoutMillis(readTimeout)
570+ .setReadTimeoutMillis(reconnectInterval))
571+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
572+ List<MockRequest> requests = newArrayList();
573+ try {
574+ cluster.init();
575+
576+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
577+ cluster.manager.connectionFactory = factory;
578+
579+ HostConnectionPool pool = createPool(cluster, 3, 3);
580+ Connection core0 = pool.connections.get(0);
581+ Connection core1 = pool.connections.get(1);
582+ Connection core2 = pool.connections.get(2);
583+
584+ // Drop two core connections.
585+ // Disable new connections initially and we'll eventually reenable it.
586+ currentClient.disableListener();
587+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
588+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core2.channel.localAddress()));
589+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
590+
591+ // Since we have a connection left the host should remain up.
592+ assertThat(cluster).host(1).hasState(Host.State.UP);
593+ assertThat(pool.connections).hasSize(1);
594+
595+ // The borrowed connection should be the open one.
596+ MockRequest request = MockRequest.send(pool);
597+ requests.add(request);
598+ assertThat(request.connection).isEqualTo(core1);
599+
600+ // Should not have tried to create a new core connection since reconnection time had not elapsed.
601+ verify(factory, never()).open(any(HostConnectionPool.class));
602+
603+ // Sleep to elapse the Reconnection Policy.
604+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
605+
606+ // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection.
607+ request = MockRequest.send(pool);
608+ requests.add(request);
609+ assertThat(request.connection).isEqualTo(core1);
610+
611+ // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core.
612+ verify(factory, timeout(reconnectInterval).times(1)).open(any(HostConnectionPool.class));
613+ reset(factory);
614+
615+ // Sleep for reconnect interval to allow reconnection time to elapse.
616+ Uninterruptibles.sleepUninterruptibly((readTimeout + reconnectInterval) * 2, TimeUnit.MILLISECONDS);
617+
618+ // Enable listening so new connections succeed.
619+ currentClient.enableListener();
620+ // Sleep to elapse the Reconnection Policy.
621+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
622+
623+ // Try to borrow a connection, the pool should grow.
624+ requests.add(MockRequest.send(pool));
625+ verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
626+ reset(factory);
627+
628+ // Another core connection should be opened as result of another request to get us up to core connections.
629+ requests.add(MockRequest.send(pool));
630+ verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
631+ reset(factory);
632+
633+ // Sending another request should not grow the pool any more, since we are now at core connections.
634+ requests.add(MockRequest.send(pool));
635+ verify(factory, after((reconnectInterval + readTimeout) * 2).never()).open(any(HostConnectionPool.class));
636+ } finally {
637+ completeRequests(requests);
638+ cluster.close();
639+ }
261640 }
262641
263642 /**
264- * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
643+ * Ensures that if a connection on a host is lost and the number of remaining connections is at
644+ * core connection count that no connections are re-established until after there are enough
645+ * inflight requests to justify creating one and the reconnection interval has elapsed.
265646 *
266- * @since 2.0.10, 2.1.6
267- * @jira_ticket JAVA-419
647+ * @jira_ticket JAVA-544
268648 * @test_category connection:connection_pool
649+ * @since 2.0.11
269650 */
270- @Test(groups = "long")
271- public void should_not_close_trashed_connection_until_no_in_flight()
272- throws ConnectionException, TimeoutException, InterruptedException {
273- cluster.getConfiguration().getPoolingOptions()
274- .setIdleTimeoutSeconds(20);
651+ @Test(groups = "short")
652+ public void should_not_schedule_reconnect_when_connection_lost_and_at_core_connections() throws Exception {
653+ int readTimeout = 1000;
654+ int reconnectInterval = 1000;
655+ Cluster cluster = this.createClusterBuilder()
656+ .withSocketOptions(new SocketOptions()
657+ .setConnectTimeoutMillis(readTimeout)
658+ .setReadTimeoutMillis(reconnectInterval))
659+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
660+ List<MockRequest> requests = newArrayList();
661+ try {
662+ cluster.init();
663+
664+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
665+ cluster.manager.connectionFactory = factory;
666+
667+ HostConnectionPool pool = createPool(cluster, 1, 2);
668+ Connection core0 = pool.connections.get(0);
669+
670+ // Create enough inFlight requests to spawn another connection.
671+ List<MockRequest> core0requests = newArrayList();
672+ for (int i = 0; i < 101; i++) {
673+ MockRequest request = MockRequest.send(pool);
674+ assertThat(request.connection).isEqualTo(core0);
675+ core0requests.add(request);
676+ }
275677
276- HostConnectionPool pool = createPool(1, 2);
277- Connection connection1 = pool.connections.get(0);
678+ // Pool should grow by 1.
679+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
680+ assertThat(pool.connections).hasSize(2);
278681
279- // Fill core connection enough to trigger creation of another one
280- for (int i = 0; i < 110; i++)
281- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
682+ // Reset factory mock as we'll be checking for new open() invokes later.
683+ reset(factory);
282684
283- TimeUnit.MILLISECONDS.sleep(100);
284- assertThat(pool.connections).hasSize(2);
685+ // Grab the new non-core connection.
686+ Connection extra1 = pool.connections.get(1);
285687
286- // Return enough times to get back under the threshold where one connection is enough
287- for (int i = 0; i < 50; i++)
288- pool.returnConnection(connection1);
688+ // Drop a connection and disable listening.
689+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
690+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
691+ currentClient.disableListener();
289692
290- // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
291- // It still has in-flight requests so should not get closed.
292- TimeUnit.SECONDS.sleep(30);
293- assertThat(pool.trash).containsExactly(connection1);
294- assertThat(connection1.inFlight.get()).isEqualTo(60);
295- assertThat(connection1.isClosed()).isFalse();
693+ // Since core0 was closed, all of it's requests should have errored.
694+ for(MockRequest request : core0requests) {
695+ verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
696+ }
296697
297- // Consume all inFlight requests on the trashed connection.
298- while (connection1.inFlight.get() > 0) {
299- pool.returnConnection(connection1);
698+ assertThat(cluster).host(1).hasState(Host.State.UP);
699+
700+ // Create enough inFlight requests to fill connection.
701+ requests.addAll(sendRequests(100, pool, singletonList(extra1)));
702+ assertThat(pool.connections).hasSize(1);
703+
704+ // A new connection should never have been spawned since we didn't max out core.
705+ verify(factory, after(readTimeout).never()).open(any(HostConnectionPool.class));
706+
707+ // Borrow another connection, since we exceed max another connection should be opened.
708+ MockRequest request = MockRequest.send(pool);
709+ requests.add(request);
710+ assertThat(request.connection).isEqualTo(extra1);
711+
712+ // After some time the a connection should attempt to be opened (but will fail).
713+ verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
714+ assertThat(pool.connections).hasSize(1);
715+
716+ // Wait some reasonable amount of time for connection to reestablish then check pool size.
717+ Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
718+ // Reconnecting failed since listening was enabled.
719+ assertThat(pool.connections).hasSize(1);
720+
721+ // Re enable listening then wait for reconnect.
722+ currentClient.enableListener();
723+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
724+
725+ // Borrow another connection, since we exceed max another connection should be opened.
726+ request = MockRequest.send(pool);
727+ requests.add(request);
728+ assertThat(request.connection).isEqualTo(extra1);
729+
730+ // Wait some reasonable amount of time for connection to reestablish then check pool size.
731+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
732+ // Reconnecting should have exceeded and pool will have grown.
733+ assertThat(pool.connections).hasSize(2);
734+
735+ // Borrowed connection should be the newly spawned connection since the other one has some inflight requests.
736+ request = MockRequest.send(pool);
737+ requests.add(request);
738+ assertThat(request.connection).isNotEqualTo(core0).isNotEqualTo(extra1);
739+ } finally {
740+ completeRequests(requests);
741+ cluster.close();
300742 }
743+ }
301744
302- // Sleep enough time for the connection to be consider idled and closed.
303- TimeUnit.SECONDS.sleep(30);
304-
305- // The connection should be now closed.
306- // The trashed connection should be closed and not in the pool or trash.
307- assertThat(connection1.isClosed()).isTrue();
308- assertThat(pool.connections).doesNotContain(connection1);
309- assertThat(pool.trash).doesNotContain(connection1);
745+ /**
746+ * Ensures that if some connections fail on pool init that the host and subsequently the
747+ * control connection is not marked down. The test also ensures that when making requests
748+ * on the pool that connections are brought up to core.
749+ *
750+ * @jira_ticket JAVA-544
751+ * @test_category connection:connection_pool
752+ * @since 2.0.11
753+ */
754+ @Test(groups="short")
755+ public void should_not_mark_host_down_if_some_connections_fail_on_init() throws Exception {
756+ int readTimeout = 1000;
757+ int reconnectInterval = 1000;
758+ Cluster cluster = this.createClusterBuilder()
759+ .withSocketOptions(new SocketOptions()
760+ .setConnectTimeoutMillis(readTimeout)
761+ .setReadTimeoutMillis(reconnectInterval))
762+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
763+ List<MockRequest> requests = newArrayList();
764+ try {
765+ cluster.init();
766+
767+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
768+ cluster.manager.connectionFactory = factory;
769+
770+ // Allow the first 4 connections to establish, but disable after that.
771+ currentClient.disableListener(4);
772+ HostConnectionPool pool = createPool(cluster, 8, 8);
773+
774+ reset(factory);
775+
776+ // Pool size should show all successful connections.
777+ assertThat(pool.connections).hasSize(4);
778+
779+ // Control connection should remain up in addition to to host.
780+ assertThat(cluster).host(1).hasState(Host.State.UP);
781+ assertThat(cluster).hasOpenControlConnection();
782+
783+ // Reenable listener, wait reconnectInterval and then try borrowing a connection.
784+ currentClient.enableListener();
785+
786+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
787+
788+ // Should open up to core connections, however it will only spawn up to 1 connection
789+ // per request, so we need to make enough requests to make up the deficit. Additionally
790+ // we need to wait for connections to be established between requests for the pool
791+ // to spawn new connections (since it only allows one simultaneous creation).
792+ for (int i = 5; i <= 8; i++) {
793+ requests.add(MockRequest.send(pool));
794+ verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
795+ reset(factory);
796+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
797+ assertThat(pool.connections).hasSize(i);
798+ }
799+ } finally {
800+ completeRequests(requests);
801+ cluster.close();
802+ }
310803 }
311804
312805 /**
313- * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
314- * the connection is put in the trash.
806+ * Ensures that if all connections fail on pool init that the host and subsequently the
807+ * control connection is not marked down since the control connection is still active.
808+ * on the pool that a TimeoutException is yielded if we are still in the reconnection window
809+ * according to the ConvictionPolicy.
315810 *
316- * @since 2.0.10, 2.1.6
317- * @jira_ticket JAVA-419
811+ * @jira_ticket JAVA-544
318812 * @test_category connection:connection_pool
813+ * @since 2.0.11
319814 */
320- @Test(groups = "short")
321- public void should_trash_on_returning_connection_with_insufficient_streams()
322- throws ConnectionException, TimeoutException, InterruptedException {
323- HostConnectionPool pool = createPool(1, 2);
324- Connection core = pool.connections.get(0);
815+ @Test(groups = "short", expectedExceptions = TimeoutException.class)
816+ public void should_throw_exception_if_convicted_and_no_connections_available() throws Exception {
817+ int readTimeout = 1000;
818+ int reconnectInterval = 1000;
819+ Cluster cluster = this.createClusterBuilder()
820+ .withSocketOptions(new SocketOptions()
821+ .setConnectTimeoutMillis(readTimeout)
822+ .setReadTimeoutMillis(reconnectInterval))
823+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
824+ try {
825+ // Init cluster so control connection is created.
826+ cluster.init();
827+ assertThat(cluster).hasOpenControlConnection();
828+
829+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
830+ cluster.manager.connectionFactory = factory;
325831
326- for (int i = 0; i < 128; i++)
327- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
832+ // Disable listener so all connections on pool fail.
833+ currentClient.disableListener();
834+ HostConnectionPool pool = createPool(cluster, 8, 8);
328835
329- TimeUnit.MILLISECONDS.sleep(100);
330- assertThat(pool.connections).hasSize(2);
836+ reset(factory);
331837
332- // Grab the new non-core connection and replace it with a spy.
333- Connection extra1 = spy(pool.connections.get(1));
334- pool.connections.set(1, extra1);
838+ // Pool should be empty.
839+ assertThat(pool.connections).hasSize(0);
335840
336- // Borrow 10 times to ensure pool is utilized.
337- for (int i = 0; i < 10; i++) {
338- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1);
841+ // Control connection should stay up with the host.
842+ assertThat(cluster).host(1).hasState(Host.State.UP);
843+ assertThat(cluster).hasOpenControlConnection();
844+
845+ MockRequest.send(pool);
846+ } finally {
847+ cluster.close();
339848 }
849+ }
340850
341- // Return connection, it should not be trashed since it still has 9 inflight requests.
342- pool.returnConnection(extra1);
343- assertThat(pool.connections).hasSize(2);
344851
345- // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
346- // this should cause the connection to be replaced and trashed on returnConnection.
347- doReturn(0).when(extra1).maxAvailableStreams();
852+ /**
853+ * Ensures that if all connections fail on pool init that the host and subsequently the
854+ * control connection is not marked down. The test also ensures that when making requests
855+ * on the pool after the conviction period that all core connections are created.
856+ *
857+ * @jira_ticket JAVA-544
858+ * @test_category connection:connection_pool
859+ * @since 2.0.11
860+ */
861+ @Test(groups="short")
862+ public void should_wait_on_connection_if_not_convicted_and_no_connections_available() throws Exception {
863+ int readTimeout = 1000;
864+ int reconnectInterval = 1000;
865+ Cluster cluster = this.createClusterBuilder()
866+ .withSocketOptions(new SocketOptions()
867+ .setConnectTimeoutMillis(readTimeout)
868+ .setReadTimeoutMillis(reconnectInterval))
869+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
870+ try {
871+ // Init cluster so control connection is created.
872+ cluster.init();
873+ assertThat(cluster).hasOpenControlConnection();
874+
875+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
876+ cluster.manager.connectionFactory = factory;
877+
878+ // Disable listener so all connections on pool fail.
879+ currentClient.disableListener();
880+ HostConnectionPool pool = createPool(cluster, 8, 8);
881+
882+ // Pool should be empty.
883+ assertThat(pool.connections).hasSize(0);
884+
885+ // Control connection should stay up with the host.
886+ assertThat(cluster).host(1).hasState(Host.State.UP);
887+ assertThat(cluster).hasOpenControlConnection();
888+
889+ currentClient.enableListener();
890+
891+ // Wait for reconnectInterval so ConvictionPolicy allows connection to be created.
892+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
893+
894+ reset(factory);
895+ MockRequest request = MockRequest.send(pool);
896+ request.simulateSuccessResponse();
897+
898+ // Should create up to core connections.
899+ verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class));
900+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
901+ assertThat(pool.connections).hasSize(8);
902+ } finally {
903+ cluster.close();
904+ }
905+ }
348906
349- // On returning of the connection, should detect that there are no available streams and trash it.
350- pool.returnConnection(extra1);
351- assertThat(pool.connections).hasSize(1);
907+ /**
908+ * Ensures that if a pool is created with zero core connections that when a request
909+ * is first sent that one and only one connection is created and that it waits on availability
910+ * of that connection and returns it.
911+ *
912+ * @jira_ticket JAVA-544
913+ * @test_category connection:connection_pool
914+ * @since 2.0.11
915+ */
916+ @Test(groups="short")
917+ public void should_wait_on_connection_if_zero_core_connections() throws Exception {
918+ int readTimeout = 1000;
919+ int reconnectInterval = 1000;
920+ Cluster cluster = this.createClusterBuilder()
921+ .withSocketOptions(new SocketOptions()
922+ .setConnectTimeoutMillis(readTimeout)
923+ .setReadTimeoutMillis(reconnectInterval))
924+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
925+ try {
926+ // Init cluster so control connection is created.
927+ cluster.init();
928+ assertThat(cluster).hasOpenControlConnection();
929+
930+ HostConnectionPool pool = createPool(cluster, 0, 2);
931+
932+ // Pool should be empty.
933+ assertThat(pool.connections).hasSize(0);
934+
935+ // Control connection should stay up with the host.
936+ assertThat(cluster).host(1).hasState(Host.State.UP);
937+ assertThat(cluster).hasOpenControlConnection();
938+
939+ // Send a request, this should create a connection.
940+ MockRequest request = MockRequest.send(pool);
941+ request.simulateSuccessResponse();
942+
943+ // Should create up to core connections.
944+ assertThat(pool.connections).hasSize(1);
945+ } finally {
946+ cluster.close();
947+ }
352948 }
353949
354- private HostConnectionPool createPool(int coreConnections, int maxConnections) {
950+ private HostConnectionPool createPool(Cluster cluster, int coreConnections, int maxConnections) {
355951 cluster.getConfiguration().getPoolingOptions()
356- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
357- .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
952+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
953+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
358954 Session session = cluster.connect();
359955 Host host = TestUtils.findHost(cluster, 1);
360- return (HostConnectionPool)((SessionManager)session).pools.get(host);
956+
957+ // Replace the existing pool with a spy pool and return it.
958+ SessionManager sm = ((SessionManager)session);
959+ return sm.pools.get(host);
361960 }
362961
363962 /**
@@ -403,7 +1002,8 @@
4031002 // Insert 100k lines in a newly created 1k columns table
4041003 PreparedStatement insertStatement = session.prepare(generateJava349InsertStatement());
4051004 for (int key = 0; key < numberOfInserts; key++) {
406- session.executeAsync(insertStatement.bind(key)).addListener(progressReporter, progressReportExecutor);
1005+ ResultSetFuture future = session.executeAsync(insertStatement.bind(key));
1006+ future.addListener(progressReporter, progressReportExecutor);
4071007 }
4081008
4091009 // Wait for all inserts to happen and stop connections and progress tracking
@@ -426,6 +1026,81 @@
4261026 sb.append(", ").append(i);
4271027 }
4281028 sb.append(");");
1029+
1030+ PrimingRequest preparedStatementPrime = PrimingRequest.preparedStatementBuilder()
1031+ .withQuery(sb.toString())
1032+ .withThen(then().withVariableTypes(PrimitiveType.INT))
1033+ .build();
1034+ primingClient.prime(preparedStatementPrime);
4291035 return sb.toString();
4301036 }
1037+
1038+ /** Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections). */
1039+ static class MockRequest implements Connection.ResponseCallback {
1040+
1041+ enum State { START, COMPLETED, FAILED, TIMED_OUT }
1042+
1043+ final Connection connection;
1044+ private Connection.ResponseHandler responseHandler;
1045+
1046+ private final AtomicReference<State> state = new AtomicReference<State>(State.START);
1047+
1048+ static MockRequest send(HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
1049+ // Create a MockRequest and spy on it. Create a response handler and add it to the connection's dispatcher.
1050+ MockRequest request = spy(new MockRequest(pool));
1051+ request.responseHandler = new Connection.ResponseHandler(request.connection, request);
1052+ request.connection.dispatcher.add(request.responseHandler);
1053+ return request;
1054+ }
1055+
1056+ private MockRequest(HostConnectionPool pool) throws ConnectionException, TimeoutException, BusyConnectionException {
1057+ connection = pool.borrowConnection(500, TimeUnit.MILLISECONDS);
1058+ }
1059+
1060+ void simulateSuccessResponse() {
1061+ onSet(connection, null, 0, 0);
1062+ }
1063+
1064+ @SuppressWarnings("unused")
1065+ void simulateErrorResponse() {
1066+ onException(connection, null, 0, 0);
1067+ }
1068+
1069+ @SuppressWarnings("unused")
1070+ void simulateTimeout() {
1071+ if (onTimeout(connection, 0, 0))
1072+ responseHandler.cancelHandler();
1073+ }
1074+
1075+ @Override
1076+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
1077+ if (state.compareAndSet(State.START, State.COMPLETED)) {
1078+ connection.release();
1079+ connection.dispatcher.removeHandler(responseHandler, true);
1080+ }
1081+ }
1082+
1083+ @Override
1084+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
1085+ if (state.compareAndSet(State.START, State.FAILED)) {
1086+ connection.release();
1087+ connection.dispatcher.removeHandler(responseHandler, true);
1088+ }
1089+ }
1090+
1091+ @Override
1092+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
1093+ return state.compareAndSet(State.START, State.TIMED_OUT);
1094+ }
1095+
1096+ @Override
1097+ public Message.Request request() {
1098+ return null; // not needed for this test class
1099+ }
1100+
1101+ @Override
1102+ public int retryCount() {
1103+ return 0; // value not important for this test class
1104+ }
1105+ }
4311106 }
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +5 −5
@@ -188,7 +188,7 @@
188188 * Test a wide row of size 1,000,000
189189 * @throws Throwable
190190 */
191- @Test(groups = "long")
191+ @Test(groups = "stress")
192192 @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle reading wide rows well.")
193193 public void wideRows() throws Throwable {
194194 Cluster.Builder builder = Cluster.builder();
@@ -212,7 +212,7 @@
212212 * Test a batch that writes a row of size 4,000 (just below the error threshold for 2.2).
213213 * @throws Throwable
214214 */
215- @Test(groups = "short")
215+ @Test(groups = "stress")
216216 @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle large batches well.")
217217 public void wideBatchRows() throws Throwable {
218218 Cluster.Builder builder = Cluster.builder();
@@ -236,7 +236,7 @@
236236 * Test a wide row of size 1,000,000 consisting of a ByteBuffer
237237 * @throws Throwable
238238 */
239- @Test(groups = "long")
239+ @Test(groups = "stress")
240240 public void wideByteRows() throws Throwable {
241241 Cluster.Builder builder = Cluster.builder();
242242 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -259,7 +259,7 @@
259259 * Test a row with a single extra large text value
260260 * @throws Throwable
261261 */
262- @Test(groups = "short")
262+ @Test(groups = "stress")
263263 public void largeText() throws Throwable {
264264 Cluster.Builder builder = Cluster.builder();
265265 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -282,7 +282,7 @@
282282 * Creates a table with 330 columns
283283 * @throws Throwable
284284 */
285- @Test(groups = "short")
285+ @Test(groups = "stress")
286286 public void wideTable() throws Throwable {
287287 Cluster.Builder builder = Cluster.builder();
288288 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().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().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().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 // Scassandra does not support V3 yet, and V4 may cause the server to crash
7889 .withProtocolVersion(ProtocolVersion.V2)
7990 .withPoolingOptions(new PoolingOptions()
@@ -84,6 +95,16 @@
8495 return builder;
8596 }
8697
98+ /**
99+ * An overrideable method for building on to the Cluster.Builder used for this
100+ * class.
101+ * @param builder
102+ * @return
103+ */
104+ protected Cluster.Builder configure(Cluster.Builder builder) {
105+ return builder;
106+ }
107+
87108 protected Host retrieveSingleHost(Cluster cluster) {
88109 Host host = cluster.getMetadata().getHost(hostAddress);
89110 if(host == null) {
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
@@ -434,6 +434,11 @@
434434 return null;
435435 }
436436
437+ public static HostConnectionPool poolOf(Session session, int hostNumber) {
438+ SessionManager sessionManager = (SessionManager)session;
439+ return sessionManager.pools.get(findHost(session.getCluster(), hostNumber));
440+ }
441+
437442 public static int numberOfLocalCoreConnections(Cluster cluster) {
438443 Configuration configuration = cluster.getConfiguration();
439444 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 features/object_mapper/using/README.md +3 −2
@@ -86,9 +86,10 @@
8686 - `consistencyLevel`: specify a consistency level.
8787 - `tracing`: set tracing flag for the query.
8888 - `saveNullFields`: if set to true, fields with value `null` in an
89- instance that is to be persisted, will be explicitly written as `null`
89+ instance that is to be persisted will be explicitly written as `null`
9090 in the query. If set to false, fields with null value won't be included
91- in the write query (thus avoiding tombstones).
91+ in the write query (thus avoiding tombstones). If not specified, the
92+ default behavior is to persist `null` fields.
9293
9394 To use options, add them to the mapper call after regular parameters:
9495
modified pom.xml +1 −1
@@ -57,7 +57,7 @@
5757 <testng.version>6.8.8</testng.version>
5858 <assertj.version>1.7.0</assertj.version>
5959 <mockito.version>1.10.8</mockito.version>
60- <scassandra.version>0.9.1</scassandra.version>
60+ <scassandra.version>0.10.0</scassandra.version>
6161 <main.basedir>${project.basedir}</main.basedir>
6262 </properties>
6363
modified upgrade_guide/README.md +14 −12
@@ -202,6 +202,19 @@
202202 binary compatibility on the 2.1 branch).
203203
204204
205+### 2.1.8
206+
207+2.1.8 is binary-compatible with 2.1.7 but introduces a small change in the
208+driver's behavior:
209+
210+1. The list of contact points provided at startup is now shuffled before trying
211+ to open the control connection, so that multiple clients with the same contact
212+ points don't all pick the same control host. As a result, you can't assume that
213+ the driver will try contact points in a deterministic order. In particular, if
214+ you use the `DCAwareRoundRobinPolicy` without specifying a primary datacenter
215+ name, make sure that you only provide local hosts as contact points.
216+
217+
205218 ### 2.1.7
206219
207220 This version brings a few changes in the driver's behavior; none of them break
@@ -235,22 +248,11 @@
235248 If this is a problem for you, `MappingManager(Session, ProtocolVersion)`
236249 preserves the previous behavior (see the API docs for more details).
237250
238-Merged from 2.0.11:
239-
240-4. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable
241- exception received from a request. The new behaviour will cause the driver to
242- process a Retry on a different node at most once, otherwise an exception will
243- be thrown. This change makes sense in the case where the node tried initially
244- for the request happens to be isolated from the rest of the cluster (e.g.
245- because of a network partition) but can still answer to the client normally.
246- In this case, trying another node has a chance of success.
247- The previous behaviour was to always throw an exception.
248-5. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()`
251+4. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()`
249252 or `raw()` is used to build a value to be inserted in the database.
250253 If you know that the CQL functions or expressions are safe, use
251254 `setIdempotent(true)` on the statement.
252255
253-
254256 ### 2.1.6
255257
256258 See [2.0.10](#2-0-x-to-2-0-10).