Elffuss BraidHub

kikocis/java-driver public

Expose an API to check for schema agreement after a schema-altering statement (JAVA-669).
Changesetf41a4e1423dacd5bdefbf63536b517ec3f3308c13dc9c1d49ba69927600b2e3d
Authorolim7t <omichallat+github@gmail.com> · 2015-04-02 11:10 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-04-15 09:28 +02:00
Parentsd4c4ae736c90

Browse the files at this changeset

9 files changed

modified driver-core/CHANGELOG.rst +2 −0
@@ -36,6 +36,8 @@
3636 - [improvement] Log keyspace xxx does not exist at WARN level (JAVA-534)
3737 - [improvement] Allow Cluster subclasses to delegate to another instance
3838 (JAVA-619)
39+- [new feature] Expose an API to check for schema agreement after a
40+ schema-altering statement (JAVA-669)
3941
4042 Merged from 2.0.9_fixes branch:
4143
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +23 −5
@@ -2037,20 +2037,38 @@
20372037 if (logger.isDebugEnabled())
20382038 logger.debug("Refreshing schema for {}{}", keyspace == null ? "" : keyspace, table == null ? "" : '.' + table);
20392039
2040+ maybeRefreshSchemaAndSignal(connection, future, rs, keyspace, table);
2041+ }
2042+
2043+ public void waitForSchemaAgreementAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs) {
2044+ maybeRefreshSchemaAndSignal(connection, future, rs, null, null);
2045+ }
2046+
2047+ private void maybeRefreshSchemaAndSignal(final Connection connection, final DefaultResultSetFuture future, final ResultSet rs, final String keyspace, final String table) {
2048+ final boolean refreshSchema = (keyspace != null); // if false, only wait for schema agreement
2049+
20402050 executor.submit(new Runnable() {
20412051 @Override
20422052 public void run() {
2053+ boolean schemaInAgreement = false;
20432054 try {
20442055 // Before refreshing the schema, wait for schema agreement so
20452056 // that querying a table just after having created it don't fail.
2046- if (!ControlConnection.waitForSchemaAgreement(connection, Cluster.Manager.this))
2057+ schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this);
2058+ if (!schemaInAgreement)
20472059 logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds());
2048- ControlConnection.refreshSchema(connection, keyspace, table, Cluster.Manager.this, false);
2060+ if (refreshSchema)
2061+ ControlConnection.refreshSchema(connection, keyspace, table, Manager.this, false);
20492062 } catch (Exception e) {
2050- logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage());
2051- submitSchemaRefresh(keyspace, table);
2063+ if (refreshSchema) {
2064+ logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage());
2065+ submitSchemaRefresh(keyspace, table);
2066+ } else {
2067+ logger.warn("Error while waiting for schema agreement", e);
2068+ }
20522069 } finally {
2053- // Always sets the result
2070+ // Always sets the result, but remember if we reached schema agreement
2071+ rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement);
20542072 future.setResult(rs);
20552073 }
20562074 }
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +36 −24
@@ -595,40 +595,52 @@
595595 int maxSchemaAgreementWaitSeconds = cluster.configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds();
596596 while (elapsed < maxSchemaAgreementWaitSeconds * 1000) {
597597
598- DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_PEERS));
599- DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_LOCAL));
600- connection.write(peersFuture);
601- connection.write(localFuture);
598+ if (checkSchemaAgreement(connection, cluster))
599+ return true;
602600
603- Set<UUID> versions = new HashSet<UUID>();
601+ // let's not flood the node too much
602+ Thread.sleep(200);
604603
605- Row localRow = localFuture.get().one();
606- if (localRow != null && !localRow.isNull("schema_version"))
607- versions.add(localRow.getUUID("schema_version"));
604+ elapsed = Cluster.timeSince(start, TimeUnit.MILLISECONDS);
605+ }
608606
609- for (Row row : peersFuture.get()) {
607+ return false;
608+ }
610609
611- InetSocketAddress addr = addressToUseForPeerHost(row, connection.address, cluster, true);
612- if (addr == null || row.isNull("schema_version"))
613- continue;
610+ private static boolean checkSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException {
611+ DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_PEERS));
612+ DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_SCHEMA_LOCAL));
613+ connection.write(peersFuture);
614+ connection.write(localFuture);
614615
615- Host peer = cluster.metadata.getHost(addr);
616- if (peer != null && peer.isUp())
617- versions.add(row.getUUID("schema_version"));
618- }
616+ Set<UUID> versions = new HashSet<UUID>();
619617
620- logger.debug("Checking for schema agreement: versions are {}", versions);
618+ Row localRow = localFuture.get().one();
619+ if (localRow != null && !localRow.isNull("schema_version"))
620+ versions.add(localRow.getUUID("schema_version"));
621621
622- if (versions.size() <= 1)
623- return true;
622+ for (Row row : peersFuture.get()) {
624623
625- // let's not flood the node too much
626- Thread.sleep(200);
624+ InetSocketAddress addr = addressToUseForPeerHost(row, connection.address, cluster, true);
625+ if (addr == null || row.isNull("schema_version"))
626+ continue;
627627
628- elapsed = Cluster.timeSince(start, TimeUnit.MILLISECONDS);
628+ Host peer = cluster.metadata.getHost(addr);
629+ if (peer != null && peer.isUp())
630+ versions.add(row.getUUID("schema_version"));
631+ }
632+ logger.debug("Checking for schema agreement: versions are {}", versions);
633+ return versions.size() <= 1;
634+ }
635+
636+ boolean checkSchemaAgreement() {
637+ Connection c = connectionRef.get();
638+ try {
639+ return c != null && checkSchemaAgreement(c, cluster);
640+ } catch (Exception e) {
641+ logger.warn("Error while checking schema agreement", e);
642+ return false;
629643 }
630-
631- return false;
632644 }
633645
634646 boolean isOpen() {
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +1 −1
@@ -91,7 +91,7 @@
9191 else
9292 keyspace.removeTable(scc.columnFamily);
9393 }
94- this.setResult(rs);
94+ session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs);
9595 break;
9696 case UPDATED:
9797 if (scc.columnFamily.isEmpty()) {
modified driver-core/src/main/java/com/datastax/driver/core/ExecutionInfo.java +34 −19
@@ -19,19 +19,7 @@
1919 import java.util.List;
2020
2121 /**
22- * Basic informations on the execution of a query.
23- * <p>
24- * This provides the following information on the execution of a (successful)
25- * query:
26- * <ul>
27- * <li>The list of Cassandra hosts tried in order (usually just one, unless
28- * a node has been tried but was dead/in error or a timeout provoked a retry
29- * (which depends on the RetryPolicy)).</li>
30- * <li>The consistency level achieved by the query (usually the one asked,
31- * though some specific RetryPolicy may allow this to be different).</li>
32- * <li>The query trace recorded by Cassandra if tracing had been set for the
33- * query.</li>
34- * </ul>
22+ * Basic information on the execution of a query.
3523 */
3624 public class ExecutionInfo {
3725 private final List<Host> triedHosts;
@@ -39,33 +27,35 @@
3927 private final QueryTrace trace;
4028 private final ByteBuffer pagingState;
4129 private final Statement statement;
30+ private volatile boolean schemaInAgreement;
4231
43- private ExecutionInfo(List<Host> triedHosts, ConsistencyLevel achievedConsistency, QueryTrace trace, ByteBuffer pagingState, Statement statement) {
32+ private ExecutionInfo(List<Host> triedHosts, ConsistencyLevel achievedConsistency, QueryTrace trace, ByteBuffer pagingState, Statement statement, boolean schemaAgreement) {
4433 this.triedHosts = triedHosts;
4534 this.achievedConsistency = achievedConsistency;
4635 this.trace = trace;
4736 this.pagingState = pagingState;
4837 this.statement = statement;
38+ this.schemaInAgreement = schemaAgreement;
4939 }
5040
5141 ExecutionInfo(List<Host> triedHosts) {
52- this(triedHosts, null, null, null, null);
42+ this(triedHosts, null, null, null, null, true);
5343 }
5444
5545 ExecutionInfo withTrace(QueryTrace newTrace) {
56- return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, statement);
46+ return new ExecutionInfo(triedHosts, achievedConsistency, newTrace, pagingState, statement, schemaInAgreement);
5747 }
5848
5949 ExecutionInfo withAchievedConsistency(ConsistencyLevel newConsistency) {
60- return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, statement);
50+ return new ExecutionInfo(triedHosts, newConsistency, trace, pagingState, statement, schemaInAgreement);
6151 }
6252
6353 ExecutionInfo withPagingState(ByteBuffer pagingState) {
64- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, statement);
54+ return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, statement, schemaInAgreement);
6555 }
6656
6757 ExecutionInfo withStatement(Statement statement) {
68- return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, statement);
58+ return new ExecutionInfo(triedHosts, achievedConsistency, trace, pagingState, statement, schemaInAgreement);
6959 }
7060
7161 /**
@@ -147,4 +137,29 @@
147137 return null;
148138 return new PagingState(this.pagingState, this.statement);
149139 }
140+
141+ /**
142+ * Whether the cluster had reached schema agreement after the execution of this query.
143+ *
144+ * After a successful schema-altering query (ex: creating a table), the driver
145+ * will check if the cluster's nodes agree on the new schema version. If not,
146+ * it will keep retrying for a given delay (configurable via
147+ * {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}).
148+ * <p>
149+ * If this method returns {@code false}, clients can call {@link Metadata#checkSchemaAgreement()}
150+ * later to perform the check manually.
151+ * <p>
152+ * Note that the schema agreement check is only performed for schema-altering queries
153+ * For other query types, this method will always return {@code true}.
154+ *
155+ * @return whether the cluster reached schema agreement, or {@code true} for a non
156+ * schema-altering statement.
157+ */
158+ public boolean isSchemaInAgreement() {
159+ return schemaInAgreement;
160+ }
161+
162+ void setSchemaInAgreement(boolean schemaAgreement) {
163+ this.schemaInAgreement = schemaAgreement;
164+ }
150165 }
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +13 −0
@@ -353,6 +353,19 @@
353353 return new HashSet<Host>(allHosts());
354354 }
355355
356+ /**
357+ * Checks whether hosts that are currently up agree on the schema definition.
358+ * <p>
359+ * This method performs a one-time check only, without any form of retry; therefore {@link Cluster.Builder#withMaxSchemaAgreementWaitSeconds(int)}
360+ * does not apply in this case.
361+ *
362+ * @return {@code true} if all hosts agree on the schema; {@code false} if they don't agree, or if the check could not be performed
363+ * (for example, if the control connection is down).
364+ */
365+ public boolean checkSchemaAgreement() {
366+ return cluster.controlConnection.checkSchemaAgreement();
367+ }
368+
356369 /**
357370 * Returns the metadata of a keyspace given its name.
358371 *
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +4 −1
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.annotations.VisibleForTesting;
19+
1820 /**
1921 * Options of the Cassandra native binary protocol.
2022 */
@@ -83,7 +85,8 @@
8385 private final int port;
8486 final int initialProtocolVersion; // What the user asked us. Will be -1 by default.
8587
86- private final int maxSchemaAgreementWaitSeconds;
88+ @VisibleForTesting
89+ volatile int maxSchemaAgreementWaitSeconds;
8790
8891 private final SSLOptions sslOptions; // null if no SSL
8992 private final AuthProvider authProvider;
added driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +124 −0
@@ -0,0 +1,124 @@
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 java.net.InetAddress;
19+import java.util.UUID;
20+
21+import org.testng.annotations.AfterClass;
22+import org.testng.annotations.AfterMethod;
23+import org.testng.annotations.BeforeClass;
24+import org.testng.annotations.Test;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+
28+import com.datastax.driver.core.exceptions.DriverException;
29+import com.datastax.driver.core.utils.UUIDs;
30+
31+public class SchemaAgreementTest {
32+
33+ // Don't use "IF EXISTS" to remain compatible with older C* versions
34+ static final String CREATE_TABLE = "CREATE TABLE foo (k int primary key, v int)";
35+ static final String DROP_TABLE = "DROP TABLE foo";
36+
37+ CCMBridge ccm;
38+ Cluster cluster;
39+ Session session;
40+ ProtocolOptions protocolOptions;
41+
42+ @BeforeClass(groups = "short")
43+ public void setup() {
44+ ccm = CCMBridge.create("schema_agreement", 2);
45+ cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
46+ session = cluster.connect();
47+ session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
48+ session.execute("use test");
49+ protocolOptions = cluster.getConfiguration().getProtocolOptions();
50+ }
51+
52+ @Test(groups = "short")
53+ public void should_set_flag_on_successful_agreement() {
54+ protocolOptions.maxSchemaAgreementWaitSeconds = 10;
55+ ResultSet rs = session.execute(CREATE_TABLE);
56+ assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
57+ }
58+
59+ @Test(groups = "short")
60+ public void should_set_flag_on_non_schema_altering_statement() {
61+ protocolOptions.maxSchemaAgreementWaitSeconds = 10;
62+ ResultSet rs = session.execute("select release_version from system.local");
63+ assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
64+ }
65+
66+ @Test(groups = "short")
67+ public void should_unset_flag_on_failed_agreement() {
68+ // Setting to 0 results in no query being set, so agreement fails
69+ protocolOptions.maxSchemaAgreementWaitSeconds = 0;
70+ ResultSet rs = session.execute(CREATE_TABLE);
71+ assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isFalse();
72+ }
73+
74+ @Test(groups = "short")
75+ public void should_check_agreement_through_cluster_metadata() {
76+ Cluster controlCluster = null;
77+ try {
78+ controlCluster = TestUtils.buildControlCluster(cluster);
79+ Session controlSession = controlCluster.connect();
80+
81+ Row localRow = controlSession.execute("SELECT schema_version FROM system.local").one();
82+ UUID localVersion = localRow.getUUID("schema_version");
83+ Row peerRow = controlSession.execute("SELECT peer, schema_version FROM system.peers").one();
84+ InetAddress peerAddress = peerRow.getInet("peer");
85+ UUID peerVersion = peerRow.getUUID("schema_version");
86+ // The two nodes should be in agreement at this point, but check just in case:
87+ assertThat(localVersion).isEqualTo(peerVersion);
88+
89+ // Now check the method under test:
90+ assertThat(cluster.getMetadata().checkSchemaAgreement()).isTrue();
91+
92+ // Insert a fake version to simulate a disagreement:
93+ forceSchemaVersion(controlSession, peerAddress, UUIDs.random());
94+ assertThat(cluster.getMetadata().checkSchemaAgreement()).isFalse();
95+
96+ forceSchemaVersion(controlSession, peerAddress, peerVersion);
97+ } finally {
98+ if (controlCluster != null)
99+ controlCluster.close();
100+ }
101+ }
102+
103+ private static void forceSchemaVersion(Session session, InetAddress peerAddress, UUID schemaVersion) {
104+ session.execute(String.format("UPDATE system.peers SET schema_version = %s WHERE peer = %s",
105+ DataType.uuid().format(schemaVersion), DataType.inet().format(peerAddress)));
106+ }
107+
108+ @AfterMethod(groups = "short")
109+ public void cleanupSchema() {
110+ protocolOptions.maxSchemaAgreementWaitSeconds = 10;
111+ try {
112+ session.execute(DROP_TABLE);
113+ } catch (DriverException e) { /*ignore*/ }
114+ }
115+
116+ @AfterClass(groups = "short")
117+ public void teardown() {
118+ if (cluster != null)
119+ cluster.close();
120+ if (ccm != null)
121+ ccm.remove();
122+ }
123+}
124+
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +16 −0
@@ -19,6 +19,7 @@
1919 import java.math.BigDecimal;
2020 import java.math.BigInteger;
2121 import java.net.InetAddress;
22+import java.net.InetSocketAddress;
2223 import java.net.ServerSocket;
2324 import java.nio.ByteBuffer;
2425 import java.util.*;
@@ -31,6 +32,9 @@
3132 import org.slf4j.LoggerFactory;
3233 import org.testng.SkipException;
3334
35+import com.datastax.driver.core.policies.RoundRobinPolicy;
36+import com.datastax.driver.core.policies.WhiteListPolicy;
37+
3438 /**
3539 * A number of static fields/methods handy for tests.
3640 */
@@ -432,4 +436,16 @@
432436 return 2;
433437 }
434438 }
439+
440+ /**
441+ * @return a {@Cluster} instance that connects only to the control host of the given cluster.
442+ */
443+ public static Cluster buildControlCluster(Cluster cluster) {
444+ Host controlHost = cluster.manager.controlConnection.connectedHost();
445+ List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress());
446+ return Cluster.builder()
447+ .addContactPointsWithPorts(singleAddress)
448+ .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
449+ .build();
450+ }
435451 }