Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 3.0.x
Changeset4b35bd0a42ce10d331fc5f1ecf01475f3b4ca7145414229bb708c1d0b25afb4c
Authorolim7t <omichallat+github@gmail.com> · 2016-05-09 13:58 -07:00
Committerolim7t <omichallat+github@gmail.com> · 2016-05-09 13:59 -07:00
Parents9aa33e768895, 876983ef4dbf

Browse the files at this changeset

11 files changed

modified changelog/README.md +30 −1
@@ -1,5 +1,13 @@
11 ## Changelog
22
3+### 3.0.2 (in progress)
4+
5+Merged from 2.1 branch:
6+
7+- [bug] JAVA-1179: Request objects should be copied when executed.
8+- [improvement] JAVA-1182: Throw error when synchronous call made on I/O thread.
9+
10+
311 ### 3.0.1
412
513 - [bug] JAVA-1132: Executing bound statement with no variables results in exception with protocol v1.
@@ -309,6 +317,20 @@
309317 - [improvement] JAVA-782: Unify "Target" enum for schema elements.
310318
311319
320+### 2.1.10.2
321+
322+Merged from 2.0 branch:
323+
324+- [bug] JAVA-1179: Request objects should be copied when executed.
325+- [improvement] JAVA-1182: Throw error when synchronous call made on I/O thread.
326+
327+
328+### 2.1.10.1
329+
330+- [bug] JAVA-1152: Fix NPE at ControlConnection.refreshNodeListAndTokenMap().
331+- [bug] JAVA-1156: Fix NPE at TableMetadata.equals().
332+
333+
312334 ### 2.1.10
313335
314336 - [bug] JAVA-988: Metadata.handleId should handle escaped double quotes.
@@ -678,12 +700,19 @@
678700 - [bug] JAVA-377, JAVA-391: Make metadata parsing more lenient.
679701
680702
681-### 2.0.13 (in progress)
703+### 2.0.12.2
704+
705+- [bug] JAVA-1179: Request objects should be copied when executed.
706+- [improvement] JAVA-1182: Throw error when synchronous call made on I/O thread.
707+
708+
709+### 2.0.12.1
682710
683711 - [bug] JAVA-994: Don't call on(Up|Down|Add|Remove) methods if Cluster is closed/closing.
684712 - [improvement] JAVA-805: Document that metrics are null until Cluster is initialized.
685713 - [bug] JAVA-1072: Ensure defunct connections are properly evicted from the pool.
686714
715+
687716 ### 2.0.12
688717
689718 - [bug] JAVA-950: Fix Cluster.connect with a case-sensitive keyspace.
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +12 −0
@@ -60,6 +60,7 @@
6060 */
6161 @Override
6262 public ResultSet execute(Statement statement) {
63+ checkNotInEventLoop();
6364 return executeAsync(statement).getUninterruptibly();
6465 }
6566
@@ -92,6 +93,7 @@
9293 */
9394 @Override
9495 public PreparedStatement prepare(String query) {
96+ checkNotInEventLoop();
9597 try {
9698 return Uninterruptibles.getUninterruptibly(prepareAsync(query));
9799 } catch (ExecutionException e) {
@@ -104,6 +106,7 @@
104106 */
105107 @Override
106108 public PreparedStatement prepare(RegularStatement statement) {
109+ checkNotInEventLoop();
107110 try {
108111 return Uninterruptibles.getUninterruptibly(prepareAsync(statement));
109112 } catch (ExecutionException e) {
@@ -172,4 +175,13 @@
172175 Thread.currentThread().interrupt();
173176 }
174177 }
178+
179+ /**
180+ * Checks that the current thread is not one of the Netty I/O threads used by the driver.
181+ * <p/>
182+ * This is called from the synchronous methods of this class to prevent deadlock issues.
183+ */
184+ protected void checkNotInEventLoop() {
185+ // This method is concrete only to avoid a breaking change. See subclass for the actual implementation.
186+ }
175187 }
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +3 −4
@@ -508,11 +508,10 @@
508508
509509 ResponseHandler write(ResponseCallback callback, long statementReadTimeoutMillis, boolean startTimeout) throws ConnectionException, BusyConnectionException {
510510
511- Message.Request request = callback.request();
512-
513511 ResponseHandler handler = new ResponseHandler(this, statementReadTimeoutMillis, callback);
514512 dispatcher.add(handler);
515- request.setStreamId(handler.streamId);
513+
514+ Message.Request request = callback.request().setStreamId(handler.streamId);
516515
517516 /*
518517 * We check for close/defunct *after* having set the handler because closing/defuncting
@@ -686,7 +685,7 @@
686685
687686 final Timer timer;
688687
689- private final EventLoopGroup eventLoopGroup;
688+ final EventLoopGroup eventLoopGroup;
690689 private final Class<? extends Channel> channelClass;
691690
692691 private final ChannelGroup allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
modified driver-core/src/main/java/com/datastax/driver/core/Message.java +15 −4
@@ -48,7 +48,7 @@
4848 R decode(ByteBuf body, ProtocolVersion version, CodecRegistry codecRegistry);
4949 }
5050
51- private volatile int streamId;
51+ private volatile int streamId = -1;
5252
5353 /**
5454 * A generic key-value custom payload. Custom payloads are simply
@@ -113,6 +113,19 @@
113113 this.tracingRequested = tracingRequested;
114114 }
115115
116+ @Override
117+ Request setStreamId(int streamId) {
118+ // JAVA-1179: defensively guard against reusing the same Request object twice.
119+ // If no streamId was ever set we can use this object directly, otherwise make a copy.
120+ if (getStreamId() < 0)
121+ return (Request) super.setStreamId(streamId);
122+ else {
123+ Request copy = this.copy();
124+ copy.setStreamId(streamId);
125+ return copy;
126+ }
127+ }
128+
116129 boolean isTracingRequested() {
117130 return tracingRequested;
118131 }
@@ -167,9 +180,7 @@
167180 }
168181 }
169182
170- Request copy() {
171- throw new UnsupportedOperationException();
172- }
183+ abstract Request copy();
173184
174185 Request copy(ConsistencyLevel newConsistencyLevel) {
175186 throw new UnsupportedOperationException();
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +1 −5
@@ -63,7 +63,7 @@
6363 private final long startTime;
6464
6565 private final AtomicBoolean isDone = new AtomicBoolean();
66- private AtomicInteger executionCount = new AtomicInteger();
66+ private final AtomicInteger executionCount = new AtomicInteger();
6767
6868 public RequestHandler(SessionManager manager, Callback callback, Statement statement) {
6969 this.id = Long.toString(System.identityHashCode(this));
@@ -105,10 +105,6 @@
105105
106106 Message.Request request = callback.request();
107107 int position = executionCount.incrementAndGet();
108- // Clone the request after the first execution, since we set the streamId on it later and we
109- // don't want to share that across executions.
110- if (position > 1)
111- request = request.copy();
112108
113109 SpeculativeExecution execution = new SpeculativeExecution(request, position);
114110 runningExecutions.add(execution);
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +32 −0
@@ -49,9 +49,11 @@
4949 };
5050
5151 private final Map<String, String> options;
52+ private final ProtocolOptions.Compression compression;
5253
5354 Startup(ProtocolOptions.Compression compression) {
5455 super(Message.Request.Type.STARTUP);
56+ this.compression = compression;
5557
5658 ImmutableMap.Builder<String, String> map = new ImmutableMap.Builder<String, String>();
5759 map.put(CQL_VERSION_OPTION, CQL_VERSION);
@@ -60,6 +62,11 @@
6062 this.options = map.build();
6163 }
6264
65+ @Override
66+ Request copy() {
67+ return new Startup(compression);
68+ }
69+
6370 @Override
6471 public String toString() {
6572 return "STARTUP " + options;
@@ -90,6 +97,11 @@
9097 super(Message.Request.Type.CREDENTIALS);
9198 this.credentials = credentials;
9299 }
100+
101+ @Override
102+ Request copy() {
103+ return new Credentials(credentials);
104+ }
93105 }
94106
95107 static class Options extends Message.Request {
@@ -109,6 +121,11 @@
109121 super(Message.Request.Type.OPTIONS);
110122 }
111123
124+ @Override
125+ Request copy() {
126+ return new Options();
127+ }
128+
112129 @Override
113130 public String toString() {
114131 return "OPTIONS";
@@ -553,6 +570,11 @@
553570 this.query = query;
554571 }
555572
573+ @Override
574+ Request copy() {
575+ return new Prepare(query);
576+ }
577+
556578 @Override
557579 public String toString() {
558580 return "PREPARE " + query;
@@ -585,6 +607,11 @@
585607 this.eventTypes = eventTypes;
586608 }
587609
610+ @Override
611+ Request copy() {
612+ return new Register(eventTypes);
613+ }
614+
588615 @Override
589616 public String toString() {
590617 return "REGISTER " + eventTypes;
@@ -612,5 +639,10 @@
612639 super(Message.Request.Type.AUTH_RESPONSE);
613640 this.token = token;
614641 }
642+
643+ @Override
644+ Request copy() {
645+ return new AuthResponse(token);
646+ }
615647 }
616648 }
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +19 −0
@@ -28,6 +28,7 @@
2828 import com.google.common.collect.ImmutableList;
2929 import com.google.common.collect.Lists;
3030 import com.google.common.util.concurrent.*;
31+import io.netty.util.concurrent.EventExecutor;
3132 import org.slf4j.Logger;
3233 import org.slf4j.LoggerFactory;
3334
@@ -47,6 +48,9 @@
4748
4849 private static final Logger logger = LoggerFactory.getLogger(Session.class);
4950
51+ private static final boolean CHECK_IO_DEADLOCKS = SystemProperties.getBoolean(
52+ "com.datastax.driver.CHECK_IO_DEADLOCKS", true);
53+
5054 final Cluster cluster;
5155 final ConcurrentMap<Host, HostConnectionPool> pools;
5256 final HostConnectionPool.PoolState poolsState;
@@ -661,6 +665,21 @@
661665 }
662666 }
663667
668+ @Override
669+ protected void checkNotInEventLoop() {
670+ if (!CHECK_IO_DEADLOCKS)
671+ return;
672+ for (EventExecutor executor : cluster.manager.connectionFactory.eventLoopGroup) {
673+ if (executor.inEventLoop()) {
674+ throw new IllegalStateException(
675+ "Detected a synchronous Session call (execute() or prepare()) on an I/O thread, " +
676+ "this can cause deadlocks or unpredictable behavior. " +
677+ "Make sure your Future callbacks only use async calls, or schedule them on a " +
678+ "different executor.");
679+ }
680+ }
681+ }
682+
664683 private static class State implements Session.State {
665684
666685 private final SessionManager session;
modified driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java +3 −3
@@ -21,7 +21,7 @@
2121 /**
2222 * Allows overriding internal settings via system properties.
2323 * <p/>
24- * Warning: this is meant for integration tests only, NOT FOR PRODUCTION USE.
24+ * This is generally reserved for tests or "expert" usage.
2525 */
2626 class SystemProperties {
2727 private static final Logger logger = LoggerFactory.getLogger(SystemProperties.class);
@@ -34,7 +34,7 @@
3434 }
3535 try {
3636 int value = Integer.parseInt(stringValue);
37- logger.warn("{} is defined, using value {}", key, value);
37+ logger.info("{} is defined, using value {}", key, value);
3838 return value;
3939 } catch (NumberFormatException e) {
4040 logger.warn("{} is defined but could not parse value {}, using default value {}", key, stringValue, defaultValue);
@@ -50,7 +50,7 @@
5050 }
5151 try {
5252 boolean value = Boolean.parseBoolean(stringValue);
53- logger.warn("{} is defined, using value {}", key, value);
53+ logger.info("{} is defined, using value {}", key, value);
5454 return value;
5555 } catch (NumberFormatException e) {
5656 logger.warn("{} is defined but could not parse value {}, using default value {}", key, stringValue, defaultValue);
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +22 −0
@@ -17,6 +17,7 @@
1717
1818 import com.datastax.driver.core.exceptions.InvalidQueryException;
1919 import com.google.common.base.Function;
20+import com.google.common.base.Throwables;
2021 import com.google.common.collect.Lists;
2122 import com.google.common.util.concurrent.*;
2223 import org.testng.annotations.DataProvider;
@@ -26,6 +27,7 @@
2627 import java.util.concurrent.*;
2728
2829 import static org.assertj.core.api.Assertions.assertThat;
30+import static org.assertj.core.api.Assertions.fail;
2931 import static org.testng.Assert.assertEquals;
3032 import static org.testng.Assert.assertTrue;
3133
@@ -119,6 +121,26 @@
119121 }
120122 }
121123
124+ @Test(groups = "short")
125+ public void should_fail_when_synchronous_call_on_io_thread() throws Exception {
126+ ResultSetFuture f = session().executeAsync("select release_version from system.local");
127+ ListenableFuture<Void> f2 = Futures.transform(f, new Function<ResultSet, Void>() {
128+ @Override
129+ public Void apply(ResultSet input) {
130+ session().execute("select release_version from system.local");
131+ return null;
132+ }
133+ });
134+ try {
135+ f2.get();
136+ fail("Expected a failed future");
137+ } catch (Exception e) {
138+ assertThat(Throwables.getRootCause(e))
139+ .isInstanceOf(IllegalStateException.class)
140+ .hasMessageContaining("Detected a synchronous Session call");
141+ }
142+ }
143+
122144 private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) {
123145 ListenableFuture<Session> sessionFuture = cluster().connectAsync(keyspace);
124146 ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() {
modified driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java +3 −0
@@ -24,6 +24,9 @@
2424
2525 /**
2626 * The configuration to use when running tests with {@link CCMTestsSupport}.
27+ * <p/>
28+ * This annotation can be used at the class level, or at the method level if you annotate the class with
29+ * {@code @CreateCCM(PER_METHOD)}.
2730 */
2831 @Retention(RUNTIME)
2932 @Target({TYPE, METHOD})
added driver-core/src/test/java/com/datastax/driver/core/ReusedStreamIdTest.java +154 −0
@@ -0,0 +1,154 @@
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.exceptions.NoHostAvailableException;
19+import com.google.common.util.concurrent.FutureCallback;
20+import com.google.common.util.concurrent.Futures;
21+import com.google.common.util.concurrent.Uninterruptibles;
22+import org.slf4j.Logger;
23+import org.slf4j.LoggerFactory;
24+import org.testng.annotations.Test;
25+
26+import java.util.List;
27+import java.util.Random;
28+import java.util.concurrent.CountDownLatch;
29+import java.util.concurrent.Semaphore;
30+import java.util.concurrent.TimeUnit;
31+import java.util.concurrent.atomic.AtomicInteger;
32+
33+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
34+import static org.assertj.core.api.Assertions.assertThat;
35+import static org.testng.Assert.fail;
36+
37+@CreateCCM(PER_METHOD)
38+public class ReusedStreamIdTest extends CCMTestsSupport {
39+
40+ static Logger logger = LoggerFactory.getLogger(ReusedStreamIdTest.class);
41+
42+ @SuppressWarnings("unused")
43+ public Cluster.Builder createClusterLowReadTimeout() {
44+ // Low Read Timeout to trigger retry behavior.
45+ return Cluster.builder().withSocketOptions(new SocketOptions().setReadTimeoutMillis(1000));
46+ }
47+
48+ /**
49+ * Ensures that if activity tied to future completion blocks netty io threads that this does not cause the
50+ * driver to possibly invoke the wrong handler for a response, as described in JAVA-1179.
51+ * <p/>
52+ * This is accomplished by setting up a 2 node cluster and setting a low read timeout (1 second). The test
53+ * submits 10 concurrent requests repeatedly for up to 500 queries and on completion of each request may block
54+ * in a callback randomly (25% of the time) for 1 second, causing a retry on the next host to trigger. If a new
55+ * stream id is not allocated on the retry, its possible it could use an already used stream id and cause the driver
56+ * to invoke the wrong handlers for a response. The test checks for this by ensuring that the column returned in a
57+ * response matches the one queried. If the column received does not match, the test fails. In cases where this
58+ * bug is present, it should be detected within 10 seconds.
59+ *
60+ * @jira_ticket JAVA-1179
61+ * @test_category queries:async_callback
62+ */
63+ @Test(groups = "long")
64+ @CCMConfig(numberOfNodes = 2, clusterProvider = "createClusterLowReadTimeout")
65+ public void should_not_receive_wrong_response_when_callbacks_block_io_thread() {
66+ int concurrency = 10;
67+ final Semaphore semaphore = new Semaphore(concurrency);
68+ // RNG to determine sleep times.
69+ final Random random = new Random();
70+
71+ try {
72+ // Use the system.local table and alternate between columns that are queried.
73+ List<ColumnMetadata> columnsToGrab = cluster().getMetadata().getKeyspace("system").getTable("local").getColumns();
74+ assertThat(columnsToGrab.size()).isGreaterThan(1);
75+
76+ final CountDownLatch errorTrigger = new CountDownLatch(1);
77+
78+ long start = System.currentTimeMillis();
79+ // 500 iterations will take roughly 1 minute.
80+ int iterations = 500;
81+ final AtomicInteger completed = new AtomicInteger(0);
82+
83+ for (int i = 1; i <= iterations; i++) {
84+ try {
85+ if (errorTrigger.getCount() == 0) {
86+ fail(String.format("Error triggered at or before %d of %d requests after %dms.", i, iterations,
87+ System.currentTimeMillis() - start));
88+ }
89+ semaphore.acquire();
90+ final String column = columnsToGrab.get(i % columnsToGrab.size()).getName();
91+ String query = String.format("select %s from system.local", column);
92+ ResultSetFuture future = session().executeAsync(query);
93+
94+ Futures.addCallback(future, new FutureCallback<ResultSet>() {
95+ @Override
96+ public void onSuccess(ResultSet result) {
97+ semaphore.release();
98+ // Expect the column that you queried to be present, if its not we got the wrong response
99+ // back.
100+ int columnIndex = result.getColumnDefinitions().getIndexOf(column);
101+ if (columnIndex == -1) {
102+ logger.error("Got response without column {}, got columns {} from Host {}.", column,
103+ result.getColumnDefinitions(), result.getExecutionInfo().getQueriedHost());
104+ errorTrigger.countDown();
105+ return;
106+ }
107+ completed.incrementAndGet();
108+ // Block netty io thread 25% of the time.
109+ int num = random.nextInt(1);
110+ if (num == 0) {
111+ // Sleep exactly one second, should trigger retry.
112+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
113+ }
114+ }
115+
116+ @Override
117+ public void onFailure(Throwable t) {
118+ semaphore.release();
119+ // NHAEs are inevitable because of low query timeouts and blocked threads.
120+ if (!(t instanceof NoHostAvailableException)) {
121+ logger.error("Unexpected error encountered.", t);
122+ errorTrigger.countDown();
123+ }
124+ }
125+ });
126+ } catch (InterruptedException e) {
127+ fail("Test interrupted", e);
128+ }
129+ if (i % (iterations / 10) == 0) {
130+ logger.info("Submitted {} of {} requests. ({} completed successfully)", i, iterations, completed.get());
131+ }
132+ }
133+
134+ // Wait for 10 seconds for any remaining requests to possibly trigger an error, its likely
135+ // that if we get to this point this will not happen.
136+ Uninterruptibles.awaitUninterruptibly(errorTrigger, 10, TimeUnit.SECONDS);
137+ if (errorTrigger.getCount() == 0) {
138+ fail(String.format("Error triggered after %dms.", System.currentTimeMillis() - start));
139+ }
140+ // Sanity check to ensure that at least some requests succeeded, we expect some failures if both
141+ // hosts timeout as its likely they could be blocked on the event loop.
142+ assertThat(completed.get()).isGreaterThan(0);
143+ } finally {
144+ try {
145+ // Acquire all permits to make sure all inflight requests complete.
146+ if (!semaphore.tryAcquire(concurrency, 10, TimeUnit.SECONDS)) {
147+ fail("Could not acquire all permits within 10 seconds of completion.");
148+ }
149+ } catch (InterruptedException e) {
150+ fail("Interrupted.", e);
151+ }
152+ }
153+ }
154+}