kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 4b35bd0a42ce10d331fc5f1ecf01475f3b4ca7145414229bb708c1d0b25afb4c |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2016-05-09 13:58 -07:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-05-09 13:59 -07:00 |
| Parents | 9aa33e768895, 876983ef4dbf |
11 files changed
modified changelog/README.md +30 −1
| @@ -1,5 +1,13 @@ | ||
| 1 | 1 | ## Changelog |
| 2 | 2 | |
| 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 | + | |
| 3 | 11 | ### 3.0.1 |
| 4 | 12 | |
| 5 | 13 | - [bug] JAVA-1132: Executing bound statement with no variables results in exception with protocol v1. |
| @@ -309,6 +317,20 @@ | ||
| 309 | 317 | - [improvement] JAVA-782: Unify "Target" enum for schema elements. |
| 310 | 318 | |
| 311 | 319 | |
| 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 | + | |
| 312 | 334 | ### 2.1.10 |
| 313 | 335 | |
| 314 | 336 | - [bug] JAVA-988: Metadata.handleId should handle escaped double quotes. |
| @@ -678,12 +700,19 @@ | ||
| 678 | 700 | - [bug] JAVA-377, JAVA-391: Make metadata parsing more lenient. |
| 679 | 701 | |
| 680 | 702 | |
| 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 | |
| 682 | 710 | |
| 683 | 711 | - [bug] JAVA-994: Don't call on(Up|Down|Add|Remove) methods if Cluster is closed/closing. |
| 684 | 712 | - [improvement] JAVA-805: Document that metrics are null until Cluster is initialized. |
| 685 | 713 | - [bug] JAVA-1072: Ensure defunct connections are properly evicted from the pool. |
| 686 | 714 | |
| 715 | + | |
| 687 | 716 | ### 2.0.12 |
| 688 | 717 | |
| 689 | 718 | - [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 @@ | ||
| 60 | 60 | */ |
| 61 | 61 | @Override |
| 62 | 62 | public ResultSet execute(Statement statement) { |
| 63 | + checkNotInEventLoop(); | |
| 63 | 64 | return executeAsync(statement).getUninterruptibly(); |
| 64 | 65 | } |
| 65 | 66 | |
| @@ -92,6 +93,7 @@ | ||
| 92 | 93 | */ |
| 93 | 94 | @Override |
| 94 | 95 | public PreparedStatement prepare(String query) { |
| 96 | + checkNotInEventLoop(); | |
| 95 | 97 | try { |
| 96 | 98 | return Uninterruptibles.getUninterruptibly(prepareAsync(query)); |
| 97 | 99 | } catch (ExecutionException e) { |
| @@ -104,6 +106,7 @@ | ||
| 104 | 106 | */ |
| 105 | 107 | @Override |
| 106 | 108 | public PreparedStatement prepare(RegularStatement statement) { |
| 109 | + checkNotInEventLoop(); | |
| 107 | 110 | try { |
| 108 | 111 | return Uninterruptibles.getUninterruptibly(prepareAsync(statement)); |
| 109 | 112 | } catch (ExecutionException e) { |
| @@ -172,4 +175,13 @@ | ||
| 172 | 175 | Thread.currentThread().interrupt(); |
| 173 | 176 | } |
| 174 | 177 | } |
| 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 | + } | |
| 175 | 187 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +3 −4
| @@ -508,11 +508,10 @@ | ||
| 508 | 508 | |
| 509 | 509 | ResponseHandler write(ResponseCallback callback, long statementReadTimeoutMillis, boolean startTimeout) throws ConnectionException, BusyConnectionException { |
| 510 | 510 | |
| 511 | - Message.Request request = callback.request(); | |
| 512 | - | |
| 513 | 511 | ResponseHandler handler = new ResponseHandler(this, statementReadTimeoutMillis, callback); |
| 514 | 512 | dispatcher.add(handler); |
| 515 | - request.setStreamId(handler.streamId); | |
| 513 | + | |
| 514 | + Message.Request request = callback.request().setStreamId(handler.streamId); | |
| 516 | 515 | |
| 517 | 516 | /* |
| 518 | 517 | * We check for close/defunct *after* having set the handler because closing/defuncting |
| @@ -686,7 +685,7 @@ | ||
| 686 | 685 | |
| 687 | 686 | final Timer timer; |
| 688 | 687 | |
| 689 | - private final EventLoopGroup eventLoopGroup; | |
| 688 | + final EventLoopGroup eventLoopGroup; | |
| 690 | 689 | private final Class<? extends Channel> channelClass; |
| 691 | 690 | |
| 692 | 691 | 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 @@ | ||
| 48 | 48 | R decode(ByteBuf body, ProtocolVersion version, CodecRegistry codecRegistry); |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | - private volatile int streamId; | |
| 51 | + private volatile int streamId = -1; | |
| 52 | 52 | |
| 53 | 53 | /** |
| 54 | 54 | * A generic key-value custom payload. Custom payloads are simply |
| @@ -113,6 +113,19 @@ | ||
| 113 | 113 | this.tracingRequested = tracingRequested; |
| 114 | 114 | } |
| 115 | 115 | |
| 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 | + | |
| 116 | 129 | boolean isTracingRequested() { |
| 117 | 130 | return tracingRequested; |
| 118 | 131 | } |
| @@ -167,9 +180,7 @@ | ||
| 167 | 180 | } |
| 168 | 181 | } |
| 169 | 182 | |
| 170 | - Request copy() { | |
| 171 | - throw new UnsupportedOperationException(); | |
| 172 | - } | |
| 183 | + abstract Request copy(); | |
| 173 | 184 | |
| 174 | 185 | Request copy(ConsistencyLevel newConsistencyLevel) { |
| 175 | 186 | throw new UnsupportedOperationException(); |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +1 −5
| @@ -63,7 +63,7 @@ | ||
| 63 | 63 | private final long startTime; |
| 64 | 64 | |
| 65 | 65 | private final AtomicBoolean isDone = new AtomicBoolean(); |
| 66 | - private AtomicInteger executionCount = new AtomicInteger(); | |
| 66 | + private final AtomicInteger executionCount = new AtomicInteger(); | |
| 67 | 67 | |
| 68 | 68 | public RequestHandler(SessionManager manager, Callback callback, Statement statement) { |
| 69 | 69 | this.id = Long.toString(System.identityHashCode(this)); |
| @@ -105,10 +105,6 @@ | ||
| 105 | 105 | |
| 106 | 106 | Message.Request request = callback.request(); |
| 107 | 107 | 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(); | |
| 112 | 108 | |
| 113 | 109 | SpeculativeExecution execution = new SpeculativeExecution(request, position); |
| 114 | 110 | runningExecutions.add(execution); |
modified driver-core/src/main/java/com/datastax/driver/core/Requests.java +32 −0
| @@ -49,9 +49,11 @@ | ||
| 49 | 49 | }; |
| 50 | 50 | |
| 51 | 51 | private final Map<String, String> options; |
| 52 | + private final ProtocolOptions.Compression compression; | |
| 52 | 53 | |
| 53 | 54 | Startup(ProtocolOptions.Compression compression) { |
| 54 | 55 | super(Message.Request.Type.STARTUP); |
| 56 | + this.compression = compression; | |
| 55 | 57 | |
| 56 | 58 | ImmutableMap.Builder<String, String> map = new ImmutableMap.Builder<String, String>(); |
| 57 | 59 | map.put(CQL_VERSION_OPTION, CQL_VERSION); |
| @@ -60,6 +62,11 @@ | ||
| 60 | 62 | this.options = map.build(); |
| 61 | 63 | } |
| 62 | 64 | |
| 65 | + @Override | |
| 66 | + Request copy() { | |
| 67 | + return new Startup(compression); | |
| 68 | + } | |
| 69 | + | |
| 63 | 70 | @Override |
| 64 | 71 | public String toString() { |
| 65 | 72 | return "STARTUP " + options; |
| @@ -90,6 +97,11 @@ | ||
| 90 | 97 | super(Message.Request.Type.CREDENTIALS); |
| 91 | 98 | this.credentials = credentials; |
| 92 | 99 | } |
| 100 | + | |
| 101 | + @Override | |
| 102 | + Request copy() { | |
| 103 | + return new Credentials(credentials); | |
| 104 | + } | |
| 93 | 105 | } |
| 94 | 106 | |
| 95 | 107 | static class Options extends Message.Request { |
| @@ -109,6 +121,11 @@ | ||
| 109 | 121 | super(Message.Request.Type.OPTIONS); |
| 110 | 122 | } |
| 111 | 123 | |
| 124 | + @Override | |
| 125 | + Request copy() { | |
| 126 | + return new Options(); | |
| 127 | + } | |
| 128 | + | |
| 112 | 129 | @Override |
| 113 | 130 | public String toString() { |
| 114 | 131 | return "OPTIONS"; |
| @@ -553,6 +570,11 @@ | ||
| 553 | 570 | this.query = query; |
| 554 | 571 | } |
| 555 | 572 | |
| 573 | + @Override | |
| 574 | + Request copy() { | |
| 575 | + return new Prepare(query); | |
| 576 | + } | |
| 577 | + | |
| 556 | 578 | @Override |
| 557 | 579 | public String toString() { |
| 558 | 580 | return "PREPARE " + query; |
| @@ -585,6 +607,11 @@ | ||
| 585 | 607 | this.eventTypes = eventTypes; |
| 586 | 608 | } |
| 587 | 609 | |
| 610 | + @Override | |
| 611 | + Request copy() { | |
| 612 | + return new Register(eventTypes); | |
| 613 | + } | |
| 614 | + | |
| 588 | 615 | @Override |
| 589 | 616 | public String toString() { |
| 590 | 617 | return "REGISTER " + eventTypes; |
| @@ -612,5 +639,10 @@ | ||
| 612 | 639 | super(Message.Request.Type.AUTH_RESPONSE); |
| 613 | 640 | this.token = token; |
| 614 | 641 | } |
| 642 | + | |
| 643 | + @Override | |
| 644 | + Request copy() { | |
| 645 | + return new AuthResponse(token); | |
| 646 | + } | |
| 615 | 647 | } |
| 616 | 648 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +19 −0
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | import com.google.common.collect.ImmutableList; |
| 29 | 29 | import com.google.common.collect.Lists; |
| 30 | 30 | import com.google.common.util.concurrent.*; |
| 31 | +import io.netty.util.concurrent.EventExecutor; | |
| 31 | 32 | import org.slf4j.Logger; |
| 32 | 33 | import org.slf4j.LoggerFactory; |
| 33 | 34 | |
| @@ -47,6 +48,9 @@ | ||
| 47 | 48 | |
| 48 | 49 | private static final Logger logger = LoggerFactory.getLogger(Session.class); |
| 49 | 50 | |
| 51 | + private static final boolean CHECK_IO_DEADLOCKS = SystemProperties.getBoolean( | |
| 52 | + "com.datastax.driver.CHECK_IO_DEADLOCKS", true); | |
| 53 | + | |
| 50 | 54 | final Cluster cluster; |
| 51 | 55 | final ConcurrentMap<Host, HostConnectionPool> pools; |
| 52 | 56 | final HostConnectionPool.PoolState poolsState; |
| @@ -661,6 +665,21 @@ | ||
| 661 | 665 | } |
| 662 | 666 | } |
| 663 | 667 | |
| 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 | + | |
| 664 | 683 | private static class State implements Session.State { |
| 665 | 684 | |
| 666 | 685 | private final SessionManager session; |
modified driver-core/src/main/java/com/datastax/driver/core/SystemProperties.java +3 −3
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | /** |
| 22 | 22 | * Allows overriding internal settings via system properties. |
| 23 | 23 | * <p/> |
| 24 | - * Warning: this is meant for integration tests only, NOT FOR PRODUCTION USE. | |
| 24 | + * This is generally reserved for tests or "expert" usage. | |
| 25 | 25 | */ |
| 26 | 26 | class SystemProperties { |
| 27 | 27 | private static final Logger logger = LoggerFactory.getLogger(SystemProperties.class); |
| @@ -34,7 +34,7 @@ | ||
| 34 | 34 | } |
| 35 | 35 | try { |
| 36 | 36 | int value = Integer.parseInt(stringValue); |
| 37 | - logger.warn("{} is defined, using value {}", key, value); | |
| 37 | + logger.info("{} is defined, using value {}", key, value); | |
| 38 | 38 | return value; |
| 39 | 39 | } catch (NumberFormatException e) { |
| 40 | 40 | logger.warn("{} is defined but could not parse value {}, using default value {}", key, stringValue, defaultValue); |
| @@ -50,7 +50,7 @@ | ||
| 50 | 50 | } |
| 51 | 51 | try { |
| 52 | 52 | boolean value = Boolean.parseBoolean(stringValue); |
| 53 | - logger.warn("{} is defined, using value {}", key, value); | |
| 53 | + logger.info("{} is defined, using value {}", key, value); | |
| 54 | 54 | return value; |
| 55 | 55 | } catch (NumberFormatException e) { |
| 56 | 56 | 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 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 19 | 19 | import com.google.common.base.Function; |
| 20 | +import com.google.common.base.Throwables; | |
| 20 | 21 | import com.google.common.collect.Lists; |
| 21 | 22 | import com.google.common.util.concurrent.*; |
| 22 | 23 | import org.testng.annotations.DataProvider; |
| @@ -26,6 +27,7 @@ | ||
| 26 | 27 | import java.util.concurrent.*; |
| 27 | 28 | |
| 28 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 30 | +import static org.assertj.core.api.Assertions.fail; | |
| 29 | 31 | import static org.testng.Assert.assertEquals; |
| 30 | 32 | import static org.testng.Assert.assertTrue; |
| 31 | 33 | |
| @@ -119,6 +121,26 @@ | ||
| 119 | 121 | } |
| 120 | 122 | } |
| 121 | 123 | |
| 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 | + | |
| 122 | 144 | private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) { |
| 123 | 145 | ListenableFuture<Session> sessionFuture = cluster().connectAsync(keyspace); |
| 124 | 146 | 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 @@ | ||
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | 26 | * 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)}. | |
| 27 | 30 | */ |
| 28 | 31 | @Retention(RUNTIME) |
| 29 | 32 | @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 | +} |