Elffuss BraidHub

kikocis/java-driver public

Make driver-side metadata optional (JAVA-828).
Changesetee08e578f68e65c431dd531de369e68b319a12e91eb378eb45d6df4c881e153a
Authorolim7t <omichallat+github@gmail.com> · 2015-08-12 20:30 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-08-14 18:58 +02:00
Parentse8d1c653ef99

Browse the files at this changeset

6 files changed

modified changelog/README.md +1 −0
@@ -37,6 +37,7 @@
3737 - [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859)
3838 - [improvement] Debounce control connection queries (JAVA-657)
3939 - [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784)
40+- [new feature] Make driver-side metadata optional (JAVA-828)
4041
4142 Merged from 2.0.10_fixes branch:
4243
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +3 −0
@@ -2200,6 +2200,9 @@
22002200 }
22012201 break;
22022202 case SCHEMA_CHANGE:
2203+ if (!configuration.getQueryOptions().isMetadataEnabled())
2204+ return;
2205+
22032206 ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event;
22042207 switch (scc.change) {
22052208 case CREATED:
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +12 −6
@@ -512,6 +512,8 @@
512512 private static void refreshNodeListAndTokenMap(Connection connection, Cluster.Manager cluster, boolean isInitialConnection, boolean logMissingRpcAddresses) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
513513 logger.debug("[Control connection] Refreshing node list and token map");
514514
515+ boolean metadataEnabled = cluster.configuration.getQueryOptions().isMetadataEnabled();
516+
515517 // Make sure we're up to date on nodes and tokens
516518
517519 DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, new Requests.Query(SELECT_LOCAL));
@@ -540,9 +542,11 @@
540542 logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address);
541543 } else {
542544 updateInfo(host, localRow, cluster, isInitialConnection);
543- Set<String> tokens = localRow.getSet("tokens", String.class);
544- if (partitioner != null && !tokens.isEmpty())
545- tokenMap.put(host, tokens);
545+ if (metadataEnabled) {
546+ Set<String> tokens = localRow.getSet("tokens", String.class);
547+ if (partitioner != null && !tokens.isEmpty())
548+ tokenMap.put(host, tokens);
549+ }
546550 }
547551 }
548552
@@ -563,7 +567,8 @@
563567 racks.add(row.getString("rack"));
564568 cassandraVersions.add(row.getString("release_version"));
565569 listenAddresses.add(row.getInet("peer"));
566- allTokens.add(row.getSet("tokens", String.class));
570+ if (metadataEnabled)
571+ allTokens.add(row.getSet("tokens", String.class));
567572 }
568573
569574 for (int i = 0; i < foundHosts.size(); i++) {
@@ -580,7 +585,7 @@
580585 if (cassandraVersions.get(i) != null)
581586 host.setVersionAndListenAdress(cassandraVersions.get(i), listenAddresses.get(i));
582587
583- if (partitioner != null && !allTokens.get(i).isEmpty())
588+ if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty())
584589 tokenMap.put(host, allTokens.get(i));
585590
586591 if (isNew && !isInitialConnection)
@@ -593,7 +598,8 @@
593598 if (!host.getSocketAddress().equals(connection.address) && !foundHostsSet.contains(host.getSocketAddress()))
594599 cluster.removeHost(host, isInitialConnection);
595600
596- cluster.metadata.rebuildTokenMap(partitioner, tokenMap);
601+ if (metadataEnabled)
602+ cluster.metadata.rebuildTokenMap(partitioner, tokenMap);
597603 }
598604
599605 boolean waitForSchemaAgreement() throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +51 −47
@@ -65,62 +65,66 @@
6565 set(ArrayBackedResultSet.fromMessage(rm, session, info, statement));
6666 break;
6767 case SCHEMA_CHANGE:
68- Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
6968 ResultSet rs = ArrayBackedResultSet.fromMessage(rm, session, info, statement);
70- switch (scc.change) {
71- case CREATED:
72- if (scc.columnFamily.isEmpty()) {
73- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null);
74- } else {
75- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.columnFamily);
76- }
77- break;
78- case DROPPED:
79- if (scc.columnFamily.isEmpty()) {
80- // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...)
81- // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements.
82- // We'll add it back if CASSANDRA-5358 changes that behavior
83- //if (scc.keyspace.equals(session.poolsState.keyspace))
84- // session.poolsState.setKeyspace(null);
85- final KeyspaceMetadata removed = session.cluster.manager.metadata.removeKeyspace(scc.keyspace);
86- if(removed != null) {
87- session.cluster.manager.executor.submit(new Runnable() {
88- @Override
89- public void run() {
90- session.cluster.manager.metadata.triggerOnKeyspaceRemoved(removed);
91- }
92- });
69+ final Cluster.Manager cluster = session.cluster.manager;
70+ if (!cluster.configuration.getQueryOptions().isMetadataEnabled()) {
71+ cluster.waitForSchemaAgreementAndSignal(connection, this, rs);
72+ } else {
73+ Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
74+ switch (scc.change) {
75+ case CREATED:
76+ if (scc.columnFamily.isEmpty()) {
77+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null);
78+ } else {
79+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.columnFamily);
9380 }
94-
95- } else {
96- KeyspaceMetadata keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.keyspace);
97- if (keyspace == null)
98- logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata",
99- scc.keyspace, scc.columnFamily);
100- else {
101- final TableMetadata removed = keyspace.removeTable(scc.columnFamily);
81+ break;
82+ case DROPPED:
83+ if (scc.columnFamily.isEmpty()) {
84+ // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...)
85+ // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements.
86+ // We'll add it back if CASSANDRA-5358 changes that behavior
87+ //if (scc.keyspace.equals(session.poolsState.keyspace))
88+ // session.poolsState.setKeyspace(null);
89+ final KeyspaceMetadata removed = cluster.metadata.removeKeyspace(scc.keyspace);
10290 if (removed != null) {
103- session.cluster.manager.executor.submit(new Runnable() {
91+ cluster.executor.submit(new Runnable() {
10492 @Override
10593 public void run() {
106- session.cluster.manager.metadata.triggerOnTableRemoved(removed);
94+ cluster.metadata.triggerOnKeyspaceRemoved(removed);
10795 }
10896 });
10997 }
98+ } else {
99+ KeyspaceMetadata keyspace = cluster.metadata.getKeyspaceInternal(scc.keyspace);
100+ if (keyspace == null)
101+ logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata",
102+ scc.keyspace, scc.columnFamily);
103+ else {
104+ final TableMetadata removed = keyspace.removeTable(scc.columnFamily);
105+ if (removed != null) {
106+ cluster.executor.submit(new Runnable() {
107+ @Override
108+ public void run() {
109+ cluster.metadata.triggerOnTableRemoved(removed);
110+ }
111+ });
112+ }
113+ }
114+ }
115+ cluster.waitForSchemaAgreementAndSignal(connection, this, rs);
116+ break;
117+ case UPDATED:
118+ if (scc.columnFamily.isEmpty()) {
119+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null);
120+ } else {
121+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.columnFamily);
110122 }
111- }
112- session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs);
113- break;
114- case UPDATED:
115- if (scc.columnFamily.isEmpty()) {
116- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, null);
117- } else {
118- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.keyspace, scc.columnFamily);
119- }
120- break;
121- default:
122- logger.info("Ignoring unknown schema change result");
123- break;
123+ break;
124+ default:
125+ logger.info("Ignoring unknown schema change result");
126+ break;
127+ }
124128 }
125129 break;
126130 default:
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +25 −9
@@ -28,8 +28,6 @@
2828 import org.slf4j.Logger;
2929 import org.slf4j.LoggerFactory;
3030
31-import com.datastax.driver.core.exceptions.DriverInternalError;
32-
3331 /**
3432 * Keeps metadata on the connected cluster, including known nodes and schema definitions.
3533 */
@@ -355,7 +353,8 @@
355353 * connection, when schema or ring topology changes. It might occasionally
356354 * be stale.
357355 *
358- * @return the token ranges.
356+ * @return the token ranges. Note that the result might be stale or empty if
357+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
359358 */
360359 public Set<TokenRange> getTokenRanges() {
361360 TokenMap current = tokenMap;
@@ -373,7 +372,8 @@
373372 * @param keyspace the name of the keyspace to get token ranges for.
374373 * @param host the host.
375374 * @return the (immutable) set of token ranges for {@code host} as known
376- * by the driver.
375+ * by the driver. Note that the result might be stale or empty if metadata
376+ * was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
377377 */
378378 public Set<TokenRange> getTokenRanges(String keyspace, Host host) {
379379 keyspace = handleId(keyspace);
@@ -402,7 +402,8 @@
402402 * @param partitionKey the partition key for which to find the set of
403403 * replica.
404404 * @return the (immutable) set of replicas for {@code partitionKey} as known
405- * by the driver.
405+ * by the driver. Note that the result might be stale or empty if metadata was
406+ * explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
406407 */
407408 public Set<Host> getReplicas(String keyspace, ByteBuffer partitionKey) {
408409 keyspace = handleId(keyspace);
@@ -425,6 +426,8 @@
425426 * @param keyspace the name of the keyspace to get replicas for.
426427 * @param range the token range.
427428 * @return the (immutable) set of replicas for {@code range} as known by the driver.
429+ * Note that the result might be stale or empty if metadata was explicitly disabled
430+ * with {@link QueryOptions#setMetadataEnabled(boolean)}.
428431 */
429432 public Set<Host> getReplicas(String keyspace, TokenRange range) {
430433 keyspace = handleId(keyspace);
@@ -488,7 +491,8 @@
488491 * @param keyspace the name of the keyspace for which metadata should be
489492 * returned.
490493 * @return the metadata of the requested keyspace or {@code null} if {@code
491- * keyspace} is not a known keyspace.
494+ * keyspace} is not a known keyspace. Note that the result might be stale or null if
495+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
492496 */
493497 public KeyspaceMetadata getKeyspace(String keyspace) {
494498 return keyspaces.get(handleId(keyspace));
@@ -512,7 +516,8 @@
512516 /**
513517 * Returns a list of all the defined keyspaces.
514518 *
515- * @return a list of all the defined keyspaces.
519+ * @return a list of all the defined keyspaces. Note that the result might be stale or empty if
520+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
516521 */
517522 public List<KeyspaceMetadata> getKeyspaces() {
518523 return new ArrayList<KeyspaceMetadata>(keyspaces.values());
@@ -528,6 +533,9 @@
528533 * Note that the returned String is formatted to be human readable (for
529534 * some definition of human readable at least).
530535 *
536+ * It might be stale or empty if metadata was explicitly disabled with
537+ * {@link QueryOptions#setMetadataEnabled(boolean)}.
538+ *
531539 * @return the CQL queries representing this cluster schema as a {code
532540 * String}.
533541 */
@@ -546,11 +554,15 @@
546554 *
547555 * @param tokenStr the string representation.
548556 * @return the token.
557+ *
558+ * @throws IllegalStateException if the token factory was not initialized. This would typically
559+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
560+ * before startup.
549561 */
550562 public Token newToken(String tokenStr) {
551563 TokenMap current = tokenMap;
552564 if (current == null)
553- throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
565+ throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled");
554566
555567 return current.factory.fromString(tokenStr);
556568 }
@@ -561,11 +573,15 @@
561573 * @param start the start token.
562574 * @param end the end token.
563575 * @return the range.
576+ *
577+ * @throws IllegalStateException if the token factory was not initialized. This would typically
578+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
579+ * before startup.
564580 */
565581 public TokenRange newTokenRange(Token start, Token end) {
566582 TokenMap current = tokenMap;
567583 if (current == null)
568- throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
584+ throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled");
569585
570586 return new TokenRange(start, end, current.factory);
571587 }
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +46 −1
@@ -54,12 +54,13 @@
5454
5555 public static final int DEFAULT_REFRESH_SCHEMA_INTERVAL_MILLIS = 1000;
5656
57-
5857 private volatile ConsistencyLevel consistency = DEFAULT_CONSISTENCY_LEVEL;
5958 private volatile ConsistencyLevel serialConsistency = DEFAULT_SERIAL_CONSISTENCY_LEVEL;
6059 private volatile int fetchSize = DEFAULT_FETCH_SIZE;
6160 private volatile boolean defaultIdempotence = DEFAULT_IDEMPOTENCE;
6261
62+ private volatile boolean metadataEnabled = true;
63+
6364 private volatile int maxPendingRefreshNodeListRequests = DEFAULT_MAX_PENDING_REFRESH_NODE_LIST_REQUESTS;
6465 private volatile int maxPendingRefreshNodeRequests = DEFAULT_MAX_PENDING_REFRESH_NODE_REQUESTS;
6566 private volatile int maxPendingRefreshSchemaRequests = DEFAULT_MAX_PENDING_REFRESH_SCHEMA_REQUESTS;
@@ -272,6 +273,50 @@
272273 return this.reprepareOnUp;
273274 }
274275
276+ /**
277+ * Toggle client-side token and schema metadata.
278+ * <p>
279+ * This feature is enabled by default. Some applications might wish to disable it
280+ * in order to eliminate the overhead of querying the metadata and building its
281+ * client-side representation. However, take note that doing so will have important
282+ * consequences:
283+ * <ul>
284+ * <li>most schema- or token-related methods in {@link Metadata} will return stale
285+ * or null/empty results (see the javadoc of each method for details);</li>
286+ * <li>{@link Metadata#newToken(String)} and
287+ * {@link Metadata#newTokenRange(Token, Token)} will throw an exception if metadata
288+ * was disabled before startup;</li>
289+ * <li>token-aware routing will not work properly: if metadata was never initialized,
290+ * {@link com.datastax.driver.core.policies.TokenAwarePolicy} will always delegate
291+ * to its child policy. Otherwise, it might not pick the best coordinator (i.e. chose
292+ * a host that is not a replica for the statement's routing key). In addition, statements
293+ * prepared while the metadata was disabled might also be sent to a non-optimal coordinator,
294+ * even if metadata was re-enabled later.</li>
295+ * </ul>
296+ *
297+ * @param enabled whether metadata is enabled.
298+ * @return this {@code QueryOptions} instance.
299+ */
300+ public QueryOptions setMetadataEnabled(boolean enabled) {
301+ boolean wasEnabled = this.metadataEnabled;
302+ this.metadataEnabled = enabled;
303+ if (!wasEnabled && enabled && manager != null) {
304+ manager.submitSchemaRefresh(null, null); // will also refresh token map
305+ }
306+ return this;
307+ }
308+
309+ /**
310+ * Whether client-side token and schema metadata is enabled.
311+ *
312+ * @return the value.
313+ *
314+ * @see #setMetadataEnabled(boolean)
315+ */
316+ public boolean isMetadataEnabled() {
317+ return metadataEnabled;
318+ }
319+
275320 /**
276321 * Sets the default window size in milliseconds used to debounce node list refresh requests.
277322 * <p>