Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset876983ef4dbfa388609a9f8a674663a364cdd016d3d03bf1172c68f799b76588
Authorolim7t <omichallat+github@gmail.com> · 2016-05-09 11:56 -07:00
Committerolim7t <omichallat+github@gmail.com> · 2016-05-09 13:37 -07:00
Parents9c9a5537845d, b0c37523b22c

Browse the files at this changeset

11 files changed

modified changelog/README.md +16 −1
@@ -1,5 +1,13 @@
11 ## Changelog
22
3+### 2.1.10.2 (in progress)
4+
5+Merged from 2.0 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 ### 2.1.10.1
412
513 - [bug] JAVA-1152: Fix NPE at ControlConnection.refreshNodeListAndTokenMap().
@@ -391,12 +399,19 @@
391399 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
392400
393401
394-### 2.0.13 (in progress)
402+### 2.0.12.2
403+
404+- [bug] JAVA-1179: Request objects should be copied when executed.
405+- [improvement] JAVA-1182: Throw error when synchronous call made on I/O thread.
406+
407+
408+### 2.0.12.1
395409
396410 - [bug] JAVA-994: Don't call on(Up|Down|Add|Remove) methods if Cluster is closed/closing.
397411 - [improvement] JAVA-805: Document that metrics are null until Cluster is initialized.
398412 - [bug] JAVA-1072: Ensure defunct connections are properly evicted from the pool.
399413
414+
400415 ### 2.0.12
401416
402417 - [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
@@ -51,6 +51,7 @@
5151 */
5252 @Override
5353 public ResultSet execute(Statement statement) {
54+ checkNotInEventLoop();
5455 return executeAsync(statement).getUninterruptibly();
5556 }
5657
@@ -75,6 +76,7 @@
7576 */
7677 @Override
7778 public PreparedStatement prepare(String query) {
79+ checkNotInEventLoop();
7880 try {
7981 return Uninterruptibles.getUninterruptibly(prepareAsync(query));
8082 } catch (ExecutionException e) {
@@ -87,6 +89,7 @@
8789 */
8890 @Override
8991 public PreparedStatement prepare(RegularStatement statement) {
92+ checkNotInEventLoop();
9093 try {
9194 return Uninterruptibles.getUninterruptibly(prepareAsync(statement));
9295 } catch (ExecutionException e) {
@@ -135,4 +138,13 @@
135138 Thread.currentThread().interrupt();
136139 }
137140 }
141+
142+ /**
143+ * Checks that the current thread is not one of the Netty I/O threads used by the driver.
144+ * <p/>
145+ * This is called from the synchronous methods of this class to prevent deadlock issues.
146+ */
147+ protected void checkNotInEventLoop() {
148+ // This method is concrete only to avoid a breaking change. See subclass for the actual implementation.
149+ }
138150 }
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +3 −4
@@ -508,11 +508,10 @@
508508
509509 public ResponseHandler write(ResponseCallback callback, boolean startTimeout) throws ConnectionException, BusyConnectionException {
510510
511- Message.Request request = callback.request();
512-
513511 ResponseHandler handler = new ResponseHandler(this, 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 public 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
@@ -46,7 +46,7 @@
4646 public R decode(ByteBuf body, ProtocolVersion version);
4747 }
4848
49- private volatile int streamId;
49+ private volatile int streamId = -1;
5050
5151 protected Message() {
5252 }
@@ -94,6 +94,19 @@
9494 this.tracingRequested = tracingRequested;
9595 }
9696
97+ @Override
98+ public Request setStreamId(int streamId) {
99+ // JAVA-1179: defensively guard against reusing the same Request object twice.
100+ // If no streamId was ever set we can use this object directly, otherwise make a copy.
101+ if (getStreamId() < 0)
102+ return (Request) super.setStreamId(streamId);
103+ else {
104+ Request copy = this.copy();
105+ copy.setStreamId(streamId);
106+ return copy;
107+ }
108+ }
109+
97110 public boolean isTracingRequested() {
98111 return tracingRequested;
99112 }
@@ -148,9 +161,7 @@
148161 }
149162 }
150163
151- Request copy() {
152- throw new UnsupportedOperationException();
153- }
164+ abstract Request copy();
154165
155166 Request copy(ConsistencyLevel newConsistencyLevel) {
156167 throw new UnsupportedOperationException();
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +1 −5
@@ -64,7 +64,7 @@
6464 private final long startTime;
6565
6666 private final AtomicBoolean isDone = new AtomicBoolean();
67- private AtomicInteger executionCount = new AtomicInteger();
67+ private final AtomicInteger executionCount = new AtomicInteger();
6868
6969 public RequestHandler(SessionManager manager, Callback callback, Statement statement) {
7070 this.id = Long.toString(System.identityHashCode(this));
@@ -106,10 +106,6 @@
106106
107107 Message.Request request = callback.request();
108108 int position = executionCount.incrementAndGet();
109- // Clone the request after the first execution, since we set the streamId on it later and we
110- // don't want to share that across executions.
111- if (position > 1)
112- request = request.copy();
113109
114110 SpeculativeExecution execution = new SpeculativeExecution(request, position);
115111 runningExecutions.add(execution);
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +32 −0
@@ -48,9 +48,11 @@
4848 };
4949
5050 private final Map<String, String> options;
51+ private final ProtocolOptions.Compression compression;
5152
5253 public Startup(ProtocolOptions.Compression compression) {
5354 super(Message.Request.Type.STARTUP);
55+ this.compression = compression;
5456
5557 ImmutableMap.Builder<String, String> map = new ImmutableMap.Builder<String, String>();
5658 map.put(CQL_VERSION_OPTION, CQL_VERSION);
@@ -59,6 +61,11 @@
5961 this.options = map.build();
6062 }
6163
64+ @Override
65+ Request copy() {
66+ return new Startup(compression);
67+ }
68+
6269 @Override
6370 public String toString() {
6471 return "STARTUP " + options;
@@ -89,6 +96,11 @@
8996 super(Message.Request.Type.CREDENTIALS);
9097 this.credentials = credentials;
9198 }
99+
100+ @Override
101+ Request copy() {
102+ return new Credentials(credentials);
103+ }
92104 }
93105
94106 public static class Options extends Message.Request {
@@ -108,6 +120,11 @@
108120 super(Message.Request.Type.OPTIONS);
109121 }
110122
123+ @Override
124+ Request copy() {
125+ return new Options();
126+ }
127+
111128 @Override
112129 public String toString() {
113130 return "OPTIONS";
@@ -525,6 +542,11 @@
525542 this.query = query;
526543 }
527544
545+ @Override
546+ Request copy() {
547+ return new Prepare(query);
548+ }
549+
528550 @Override
529551 public String toString() {
530552 return "PREPARE " + query;
@@ -557,6 +579,11 @@
557579 this.eventTypes = eventTypes;
558580 }
559581
582+ @Override
583+ Request copy() {
584+ return new Register(eventTypes);
585+ }
586+
560587 @Override
561588 public String toString() {
562589 return "REGISTER " + eventTypes;
@@ -584,5 +611,10 @@
584611 super(Message.Request.Type.AUTH_RESPONSE);
585612 this.token = token;
586613 }
614+
615+ @Override
616+ Request copy() {
617+ return new AuthResponse(token);
618+ }
587619 }
588620 }
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +19 −0
@@ -27,6 +27,7 @@
2727 import com.google.common.collect.ImmutableList;
2828 import com.google.common.collect.Lists;
2929 import com.google.common.util.concurrent.*;
30+import io.netty.util.concurrent.EventExecutor;
3031 import org.slf4j.Logger;
3132 import org.slf4j.LoggerFactory;
3233
@@ -46,6 +47,9 @@
4647
4748 private static final Logger logger = LoggerFactory.getLogger(Session.class);
4849
50+ private static final boolean CHECK_IO_DEADLOCKS = SystemProperties.getBoolean(
51+ "com.datastax.driver.CHECK_IO_DEADLOCKS", true);
52+
4953 final Cluster cluster;
5054 final ConcurrentMap<Host, HostConnectionPool> pools;
5155 final HostConnectionPool.PoolState poolsState;
@@ -639,6 +643,21 @@
639643 }
640644 }
641645
646+ @Override
647+ protected void checkNotInEventLoop() {
648+ if (!CHECK_IO_DEADLOCKS)
649+ return;
650+ for (EventExecutor executor : cluster.manager.connectionFactory.eventLoopGroup) {
651+ if (executor.inEventLoop()) {
652+ throw new IllegalStateException(
653+ "Detected a synchronous Session call (execute() or prepare()) on an I/O thread, " +
654+ "this can cause deadlocks or unpredictable behavior. " +
655+ "Make sure your Future callbacks only use async calls, or schedule them on a " +
656+ "different executor.");
657+ }
658+ }
659+ }
660+
642661 private static class State implements Session.State {
643662
644663 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
@@ -125,6 +127,26 @@
125127 }
126128 }
127129
130+ @Test(groups = "short")
131+ public void should_fail_when_synchronous_call_on_io_thread() throws Exception {
132+ ResultSetFuture f = session().executeAsync("select release_version from system.local");
133+ ListenableFuture<Void> f2 = Futures.transform(f, new Function<ResultSet, Void>() {
134+ @Override
135+ public Void apply(ResultSet input) {
136+ session().execute("select release_version from system.local");
137+ return null;
138+ }
139+ });
140+ try {
141+ f2.get();
142+ fail("Expected a failed future");
143+ } catch (Exception e) {
144+ assertThat(Throwables.getRootCause(e))
145+ .isInstanceOf(IllegalStateException.class)
146+ .hasMessageContaining("Detected a synchronous Session call");
147+ }
148+ }
149+
128150 private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) {
129151 ListenableFuture<Session> sessionFuture = cluster().connectAsync(keyspace);
130152 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+}