Elffuss BraidHub

kikocis/java-driver public

Fix Cluster.connect with a case-sensitive keyspace (JAVA-950).

Go back to the previous strategy of first initializing a session with no
keyspace and then issuing a USE statement. This guarantees that
SessionManager.poolsState.keyspace always contains a keyspace in the
"internal" format (unquoted and in the correct case), and keeps the
implementation simple.
The downside is that if the keyspace is wrong, we'll open all
connections before realizing the error, but that's an edge case.
Changesetf59550660f4e59d7152ae535f53ab01b74da3d61aec6a981eae50f2348e25a36
Authorolim7t <omichallat+github@gmail.com> · 2015-10-14 15:43 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-10-27 17:59 +01:00
Parentsadd58104027d

Browse the files at this changeset

7 files changed

modified changelog/README.md +5 −0
@@ -1,5 +1,10 @@
11 ## Changelog
22
3+### 2.0.12 (in progress)
4+
5+- [bug] Fix Cluster.connect with a case-sensitive keyspace (JAVA-950)
6+
7+
38 ### 2.0.11
49
510 - [improvement] Log streamid at the trace level on sending request and receiving response (JAVA-718)
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +27 −8
@@ -26,9 +26,9 @@
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.Objects;
3031 import com.google.common.base.Predicates;
31-import com.google.common.base.Throwables;
3232 import com.google.common.collect.*;
3333 import com.google.common.util.concurrent.*;
3434 import org.slf4j.Logger;
@@ -36,6 +36,7 @@
3636
3737 import com.datastax.driver.core.exceptions.AuthenticationException;
3838 import com.datastax.driver.core.exceptions.DriverInternalError;
39+import com.datastax.driver.core.exceptions.InvalidQueryException;
3940 import com.datastax.driver.core.exceptions.NoHostAvailableException;
4041 import com.datastax.driver.core.policies.*;
4142 import com.datastax.driver.core.utils.MoreFutures;
@@ -221,7 +222,7 @@
221222 */
222223 public Session newSession() {
223224 checkNotClosed(manager);
224- return manager.newSession(null);
225+ return manager.newSession();
225226 }
226227
227228 /**
@@ -272,6 +273,7 @@
272273 * be contacted to set the {@code keyspace}.
273274 * @throws AuthenticationException if an authentication error occurs while
274275 * contacting the initial contact points.
276+ * @throws InvalidQueryException if the keyspace does not exists.
275277 * @throws IllegalStateException if the Cluster was closed prior to calling
276278 * this method. This can occur either directly (through {@link #close()} or
277279 * {@link #closeAsync()}), or as a result of an error while initializing the
@@ -332,11 +334,28 @@
332334 * {@link #closeAsync()}), or as a result of an error while initializing the
333335 * Cluster.
334336 */
335- public ListenableFuture<Session> connectAsync(String keyspace) {
337+ public ListenableFuture<Session> connectAsync(final String keyspace) {
336338 checkNotClosed(manager);
337339 init();
338- AsyncInitSession session = manager.newSession(keyspace);
339- return session.initAsync();
340+ final AsyncInitSession session = manager.newSession();
341+ ListenableFuture<Session> sessionInitialized = session.initAsync();
342+ if (keyspace == null) {
343+ return sessionInitialized;
344+ } else {
345+ ListenableFuture<ResultSet> keyspaceSet = Futures.transform(sessionInitialized, new AsyncFunction<Session, ResultSet>() {
346+ @Override
347+ public ListenableFuture<ResultSet> apply(Session session) throws Exception {
348+ return session.executeAsync("USE " + keyspace);
349+ }
350+ });
351+ Futures.addCallback(keyspaceSet, new MoreFutures.FailureCallback<ResultSet>() {
352+ @Override
353+ public void onFailure(Throwable t) {
354+ session.closeAsync();
355+ }
356+ });
357+ return Futures.transform(keyspaceSet, Functions.<Session>constant(session));
358+ }
340359 }
341360
342361 /**
@@ -1487,8 +1506,8 @@
14871506 return translated == null ? sa : translated;
14881507 }
14891508
1490- private AsyncInitSession newSession(String keyspace) {
1491- SessionManager session = new SessionManager(Cluster.this, keyspace);
1509+ private AsyncInitSession newSession() {
1510+ SessionManager session = new SessionManager(Cluster.this);
14921511 sessions.add(session);
14931512 return session;
14941513 }
@@ -1925,7 +1944,7 @@
19251944
19261945 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
19271946 for (SessionManager s : sessions)
1928- futures.add(s.maybeAddPool(host, reusedConnection, false));
1947+ futures.add(s.maybeAddPool(host, reusedConnection));
19291948
19301949 try {
19311950 // 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;
@@ -182,7 +179,7 @@
182179 public ListenableFuture<Void> create(Throwable t) throws Exception {
183180 SettableFuture<Void> future = SettableFuture.create();
184181 // Make sure the connection gets properly closed.
185- if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException || t instanceof SetKeyspaceException) {
182+ if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) {
186183 // Just propagate
187184 closeAsync().force();
188185 future.setException(t);
@@ -474,19 +471,13 @@
474471 return Futures.transform(future, new AsyncFunction<Message.Response, Void>() {
475472 @Override
476473 public ListenableFuture<Void> apply(Message.Response response) throws Exception {
477- if (response.type == RESULT) {
478- Connection.this.keyspace = keyspace;
474+ if (response instanceof SetKeyspace) {
475+ Connection.this.keyspace = ((SetKeyspace)response).keyspace;
479476 return MoreFutures.VOID_SUCCESS;
480477 } else if (response.type == ERROR) {
481478 closeAsync().force();
482479 Responses.Error error = (Responses.Error)response;
483- Exception e = error.asException(address);
484- if (e instanceof InvalidQueryException) {
485- // Most likely means that the keyspace name is wrong. Wrap that in a specific exception, because we want
486- // to treat it specially in case of a Session init.
487- e = new SetKeyspaceException(e);
488- }
489- throw e;
480+ throw error.asException(address);
490481 } else {
491482 closeAsync().force();
492483 throw new DriverInternalError("Unexpected response while setting keyspace: " + response);
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +1 −19
@@ -100,8 +100,6 @@
100100 * pool.
101101 */
102102 public ListenableFuture<Void> initAsync(Connection reusedConnection) {
103- String keyspace = manager.poolsState.keyspace;
104-
105103 Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
106104
107105 // Create initial core connections
@@ -121,7 +119,7 @@
121119 }
122120 reusedConnection = null;
123121 connections.add(connection);
124- connectionFutures.add(handleErrors(setKeyspaceAsync(connectionFuture, connection, keyspace), initExecutor));
122+ connectionFutures.add(handleErrors(connectionFuture, initExecutor));
125123 }
126124
127125 ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
@@ -170,7 +168,6 @@
170168 // accordingly in SessionManager#maybeAddPool.
171169 Throwables.propagateIfInstanceOf(t, ClusterNameMismatchException.class);
172170 Throwables.propagateIfInstanceOf(t, UnsupportedProtocolVersionException.class);
173- Throwables.propagateIfInstanceOf(t, SetKeyspaceException.class);
174171
175172 // We don't want to swallow Errors either as they probably indicate a more serious issue (OOME...)
176173 Throwables.propagateIfInstanceOf(t, Error.class);
@@ -181,17 +178,6 @@
181178 }, executor);
182179 }
183180
184- private ListenableFuture<Void> setKeyspaceAsync(ListenableFuture<Void> initFuture, final Connection connection, final String keyspace) {
185- return (keyspace == null)
186- ? initFuture
187- : Futures.transform(initFuture, new AsyncFunction<Void, Void>() {
188- @Override
189- public ListenableFuture<Void> apply(Void input) throws Exception {
190- return connection.setKeyspaceAsync(keyspace);
191- }
192- });
193- }
194-
195181 // Clean up if we got a fatal error at construction time but still created part of the core connections
196182 private void forceClose(List<Connection> connections) {
197183 for (Connection connection : connections) {
@@ -682,10 +668,6 @@
682668
683669 volatile String keyspace;
684670
685- PoolState(String keyspace) {
686- this.keyspace = keyspace;
687- }
688-
689671 void setKeyspace(String keyspace) {
690672 this.keyspace = keyspace;
691673 }
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
@@ -328,7 +326,7 @@
328326 }
329327
330328 // Returns whether there was problem creating the pool
331- ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection, final boolean failOnKeyspaceError) {
329+ ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) {
332330 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
333331 if (distance == HostDistance.IGNORED)
334332 return Futures.immediateFuture(true);
@@ -361,9 +359,6 @@
361359 ClusterNameMismatchException e = (ClusterNameMismatchException)t;
362360 cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
363361 cluster.manager.triggerOnDown(host, false);
364- } else if ((t instanceof SetKeyspaceException) && failOnKeyspaceError) {
365- future.setException(t.getCause());
366- return;
367362 } else {
368363 logger.error("Error creating pool to " + host, t);
369364 }
@@ -409,7 +404,7 @@
409404
410405 if (pool == null) {
411406 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
412- poolCreatedFutures.add(maybeAddPool(h, null, false));
407+ poolCreatedFutures.add(maybeAddPool(h, null));
413408 } else if (dist != pool.hostDistance) {
414409 if (dist == HostDistance.IGNORED) {
415410 toRemove.add(h);
@@ -443,7 +438,7 @@
443438 if (pool == null) {
444439 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
445440 try {
446- maybeAddPool(h, null, false).get();
441+ maybeAddPool(h, null).get();
447442 } catch (ExecutionException e) {
448443 // Ignore, maybeAddPool has already handled the error
449444 }
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) {