Elffuss BraidHub

kikocis/java-driver public

Fix keyspace handling + tests

Protects overrun of 'USE <keyspace>' requests on a connection by
tracking an in flight 'USE <keyspace>' request. If the target keyspace
is the same, the future tied to that attempt is used.
Changeset307a50ac64a5e66c5779cf285bcbd1bb66ded910f1edcaa20cfef72c20e67cd0
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2016-09-22 14:20 -05:00
Committerolim7t <omichallat+github@gmail.com> · 2016-09-23 22:42 -07:00
Parentsed90b7b4a2f8

Browse the files at this changeset

3 files changed

modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +86 −25
@@ -19,7 +19,6 @@
1919 import com.datastax.driver.core.exceptions.*;
2020 import com.datastax.driver.core.utils.MoreFutures;
2121 import com.google.common.annotations.VisibleForTesting;
22-import com.google.common.base.Function;
2322 import com.google.common.base.Objects;
2423 import com.google.common.collect.Lists;
2524 import com.google.common.collect.MapMaker;
@@ -87,7 +86,9 @@
8786 final AtomicInteger inFlight = new AtomicInteger(0);
8887
8988 private final AtomicInteger writer = new AtomicInteger(0);
90- private volatile String keyspace;
89+
90+ private final AtomicReference<SetKeyspaceAttempt> targetKeyspace;
91+ private final SetKeyspaceAttempt defaultKeyspaceAttempt;
9192
9293 private volatile boolean isInitialized;
9394 private final AtomicBoolean isDefunct = new AtomicBoolean();
@@ -115,6 +116,8 @@
115116 this.name = name;
116117 this.ownerRef.set(owner);
117118 this.thisFuture = Futures.immediateFuture(this);
119+ this.defaultKeyspaceAttempt = new SetKeyspaceAttempt(null, thisFuture);
120+ this.targetKeyspace = new AtomicReference<SetKeyspaceAttempt>(defaultKeyspaceAttempt);
118121 }
119122
120123 /**
@@ -422,7 +425,6 @@
422425 else if (Host.statesLogger.isDebugEnabled())
423426 Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage());
424427
425-
426428 Host host = factory.manager.metadata.getHost(address);
427429 if (host != null) {
428430 // Sometimes close() can be called before defunct(); avoid decrementing the connection count twice, but
@@ -456,14 +458,14 @@
456458 }
457459
458460 String keyspace() {
459- return keyspace;
461+ return targetKeyspace.get().keyspace;
460462 }
461463
462464 void setKeyspace(String keyspace) throws ConnectionException {
463465 if (keyspace == null)
464466 return;
465467
466- if (this.keyspace != null && this.keyspace.equals(keyspace))
468+ if (Objects.equal(keyspace(), keyspace))
467469 return;
468470
469471 try {
@@ -488,27 +490,58 @@
488490 }
489491
490492 ListenableFuture<Connection> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
491- if (Objects.equal(this.keyspace, keyspace)) {
492- return thisFuture;
493- }
493+ SetKeyspaceAttempt existingAttempt = targetKeyspace.get();
494+ if (Objects.equal(existingAttempt.keyspace, keyspace))
495+ return existingAttempt.future;
496+
497+ final SettableFuture<Connection> ksFuture = SettableFuture.create();
498+ final SetKeyspaceAttempt attempt = new SetKeyspaceAttempt(keyspace, ksFuture);
499+
500+ // Check for an existing keyspace attempt.
501+ while (true) {
502+ existingAttempt = targetKeyspace.get();
503+ // if existing attempts' keyspace matches what we are trying to set, use it.
504+ if (attempt.equals(existingAttempt)) {
505+ return existingAttempt.future;
506+ } else if (!existingAttempt.future.isDone()) {
507+ // If the existing attempt is still in flight, fail this attempt immediately.
508+ ksFuture.setException(new DriverException("Aborting attempt to set keyspace to '" + keyspace + "' since there is already an in flight attempt to set keyspace to '" + existingAttempt.keyspace + "'. "
509+ + "This can happen if you try to USE different keyspaces from the same session simultaneously."));
510+ return ksFuture;
511+ } else if (targetKeyspace.compareAndSet(existingAttempt, attempt)) {
512+ // Otherwise, if the existing attempt is done, start a new set keyspace attempt for the new keyspace.
513+ logger.debug("{} Setting keyspace {}", this, keyspace);
514+ // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
515+ Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
516+ Futures.addCallback(future, new FutureCallback<Message.Response>() {
517+
518+ @Override
519+ public void onSuccess(Message.Response response) {
520+ if (response instanceof SetKeyspace) {
521+ logger.debug("{} Keyspace set to {}", Connection.this, keyspace);
522+ ksFuture.set(Connection.this);
523+ } else {
524+ // Unset this attempt so new attempts may be made for the same keyspace.
525+ targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt);
526+ if (response.type == ERROR) {
527+ Responses.Error error = (Responses.Error) response;
528+ ksFuture.setException(defunct(error.asException(address)));
529+ } else {
530+ ksFuture.setException(defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response)));
531+ }
532+ }
533+ }
494534
495- logger.trace("{} Setting keyspace {}", this, keyspace);
496- // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
497- Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
498- return Futures.transform(future, new Function<Message.Response, Connection>() {
499- @Override
500- public Connection apply(Message.Response response) {
501- if (response instanceof SetKeyspace) {
502- Connection.this.keyspace = ((SetKeyspace) response).keyspace;
503- return Connection.this;
504- } else if (response.type == ERROR) {
505- Responses.Error error = (Responses.Error) response;
506- throw defunct(error.asException(address));
507- } else {
508- throw defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response));
509- }
535+ @Override
536+ public void onFailure(Throwable t) {
537+ targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt);
538+ ksFuture.setException(t);
539+ }
540+ }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor());
541+
542+ return ksFuture;
510543 }
511- }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor());
544+ }
512545 }
513546
514547 /**
@@ -1189,6 +1222,34 @@
11891222 }
11901223 }
11911224
1225+ private class SetKeyspaceAttempt {
1226+ private final String keyspace;
1227+ private final ListenableFuture<Connection> future;
1228+
1229+ SetKeyspaceAttempt(String keyspace, ListenableFuture<Connection> future) {
1230+ this.keyspace = keyspace;
1231+ this.future = future;
1232+ }
1233+
1234+ @Override
1235+ public boolean equals(Object o) {
1236+ if (this == o)
1237+ return true;
1238+ if (!(o instanceof SetKeyspaceAttempt))
1239+ return false;
1240+
1241+ SetKeyspaceAttempt that = (SetKeyspaceAttempt) o;
1242+
1243+ return keyspace != null ? keyspace.equals(that.keyspace) : that.keyspace == null;
1244+
1245+ }
1246+
1247+ @Override
1248+ public int hashCode() {
1249+ return keyspace != null ? keyspace.hashCode() : 0;
1250+ }
1251+ }
1252+
11921253 static class Future extends AbstractFuture<Message.Response> implements RequestHandler.Callback {
11931254
11941255 private final Message.Request request;
@@ -1358,7 +1419,7 @@
13581419 pipeline.addLast("ssl", sslOptions.newSSLHandler(channel));
13591420 }
13601421
1361-// pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
1422+ // pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
13621423
13631424 pipeline.addLast("frameDecoder", new Frame.Decoder());
13641425 pipeline.addLast("frameEncoder", frameEncoder);
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +27 −6
@@ -28,10 +28,7 @@
2828 import org.slf4j.LoggerFactory;
2929
3030 import java.util.*;
31-import java.util.concurrent.ConcurrentLinkedQueue;
32-import java.util.concurrent.CopyOnWriteArrayList;
33-import java.util.concurrent.CopyOnWriteArraySet;
34-import java.util.concurrent.Executor;
31+import java.util.concurrent.*;
3532 import java.util.concurrent.atomic.AtomicInteger;
3633 import java.util.concurrent.atomic.AtomicReference;
3734
@@ -337,14 +334,37 @@
337334 }
338335 }
339336
340- SettableFuture<Connection> pendingBorrow = pendingBorrows.poll();
337+ final SettableFuture<Connection> pendingBorrow = pendingBorrows.poll();
341338 if (pendingBorrow == null) {
342339 // Another thread has emptied the queue since our last check, restore the count
343340 connection.inFlight.decrementAndGet();
344341 } else {
345342 totalInFlight.incrementAndGet();
346343 pendingBorrowCount.decrementAndGet();
347- pendingBorrow.set(connection);
344+ // Ensure that the keyspace set on the connection is the one set on the pool state, in the general case it will be.
345+ ListenableFuture<Connection> setKeyspaceFuture = connection.setKeyspaceAsync(manager.poolsState.keyspace);
346+ // Slight optimization, if the keyspace was already correct the future will be complete, so simply complete it here.
347+ if (setKeyspaceFuture.isDone()) {
348+ try {
349+ pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture));
350+ } catch (ExecutionException e) {
351+ pendingBorrow.setException(e.getCause());
352+ }
353+ } else {
354+ // Otherwise the keyspace did need to be set, tie the pendingBorrow future to the set keyspace completion.
355+ Futures.addCallback(setKeyspaceFuture, new FutureCallback<Connection>() {
356+
357+ @Override
358+ public void onSuccess(Connection c) {
359+ pendingBorrow.set(c);
360+ }
361+
362+ @Override
363+ public void onFailure(Throwable t) {
364+ pendingBorrow.setException(t);
365+ }
366+ });
367+ }
348368 }
349369 }
350370 }
@@ -413,6 +433,7 @@
413433 }
414434 logger.debug("Creating new connection on busy pool to {}", host);
415435 newConnection = manager.connectionFactory().open(this);
436+ newConnection.setKeyspace(manager.poolsState.keyspace);
416437 }
417438 connections.add(newConnection);
418439
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +225 −12
@@ -16,8 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.codahale.metrics.Gauge;
19-import com.datastax.driver.core.exceptions.BusyConnectionException;
20-import com.datastax.driver.core.exceptions.ConnectionException;
19+import com.datastax.driver.core.exceptions.*;
2120 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2221 import com.datastax.driver.core.utils.MoreFutures;
2322 import com.google.common.base.Predicate;
@@ -112,14 +111,231 @@
112111 MockRequest failedBorrow = MockRequest.send(pool, maxQueueSize);
113112 try {
114113 failedBorrow.getConnection();
115- fail("Expected a ConnectionException");
116- } catch (ConnectionException e) { /*expected*/}
114+ fail("Expected a BusyPoolException");
115+ } catch (BusyPoolException e) {/*expected*/}
117116 } finally {
118117 MockRequest.completeAll(allRequests);
119118 cluster.close();
120119 }
121120 }
122121
122+ /**
123+ * Ensures that any enqueued connection borrow requests are failed when their associated connection pool closes.
124+ *
125+ * @jira_ticket JAVA-839
126+ * @test_category connection:connection_pool
127+ * @since 3.0.4, 3.1.1
128+ */
129+ @Test(groups = "short")
130+ public void requests_with_enqueued_borrow_requests_should_be_failed_when_pool_closes() {
131+ Cluster cluster = createClusterBuilder().build();
132+ List<MockRequest> requests = newArrayList();
133+ try {
134+ HostConnectionPool pool = createPool(cluster, 2, 2);
135+ int maxQueueSize = 256;
136+
137+ assertThat(pool.connections.size()).isEqualTo(2);
138+ List<Connection> coreConnections = newArrayList(pool.connections);
139+ // fill connections
140+ requests = MockRequest.sendMany(2 * 128, pool);
141+ assertBorrowedConnections(requests, coreConnections);
142+ // fill queue
143+ List<MockRequest> queuedRequests = MockRequest.sendMany(maxQueueSize, pool, maxQueueSize);
144+
145+ // Closing the pool should fail all queued connections.
146+ pool.closeAsync();
147+
148+ for (MockRequest queuedRequest : queuedRequests) {
149+ // Future should be completed.
150+ assertThat(queuedRequest.connectionFuture.isDone()).isTrue();
151+ try {
152+ // Future should fail as result of the pool closing.
153+ queuedRequest.getConnection();
154+ fail("Expected a ConnectionException");
155+ } catch (ConnectionException e) {/*expected*/}
156+ }
157+ } finally {
158+ MockRequest.completeAll(requests);
159+ cluster.close();
160+ }
161+ }
162+
163+ /**
164+ * Validates that if the keyspace tied to the Session's pool state is different than the keyspace on the connection
165+ * being used in dequeue that {@link Connection#setKeyspaceAsync(String)} is set on that connection and that
166+ * "USE keyspace" is only called once since setKeyspaceAsync should not attempt setting the keyspace if there is
167+ * already a request inflight that is doing this.
168+ *
169+ * @jira_ticket JAVA-839
170+ * @test_category connection:connection_pool
171+ * @since 3.0.4, 3.1.1
172+ */
173+ @Test(groups = "short")
174+ public void should_adjust_connection_keyspace_on_dequeue_if_pool_state_is_different() throws TimeoutException, ExecutionException {
175+ Cluster cluster = createClusterBuilder().build();
176+ List<MockRequest> requests = newArrayList();
177+ try {
178+ HostConnectionPool pool = createPool(cluster, 1, 1);
179+ int maxQueueSize = 256;
180+
181+ assertThat(pool.connections.size()).isEqualTo(1);
182+ List<Connection> coreConnections = newArrayList(pool.connections);
183+ // fill connections
184+ requests = MockRequest.sendMany(128, pool);
185+ assertBorrowedConnections(requests, coreConnections);
186+ // fill queue
187+ List<MockRequest> queuedRequests = MockRequest.sendMany(maxQueueSize, pool, maxQueueSize);
188+
189+ // Wait for connections to be borrowed before changing keyspace.
190+ for (MockRequest request : requests) {
191+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
192+ }
193+ // Simulate change of keyspace on pool. Prime a delay so existing requests can complete beforehand.
194+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"newkeyspace\"").withThen(PrimingRequest.then().withFixedDelay(2000L)));
195+ pool.manager.poolsState.setKeyspace("newkeyspace");
196+
197+ // Complete all requests, this should cause dequeue on connection.
198+ MockRequest.completeAll(requests);
199+
200+ // Check the status on queued request's connection futures. We expect that dequeue should
201+ // be called when connection is released by previous requests completing, and that one set
202+ // keyspace attempt should be tried.
203+
204+ // Because Scassandra currently returns a 'ROWS' response for set keyspace, the attempt
205+ // will fail, and thus the enqueued connection futures will fail in the following ways:
206+ // 1. DriverInternalError for set keyspace returning 'ROWS' response
207+ // 2. TransportException for connection being closed, when this happens we stop checking these futures.
208+ // 3. Never completing because no connections are available.
209+ boolean timeoutAcceptable = false;
210+ for (MockRequest queuedRequest : queuedRequests) {
211+ try {
212+ Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS);
213+ fail("Expected an exception (because Scassandra doesn't support 'USE keyspace'");
214+ } catch (ExecutionException e) {
215+ try {
216+ throw e.getCause();
217+ } catch (DriverInternalError die) {
218+ assertThat(die.getMessage()).contains("Unexpected response while setting keyspace");
219+ // Subsequent futures may timeout because the connection is closed.
220+ timeoutAcceptable = true;
221+ } catch (TransportException ce) {
222+ /* expected, Scassandra returning a ROWS response for 'USE keyspace' should defunct and close the connection */
223+ // all remaining futures will timeout since there are no remaining connections.
224+ break;
225+ } catch (Throwable t) {
226+ fail("Unexpected cause of future failing", t);
227+ }
228+ } catch (TimeoutException te) {
229+ assertThat(timeoutAcceptable).isTrue();
230+ break;
231+ }
232+ }
233+
234+ // We should only have gotten one 'USE newkeyspace' query since Connection#setKeyspaceAsync should only do
235+ // this once if there is already a request in flight.
236+ assertThat(activityClient.retrieveQueries()).extractingResultOf("getQuery").containsOnlyOnce("USE \"newkeyspace\"");
237+ } finally {
238+ MockRequest.completeAll(requests);
239+ cluster.close();
240+ }
241+ }
242+
243+ /**
244+ * Ensures that on borrowConnection if a set keyspace attempt is in progress on that connection for a different keyspace than the
245+ * pool state that the borrowConnection future returned is failed.
246+ *
247+ * @jira_ticket JAVA-839
248+ * @test_category connection:connection_pool
249+ * @since 3.0.4, 3.1.1
250+ */
251+ @Test(groups = "short")
252+ public void should_fail_in_borrowConnection_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() throws TimeoutException {
253+ Cluster cluster = createClusterBuilder().build();
254+ try {
255+ HostConnectionPool pool = createPool(cluster, 1, 1);
256+
257+ // Respond to setting as slowks very slowly.
258+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"slowks\"").withThen(PrimingRequest.then().withFixedDelay(5000L)));
259+
260+ Connection connection = pool.connections.get(0);
261+
262+ connection.setKeyspaceAsync("slowks");
263+
264+ // Simulate change of keyspace on pool.
265+ pool.manager.poolsState.setKeyspace("newks");
266+
267+ MockRequest request = MockRequest.send(pool);
268+
269+ try {
270+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
271+ fail("Should have thrown exception");
272+ } catch (ExecutionException e) {
273+ assertThat(e.getCause()).isInstanceOf(DriverException.class);
274+ assertThat(e.getCause().getMessage()).contains("Aborting attempt to set keyspace to 'newks' since there is already an in flight attempt to set keyspace to 'slowks'.");
275+ }
276+ } finally {
277+ cluster.close();
278+ }
279+ }
280+
281+ /**
282+ * Ensures that while dequeuing borrow connection requests that if a set keyspace attempt is in progress on that connection for a difference
283+ * keyspace than the pool state that the future for that borrow attempt is failed.
284+ *
285+ * @jira_ticket JAVA-839
286+ * @test_category connection:connection_pool
287+ * @since 3.0.4, 3.1.1
288+ */
289+ @Test(groups = "short")
290+ public void should_fail_in_dequeue_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() throws ExecutionException, TimeoutException {
291+ Cluster cluster = createClusterBuilder().build();
292+ List<MockRequest> requests = newArrayList();
293+ try {
294+ // Limit requests per connection to 100 so we don't exhaust stream ids.
295+ cluster.getConfiguration().getPoolingOptions().setMaxRequestsPerConnection(HostDistance.LOCAL, 100);
296+ HostConnectionPool pool = createPool(cluster, 1, 1);
297+ int maxQueueSize = 256;
298+
299+ assertThat(pool.connections.size()).isEqualTo(1);
300+ List<Connection> coreConnections = newArrayList(pool.connections);
301+
302+ // fill connections
303+ requests = MockRequest.sendMany(100, pool);
304+ assertBorrowedConnections(requests, coreConnections);
305+
306+ // send a request that will be queued.
307+ MockRequest queuedRequest = MockRequest.send(pool, maxQueueSize);
308+
309+ // Wait for connections to be borrowed before changing keyspace.
310+ for (MockRequest request : requests) {
311+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
312+ }
313+
314+ // Respond to setting as slowks very slowly.
315+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"slowks\"").withThen(PrimingRequest.then().withFixedDelay(5000L)));
316+ Connection connection = pool.connections.get(0);
317+ connection.setKeyspaceAsync("slowks");
318+
319+ // Simulate change of keyspace on pool.
320+ pool.manager.poolsState.setKeyspace("newkeyspace");
321+
322+ // Complete all requests, this should cause dequeue on connection.
323+ MockRequest.completeAll(requests);
324+
325+ try {
326+ Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS);
327+ fail("Should have thrown exception");
328+ } catch (ExecutionException e) {
329+ assertThat(e.getCause()).isInstanceOf(DriverException.class);
330+ assertThat(e.getCause().getMessage()).contains("Aborting attempt to set keyspace to 'newkeyspace' since there is already an in flight attempt to set keyspace to 'slowks'.");
331+ }
332+
333+ } finally {
334+ MockRequest.completeAll(requests);
335+ cluster.close();
336+ }
337+ }
338+
123339 /**
124340 * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
125341 * return a failed future instead of creating a new connection.
@@ -129,7 +345,7 @@
129345 * @since 2.0.10, 2.1.6
130346 */
131347 @Test(groups = "short")
132- public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
348+ public void variable_size_pool_should_fill_its_connections_and_then_reject() throws Exception {
133349 Cluster cluster = createClusterBuilder().build();
134350 List<MockRequest> allRequests = newArrayList();
135351 try {
@@ -163,8 +379,8 @@
163379 MockRequest failedBorrow = MockRequest.send(pool);
164380 try {
165381 failedBorrow.getConnection();
166- fail("Expected a ConnectionException");
167- } catch (ConnectionException e) { /*expected*/}
382+ fail("Expected a BusyPoolException");
383+ } catch (BusyPoolException e) { /*expected*/}
168384 } finally {
169385 MockRequest.completeAll(allRequests);
170386 cluster.close();
@@ -474,7 +690,6 @@
474690 }
475691 }
476692
477-
478693 /**
479694 * Ensures that if all connections on a host are closed that the host is marked
480695 * down and the control connection is notified of that fact and re-established
@@ -549,7 +764,6 @@
549764 }
550765 }
551766
552-
553767 /**
554768 * Ensures that if a connection on a host is lost that brings the number of active connections in a pool
555769 * under core connection count that up to core connections are re-established, but only after the
@@ -855,14 +1069,13 @@
8551069 MockRequest failedBorrow = MockRequest.send(pool);
8561070 try {
8571071 failedBorrow.getConnection();
858- fail("Expected a ConnectionException");
859- } catch (ConnectionException e) { /*expected*/}
1072+ fail("Expected a BusyPoolException");
1073+ } catch (BusyPoolException e) { /*expected*/}
8601074 } finally {
8611075 cluster.close();
8621076 }
8631077 }
8641078
865-
8661079 /**
8671080 * Ensures that if all connections fail on pool init that the host and subsequently the
8681081 * control connection is not marked down. The test also ensures that when making requests