Elffuss BraidHub

kikocis/java-driver public

Merge pull request #486 from datastax/java950_3.0

Fix Cluster.connect with a case-sensitive keyspace (JAVA-950).
Changeset7c8de89c8f6b19b66ad04ebd220b77e46dab142fe9e1262d6480bb7468a1b926
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-10-15 21:27 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-10-15 21:27 +02:00
Parents7f3ccb3b2b46, a64e85d5a0c6

Browse the files at this changeset

7 files changed

modified changelog/README.md +1 −0
@@ -15,6 +15,7 @@
1515 - [improvement] Limit visibility of codec internals (JAVA-932)
1616 - [improvement] Warn if a custom codec collides with an existing one (JAVA-934)
1717 - [improvement] Allow typed getters/setters to target any CQL type (JAVA-940)
18+- [bug] Fix Cluster.connect with a case-sensitive keyspace (JAVA-950)
1819
1920
2021 ### 3.0.0-alpha3
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +27 −7
@@ -26,6 +26,7 @@
2626 import java.util.concurrent.atomic.AtomicReference;
2727
2828 import com.google.common.annotations.VisibleForTesting;
29+import com.google.common.base.Functions;
2930 import com.google.common.base.Predicates;
3031 import com.google.common.base.Strings;
3132 import com.google.common.collect.*;
@@ -35,6 +36,7 @@
3536
3637 import com.datastax.driver.core.exceptions.AuthenticationException;
3738 import com.datastax.driver.core.exceptions.DriverInternalError;
39+import com.datastax.driver.core.exceptions.InvalidQueryException;
3840 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3941 import com.datastax.driver.core.policies.*;
4042 import com.datastax.driver.core.utils.MoreFutures;
@@ -222,7 +224,7 @@
222224 */
223225 public Session newSession() {
224226 checkNotClosed(manager);
225- return manager.newSession(null);
227+ return manager.newSession();
226228 }
227229
228230 /**
@@ -273,6 +275,7 @@
273275 * be contacted to set the {@code keyspace}.
274276 * @throws AuthenticationException if an authentication error occurs while
275277 * contacting the initial contact points.
278+ * @throws InvalidQueryException if the keyspace does not exists.
276279 * @throws IllegalStateException if the Cluster was closed prior to calling
277280 * this method. This can occur either directly (through {@link #close()} or
278281 * {@link #closeAsync()}), or as a result of an error while initializing the
@@ -333,11 +336,28 @@
333336 * {@link #closeAsync()}), or as a result of an error while initializing the
334337 * Cluster.
335338 */
336- public ListenableFuture<Session> connectAsync(String keyspace) {
339+ public ListenableFuture<Session> connectAsync(final String keyspace) {
337340 checkNotClosed(manager);
338341 init();
339- Session session = manager.newSession(keyspace);
340- return session.initAsync();
342+ final Session session = manager.newSession();
343+ ListenableFuture<Session> sessionInitialized = session.initAsync();
344+ if (keyspace == null) {
345+ return sessionInitialized;
346+ } else {
347+ ListenableFuture<ResultSet> keyspaceSet = Futures.transform(sessionInitialized, new AsyncFunction<Session, ResultSet>() {
348+ @Override
349+ public ListenableFuture<ResultSet> apply(Session session) throws Exception {
350+ return session.executeAsync("USE " + keyspace);
351+ }
352+ });
353+ Futures.addCallback(keyspaceSet, new MoreFutures.FailureCallback<ResultSet>() {
354+ @Override
355+ public void onFailure(Throwable t) {
356+ session.closeAsync();
357+ }
358+ });
359+ return Futures.transform(keyspaceSet, Functions.constant(session));
360+ }
341361 }
342362
343363 /**
@@ -1500,8 +1520,8 @@
15001520 return translated == null ? sa : translated;
15011521 }
15021522
1503- private Session newSession(String keyspace) {
1504- SessionManager session = new SessionManager(Cluster.this, keyspace);
1523+ private Session newSession() {
1524+ SessionManager session = new SessionManager(Cluster.this);
15051525 sessions.add(session);
15061526 return session;
15071527 }
@@ -1935,7 +1955,7 @@
19351955
19361956 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
19371957 for (SessionManager s : sessions)
1938- futures.add(s.maybeAddPool(host, reusedConnection, false));
1958+ futures.add(s.maybeAddPool(host, reusedConnection));
19391959
19401960 try {
19411961 // Only mark the node up once all session have added their pool (if the load-balancing
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +6 −15
@@ -46,14 +46,11 @@
4646
4747 import static io.netty.handler.timeout.IdleState.ALL_IDLE;
4848
49-import com.datastax.driver.core.exceptions.AuthenticationException;
50-import com.datastax.driver.core.exceptions.DriverException;
51-import com.datastax.driver.core.exceptions.DriverInternalError;
52-import com.datastax.driver.core.exceptions.InvalidQueryException;
49+import com.datastax.driver.core.Responses.Result.SetKeyspace;
50+import com.datastax.driver.core.exceptions.*;
5351 import com.datastax.driver.core.utils.MoreFutures;
5452
5553 import static com.datastax.driver.core.Message.Response.Type.ERROR;
56-import static com.datastax.driver.core.Message.Response.Type.RESULT;
5754
5855 // For LoggingHandler
5956 //import org.jboss.netty.handler.logging.LoggingHandler;
@@ -183,7 +180,7 @@
183180 public ListenableFuture<Void> create(Throwable t) throws Exception {
184181 SettableFuture<Void> future = SettableFuture.create();
185182 // Make sure the connection gets properly closed.
186- if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException || t instanceof SetKeyspaceException) {
183+ if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) {
187184 // Just propagate
188185 closeAsync().force();
189186 future.setException(t);
@@ -481,19 +478,13 @@
481478 return Futures.transform(future, new AsyncFunction<Message.Response, Void>() {
482479 @Override
483480 public ListenableFuture<Void> apply(Message.Response response) throws Exception {
484- if (response.type == RESULT) {
485- Connection.this.keyspace = keyspace;
481+ if (response instanceof SetKeyspace) {
482+ Connection.this.keyspace = ((SetKeyspace)response).keyspace;
486483 return MoreFutures.VOID_SUCCESS;
487484 } else if (response.type == ERROR) {
488485 closeAsync().force();
489486 Responses.Error error = (Responses.Error)response;
490- Exception e = error.asException(address);
491- if (e instanceof InvalidQueryException) {
492- // Most likely means that the keyspace name is wrong. Wrap that in a specific exception, because we want
493- // to treat it specially in case of a Session init.
494- e = new SetKeyspaceException(e);
495- }
496- throw e;
487+ throw error.asException(address);
497488 } else {
498489 closeAsync().force();
499490 throw new DriverInternalError("Unexpected response while setting keyspace: " + response);
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +1 −19
@@ -105,8 +105,6 @@
105105 * pool.
106106 */
107107 ListenableFuture<Void> initAsync(Connection reusedConnection) {
108- String keyspace = manager.poolsState.keyspace;
109-
110108 Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
111109
112110 // Create initial core connections
@@ -126,7 +124,7 @@
126124 }
127125 reusedConnection = null;
128126 connections.add(connection);
129- connectionFutures.add(handleErrors(setKeyspaceAsync(connectionFuture, connection, keyspace), initExecutor));
127+ connectionFutures.add(handleErrors(connectionFuture, initExecutor));
130128 }
131129
132130 ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
@@ -175,7 +173,6 @@
175173 // accordingly in SessionManager#maybeAddPool.
176174 Throwables.propagateIfInstanceOf(t, ClusterNameMismatchException.class);
177175 Throwables.propagateIfInstanceOf(t, UnsupportedProtocolVersionException.class);
178- Throwables.propagateIfInstanceOf(t, SetKeyspaceException.class);
179176
180177 // We don't want to swallow Errors either as they probably indicate a more serious issue (OOME...)
181178 Throwables.propagateIfInstanceOf(t, Error.class);
@@ -186,17 +183,6 @@
186183 }, executor);
187184 }
188185
189- private ListenableFuture<Void> setKeyspaceAsync(ListenableFuture<Void> initFuture, final Connection connection, final String keyspace) {
190- return (keyspace == null)
191- ? initFuture
192- : Futures.transform(initFuture, new AsyncFunction<Void, Void>() {
193- @Override
194- public ListenableFuture<Void> apply(Void input) throws Exception {
195- return connection.setKeyspaceAsync(keyspace);
196- }
197- });
198- }
199-
200186 // Clean up if we got a fatal error at construction time but still created part of the core connections
201187 private void forceClose(List<Connection> connections) {
202188 for (Connection connection : connections) {
@@ -687,10 +673,6 @@
687673 static class PoolState {
688674 volatile String keyspace;
689675
690- PoolState(String keyspace) {
691- this.keyspace = keyspace;
692- }
693-
694676 void setKeyspace(String keyspace) {
695677 this.keyspace = keyspace;
696678 }
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +6 −11
@@ -21,9 +21,7 @@
2121 import java.util.concurrent.*;
2222 import java.util.concurrent.atomic.AtomicReference;
2323
24-import com.google.common.base.Function;
2524 import com.google.common.base.Functions;
26-import com.google.common.base.Throwables;
2725 import com.google.common.collect.ImmutableList;
2826 import com.google.common.collect.Lists;
2927 import com.google.common.util.concurrent.*;
@@ -56,10 +54,10 @@
5654 private volatile boolean isClosing;
5755
5856 // Package protected, only Cluster should construct that.
59- SessionManager(Cluster cluster, String keyspace) {
57+ SessionManager(Cluster cluster) {
6058 this.cluster = cluster;
6159 this.pools = new ConcurrentHashMap<Host, HostConnectionPool>();
62- this.poolsState = new HostConnectionPool.PoolState(keyspace);
60+ this.poolsState = new HostConnectionPool.PoolState();
6361 }
6462
6563 public Session init() {
@@ -113,7 +111,7 @@
113111 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size());
114112 for (Host host : hosts)
115113 if (host.state != Host.State.DOWN)
116- futures.add(maybeAddPool(host, null, true));
114+ futures.add(maybeAddPool(host, null));
117115 return Futures.allAsList(futures);
118116 }
119117
@@ -332,7 +330,7 @@
332330 }
333331
334332 // Returns whether there was problem creating the pool
335- ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection, final boolean failOnKeyspaceError) {
333+ ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) {
336334 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
337335 if (distance == HostDistance.IGNORED)
338336 return Futures.immediateFuture(true);
@@ -365,9 +363,6 @@
365363 ClusterNameMismatchException e = (ClusterNameMismatchException)t;
366364 cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
367365 cluster.manager.triggerOnDown(host, false);
368- } else if ((t instanceof SetKeyspaceException) && failOnKeyspaceError) {
369- future.setException(t.getCause());
370- return;
371366 } else {
372367 logger.error("Error creating pool to " + host, t);
373368 }
@@ -413,7 +408,7 @@
413408
414409 if (pool == null) {
415410 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
416- poolCreatedFutures.add(maybeAddPool(h, null, false));
411+ poolCreatedFutures.add(maybeAddPool(h, null));
417412 } else if (dist != pool.hostDistance) {
418413 if (dist == HostDistance.IGNORED) {
419414 toRemove.add(h);
@@ -447,7 +442,7 @@
447442 if (pool == null) {
448443 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
449444 try {
450- maybeAddPool(h, null, false).get();
445+ maybeAddPool(h, null).get();
451446 } catch (ExecutionException e) {
452447 // Ignore, maybeAddPool has already handled the error
453448 }
deleted driver-core/src/main/java/com/datastax/driver/core/SetKeyspaceException.java +0 −23
@@ -1,23 +0,0 @@
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-@SuppressWarnings("serial")
19-class SetKeyspaceException extends Exception {
20- SetKeyspaceException(Exception cause) {
21- super(cause);
22- }
23-}
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +42 −19
@@ -16,15 +16,13 @@
1616 package com.datastax.driver.core;
1717
1818 import java.util.Collection;
19-import java.util.concurrent.ExecutionException;
20-import java.util.concurrent.TimeUnit;
19+import java.util.List;
20+import java.util.concurrent.*;
2121
2222 import com.google.common.base.Function;
2323 import com.google.common.collect.Lists;
24-import com.google.common.util.concurrent.AsyncFunction;
25-import com.google.common.util.concurrent.Futures;
26-import com.google.common.util.concurrent.ListenableFuture;
27-import com.google.common.util.concurrent.Uninterruptibles;
24+import com.google.common.util.concurrent.*;
25+import org.testng.annotations.DataProvider;
2826 import org.testng.annotations.Test;
2927
3028 import static org.assertj.core.api.Assertions.assertThat;
@@ -35,12 +33,24 @@
3533
3634 public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster {
3735
36+ @DataProvider(name="keyspace")
37+ public static Object[][] keyspace() {
38+ return new Object[][]{ { "asyncquerytest" }, { "\"AsyncQueryTest\"" } };
39+ }
40+
3841 @Override
3942 protected Collection<String> getTableDefinitions() {
40- return Lists.newArrayList(
41- "create table foo(k int primary key, v int)",
42- "insert into foo (k, v) values (1, 1)"
43- );
43+ List<String> definitions = Lists.newArrayList();
44+
45+ for (Object[] objects : keyspace()) {
46+ String keyspace = (String)objects[0];
47+
48+ definitions.add(String.format("create keyspace %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace));
49+ definitions.add(String.format("create table %s.foo(k int primary key, v int)", keyspace));
50+ definitions.add(String.format("insert into %s.foo (k, v) values (1, 1)", keyspace));
51+ }
52+
53+ return definitions;
4454 }
4555
4656 /**
@@ -76,27 +86,40 @@
7686 // Neither cluster2 nor session2 are initialized at this point
7787 assertThat(cluster2.manager.metadata).isNull();
7888
79- ResultSetFuture future = session2.executeAsync(String.format("select v from %s.foo where k = 1", keyspace));
89+ ResultSetFuture future = session2.executeAsync("select release_version from system.local");
8090 Row row = Uninterruptibles.getUninterruptibly(future).one();
8191
82- assertThat(row.getInt(0)).isEqualTo(1);
92+ assertThat(row.getString(0)).isNotEmpty();
8393 } finally {
8494 if (cluster2 != null)
8595 cluster2.close();
8696 }
8797 }
8898
89- @Test(groups = "short")
90- public void should_chain_query_on_async_session_init() throws Exception {
91- ListenableFuture<Integer> resultFuture = connectAndQuery(this.keyspace);
99+ @Test(groups = "short", dataProvider = "keyspace", enabled = false,
100+ description = "disabled because the blocking USE call in the current pool implementation makes it deadlock")
101+ public void should_chain_query_on_async_session_init_with_same_executor(String keyspace) throws Exception {
102+ ListenableFuture<Integer> resultFuture = connectAndQuery(keyspace, MoreExecutors.sameThreadExecutor());
92103
93104 Integer result = Uninterruptibles.getUninterruptibly(resultFuture);
94105 assertThat(result).isEqualTo(1);
95106 }
96107
108+ @Test(groups = "short", dataProvider = "keyspace")
109+ public void should_chain_query_on_async_session_init_with_different_executor(String keyspace) throws Exception {
110+ ExecutorService executor = Executors.newFixedThreadPool(1);
111+
112+ ListenableFuture<Integer> resultFuture = connectAndQuery(keyspace, executor);
113+
114+ Integer result = Uninterruptibles.getUninterruptibly(resultFuture);
115+ assertThat(result).isEqualTo(1);
116+
117+ executor.shutdownNow();
118+ }
119+
97120 @Test(groups = "short")
98121 public void should_propagate_error_to_chained_query_if_session_init_fails() throws Exception {
99- ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace");
122+ ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace", MoreExecutors.sameThreadExecutor());
100123
101124 try {
102125 Uninterruptibles.getUninterruptibly(resultFuture);
@@ -107,20 +130,20 @@
107130 }
108131 }
109132
110- private ListenableFuture<Integer> connectAndQuery(String keyspace) {
133+ private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) {
111134 ListenableFuture<Session> sessionFuture = cluster.connectAsync(keyspace);
112135 ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() {
113136 @Override
114137 public ListenableFuture<ResultSet> apply(Session session) throws Exception {
115138 return session.executeAsync("select v from foo where k = 1");
116139 }
117- });
140+ }, executor);
118141 return Futures.transform(queryFuture, new Function<ResultSet, Integer>() {
119142 @Override
120143 public Integer apply(ResultSet rs) {
121144 return rs.one().getInt(0);
122145 }
123- });
146+ }, executor);
124147 }
125148
126149 private static HostConnectionPool getPool(Session session) {