Elffuss BraidHub

kikocis/java-driver public

JAVA-1193: Refresh token and replica metadata synchronously when schema is altered

This commit also introduces the following refactorings:

1) Cache and reuse host and token information whenever possible

This commit modifies the TokenMap class so that it caches all
the information about hosts and tokens from the last token map
computation. This information can then be reused in a subsequent
token map computation, if only the schema has changed, but not
the topology.

2) Optimize calls to submitNodeListRefresh()

In some circonstances, this method could be called recursively
(i.e., triggered while already processing a node list refresh request).

This commit suppresses the calls to submitNodeListRefresh() from
ControlConnection and replaces them with calls to that method only
when appropriate, i.e.:
- When inside a node refresh, and the node has been added or removed;
- When reconnecting, and the node has been added.

The effect is that submitNodeListRefresh() is NOT called when in
triggerOnAdd() nor in triggerOnRemove(), because we are already inside
a node list refresh operation.

3) Minor optimizations

This commit optimizes code around TokenMap:
- Remove unnecessary field TokenMap.hosts
- Rename fields in TokenMap for consistency
- Avoid creating intermediary Set<String> instances by creating
Set<Token> instances directly when reading rows from system.local and
system.peers.
Changeset7518b703ac6326d0d7d40e6bd7958a0f273c1496f3b3155c87ee40294c659b1b
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-05-11 16:01 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2016-07-08 09:06 -07:00
Parents66728a15bc91

Browse the files at this changeset

8 files changed

modified changelog/README.md +1 −0
@@ -18,6 +18,7 @@
1818 - [improvement] JAVA-1227: Document "SELECT *" issue with prepared statement.
1919 - [bug] JAVA-1160: Fix NPE in VersionNumber.getPreReleaseLabels().
2020 - [improvement] JAVA-1126: Handle schema changes in Mapper.
21+- [bug] JAVA-1193: Refresh token and replica metadata synchronously when schema is altered.
2122
2223
2324 ### 3.0.2
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +9 −6
@@ -1851,9 +1851,10 @@
18511851 if (controlConnection.refreshNodeInfo(host)) {
18521852 logger.debug("Successful reconnection to {}, setting host UP", host);
18531853 try {
1854- if (isHostAddition)
1854+ if (isHostAddition) {
18551855 onAdd(host, connection);
1856- else
1856+ submitNodeListRefresh();
1857+ } else
18571858 onUp(host, connection);
18581859 } catch (InterruptedException e) {
18591860 Thread.currentThread().interrupt();
@@ -2226,15 +2227,15 @@
22262227 return schemaRefreshRequestDebouncer.eventReceived(request);
22272228 }
22282229
2229- void submitNodeListRefresh() {
2230+ ListenableFuture<Void> submitNodeListRefresh() {
22302231 logger.trace("Submitting node list and token map refresh");
2231- nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest());
2232+ return nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest());
22322233 }
22332234
2234- void submitNodeRefresh(InetSocketAddress address, HostEvent eventType) {
2235+ ListenableFuture<Void> submitNodeRefresh(InetSocketAddress address, HostEvent eventType) {
22352236 NodeRefreshRequest request = new NodeRefreshRequest(address, eventType);
22362237 logger.trace("Submitting node refresh: {}", request);
2237- nodeRefreshRequestDebouncer.eventReceived(request);
2238+ return nodeRefreshRequestDebouncer.eventReceived(request);
22382239 }
22392240
22402241 // refresh the schema using the provided connection, and notice the future with the provided resultset once done
@@ -2709,6 +2710,7 @@
27092710 public void runMayThrow() throws Exception {
27102711 if (controlConnection.refreshNodeInfo(host)) {
27112712 onAdd(host, null);
2713+ submitNodeListRefresh();
27122714 } else {
27132715 logger.debug("Not enough info for {}, ignoring host", host);
27142716 }
@@ -2745,6 +2747,7 @@
27452747 if (metadata.remove(host)) {
27462748 logger.info("Cassandra host {} removed", host);
27472749 onRemove(host);
2750+ submitNodeListRefresh();
27482751 }
27492752 }
27502753 };
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +37 −29
@@ -267,16 +267,15 @@
267267
268268 // We need to refresh the node list first so we know about the cassandra version of
269269 // the node we're connecting to.
270+ // This will create the token map for the first time, but it will be incomplete
271+ // due to the lack of keyspace information
270272 refreshNodeListAndTokenMap(connection, cluster, isInitialConnection, true);
271273
274+ // refresh schema will also update the token map again,
275+ // this time with information about keyspaces
272276 logger.debug("[Control connection] Refreshing schema");
273277 refreshSchema(connection, null, null, null, null, cluster);
274278
275- // We need to refresh the node list again;
276- // We want that because the token map was not properly initialized by the first call above,
277- // since it requires the list of keyspaces to be loaded.
278- refreshNodeListAndTokenMap(connection, cluster, false, false);
279-
280279 return connection;
281280 } catch (BusyConnectionException e) {
282281 connection.closeAsync().force();
@@ -306,11 +305,6 @@
306305 if (c == null || c.isClosed())
307306 return;
308307 refreshSchema(c, targetType, targetKeyspace, targetName, signature, cluster);
309- // If we rebuild all from scratch or have an updated keyspace, rebuild the token map
310- // since some replication on some keyspace may have changed
311- if ((targetType == null || targetType == KEYSPACE)) {
312- cluster.submitNodeListRefresh();
313- }
314308 } catch (ConnectionException e) {
315309 logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage());
316310 signalError();
@@ -545,7 +539,8 @@
545539 connection.write(peersFuture);
546540
547541 String partitioner = null;
548- Map<Host, Collection<String>> tokenMap = new HashMap<Host, Collection<String>>();
542+ Token.Factory factory = null;
543+ Map<Host, Set<Token>> tokenMap = new HashMap<Host, Set<Token>>();
549544
550545 // Update cluster name, DC and rack for the one node we are connected to
551546 Row localRow = localFuture.get().one();
@@ -555,8 +550,10 @@
555550 cluster.metadata.clusterName = clusterName;
556551
557552 partitioner = localRow.getString("partitioner");
558- if (partitioner != null)
553+ if (partitioner != null) {
559554 cluster.metadata.partitioner = partitioner;
555+ factory = Token.getFactory(partitioner);
556+ }
560557
561558 Host host = cluster.metadata.getHost(connection.address);
562559 // In theory host can't be null. However there is no point in risking a NPE in case we
@@ -565,10 +562,12 @@
565562 logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address);
566563 } else {
567564 updateInfo(host, localRow, cluster, isInitialConnection);
568- if (metadataEnabled) {
569- Set<String> tokens = localRow.getSet("tokens", String.class);
570- if (partitioner != null && !tokens.isEmpty())
565+ if (metadataEnabled && factory != null) {
566+ Set<String> tokensStr = localRow.getSet("tokens", String.class);
567+ if (!tokensStr.isEmpty()) {
568+ Set<Token> tokens = toTokens(factory, tokensStr);
571569 tokenMap.put(host, tokens);
570+ }
572571 }
573572 }
574573 }
@@ -579,7 +578,7 @@
579578 List<String> cassandraVersions = new ArrayList<String>();
580579 List<InetAddress> broadcastAddresses = new ArrayList<InetAddress>();
581580 List<InetAddress> listenAddresses = new ArrayList<InetAddress>();
582- List<Set<String>> allTokens = new ArrayList<Set<String>>();
581+ List<Set<Token>> allTokens = new ArrayList<Set<Token>>();
583582 List<String> dseVersions = new ArrayList<String>();
584583 List<Boolean> dseGraphEnabled = new ArrayList<Boolean>();
585584 List<String> dseWorkloads = new ArrayList<String>();
@@ -596,8 +595,14 @@
596595 racks.add(row.getString("rack"));
597596 cassandraVersions.add(row.getString("release_version"));
598597 broadcastAddresses.add(row.getInet("peer"));
599- if (metadataEnabled)
600- allTokens.add(row.getSet("tokens", String.class));
598+ if (metadataEnabled && factory != null) {
599+ Set<String> tokensStr = row.getSet("tokens", String.class);
600+ Set<Token> tokens = null;
601+ if (!tokensStr.isEmpty()) {
602+ tokens = toTokens(factory, tokensStr);
603+ }
604+ allTokens.add(tokens);
605+ }
601606 InetAddress listenAddress = row.getColumnDefinitions().contains("listen_address") ? row.getInet("listen_address") : null;
602607 listenAddresses.add(listenAddress);
603608 String dseWorkload = row.getColumnDefinitions().contains("workload") ? row.getString("workload") : null;
@@ -640,7 +645,7 @@
640645 if (dseGraphEnabled.get(i) != null)
641646 host.setDseGraphEnabled(dseGraphEnabled.get(i));
642647
643- if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty())
648+ if (metadataEnabled && factory != null && allTokens.get(i) != null)
644649 tokenMap.put(host, allTokens.get(i));
645650
646651 if (isNew && !isInitialConnection)
@@ -653,8 +658,16 @@
653658 if (!host.getSocketAddress().equals(connection.address) && !foundHostsSet.contains(host.getSocketAddress()))
654659 cluster.removeHost(host, isInitialConnection);
655660
656- if (metadataEnabled)
657- cluster.metadata.rebuildTokenMap(partitioner, tokenMap);
661+ if (metadataEnabled && factory != null && !tokenMap.isEmpty())
662+ cluster.metadata.rebuildTokenMap(factory, tokenMap);
663+ }
664+
665+ private static Set<Token> toTokens(Token.Factory factory, Set<String> tokensStr) {
666+ Set<Token> tokens = new LinkedHashSet<Token>(tokensStr.size());
667+ for (String tokenStr : tokensStr) {
668+ tokens.add(factory.fromString(tokenStr));
669+ }
670+ return tokens;
658671 }
659672
660673 private static boolean isValidPeer(Row peerRow, boolean logIfInvalid) {
@@ -756,13 +769,15 @@
756769 public void onUp(Host host) {
757770 }
758771
772+ public void onAdd(Host host) {
773+ }
774+
759775 public void onDown(Host host) {
760776 onHostGone(host);
761777 }
762778
763779 public void onRemove(Host host) {
764780 onHostGone(host);
765- cluster.submitNodeListRefresh();
766781 }
767782
768783 private void onHostGone(Host host) {
@@ -783,11 +798,4 @@
783798 backgroundReconnect(0);
784799 }
785800
786- public void onAdd(Host host) {
787- // Refresh infos and token map if we didn't knew about that host, i.e. if we either don't have basic infos on it,
788- // or it's not part of our computed token map
789- Metadata.TokenMap tkmap = cluster.metadata.tokenMap;
790- if (host.getCassandraVersion() == null || tkmap == null || !tkmap.hosts.contains(host))
791- cluster.submitNodeListRefresh();
792- }
793801 }
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +47 −41
@@ -41,7 +41,7 @@
4141 volatile String partitioner;
4242 private final ConcurrentMap<InetSocketAddress, Host> hosts = new ConcurrentHashMap<InetSocketAddress, Host>();
4343 final ConcurrentMap<String, KeyspaceMetadata> keyspaces = new ConcurrentHashMap<String, KeyspaceMetadata>();
44- volatile TokenMap tokenMap;
44+ private volatile TokenMap tokenMap;
4545
4646 final ReentrantLock lock = new ReentrantLock();
4747
@@ -62,18 +62,28 @@
6262 this.cluster = cluster;
6363 }
6464
65- void rebuildTokenMap(String partitioner, Map<Host, Collection<String>> allTokens) {
65+ // rebuilds the token map with the current hosts, typically when refreshing schema metadata
66+ void rebuildTokenMap() {
6667 lock.lock();
6768 try {
68- if (allTokens.isEmpty())
69- return;
70-
71- Token.Factory factory = partitioner == null
72- ? (tokenMap == null ? null : tokenMap.factory)
73- : Token.getFactory(partitioner);
74- if (factory == null)
69+ if (tokenMap == null)
7570 return;
71+ this.tokenMap = TokenMap.build(
72+ tokenMap.factory,
73+ tokenMap.primaryToTokens,
74+ keyspaces.values(),
75+ tokenMap.ring,
76+ tokenMap.tokenRanges,
77+ tokenMap.tokenToPrimary);
78+ } finally {
79+ lock.unlock();
80+ }
81+ }
7682
83+ // rebuilds the token map for a new set of hosts, typically when refreshing nodes list
84+ void rebuildTokenMap(Token.Factory factory, Map<Host, Set<Token>> allTokens) {
85+ lock.lock();
86+ try {
7787 this.tokenMap = TokenMap.build(factory, allTokens, keyspaces.values());
7888 } finally {
7989 lock.unlock();
@@ -264,7 +274,7 @@
264274 if (current == null) {
265275 return Collections.emptySet();
266276 } else {
267- Map<Host, Set<TokenRange>> dcRanges = current.hostsToRanges.get(keyspace);
277+ Map<Host, Set<TokenRange>> dcRanges = current.hostsToRangesByKeyspace.get(keyspace);
268278 if (dcRanges == null) {
269279 return Collections.emptySet();
270280 } else {
@@ -384,7 +394,7 @@
384394 KeyspaceMetadata removeKeyspace(String keyspace) {
385395 KeyspaceMetadata removed = keyspaces.remove(keyspace);
386396 if (tokenMap != null)
387- tokenMap.tokenToHosts.remove(keyspace);
397+ tokenMap.tokenToHostsByKeyspace.remove(keyspace);
388398 return removed;
389399 }
390400
@@ -609,61 +619,57 @@
609619 }
610620 }
611621
612- static class TokenMap {
622+ private static class TokenMap {
613623
614624 private final Token.Factory factory;
615- private final Map<String, Map<Token, Set<Host>>> tokenToHosts;
616- private final Map<String, Map<Host, Set<TokenRange>>> hostsToRanges;
625+ private final Map<Host, Set<Token>> primaryToTokens;
626+ private final Map<String, Map<Token, Set<Host>>> tokenToHostsByKeyspace;
627+ private final Map<String, Map<Host, Set<TokenRange>>> hostsToRangesByKeyspace;
617628 private final List<Token> ring;
618629 private final Set<TokenRange> tokenRanges;
619- final Set<Host> hosts;
630+ private final Map<Token, Host> tokenToPrimary;
620631
621632 private TokenMap(Token.Factory factory,
633+ List<Token> ring,
634+ Set<TokenRange> tokenRanges,
635+ Map<Token, Host> tokenToPrimary,
622636 Map<Host, Set<Token>> primaryToTokens,
623- Map<String, Map<Token, Set<Host>>> tokenToHosts,
624- Map<String, Map<Host, Set<TokenRange>>> hostsToRanges,
625- List<Token> ring, Set<TokenRange> tokenRanges, Set<Host> hosts) {
637+ Map<String, Map<Token, Set<Host>>> tokenToHostsByKeyspace,
638+ Map<String, Map<Host, Set<TokenRange>>> hostsToRangesByKeyspace) {
626639 this.factory = factory;
627- this.tokenToHosts = tokenToHosts;
628- this.hostsToRanges = hostsToRanges;
629640 this.ring = ring;
630641 this.tokenRanges = tokenRanges;
631- this.hosts = hosts;
642+ this.tokenToPrimary = tokenToPrimary;
643+ this.primaryToTokens = primaryToTokens;
644+ this.tokenToHostsByKeyspace = tokenToHostsByKeyspace;
645+ this.hostsToRangesByKeyspace = hostsToRangesByKeyspace;
632646 for (Map.Entry<Host, Set<Token>> entry : primaryToTokens.entrySet()) {
633647 Host host = entry.getKey();
634648 host.setTokens(ImmutableSet.copyOf(entry.getValue()));
635649 }
636650 }
637651
638- public static TokenMap build(Token.Factory factory, Map<Host, Collection<String>> allTokens, Collection<KeyspaceMetadata> keyspaces) {
639-
640- Set<Host> hosts = allTokens.keySet();
652+ private static TokenMap build(Token.Factory factory, Map<Host, Set<Token>> allTokens, Collection<KeyspaceMetadata> keyspaces) {
641653 Map<Token, Host> tokenToPrimary = new HashMap<Token, Host>();
642- Map<Host, Set<Token>> primaryToTokens = new HashMap<Host, Set<Token>>();
643654 Set<Token> allSorted = new TreeSet<Token>();
644-
645- for (Map.Entry<Host, Collection<String>> entry : allTokens.entrySet()) {
655+ for (Map.Entry<Host, ? extends Collection<Token>> entry : allTokens.entrySet()) {
646656 Host host = entry.getKey();
647- for (String tokenStr : entry.getValue()) {
657+ for (Token t : entry.getValue()) {
648658 try {
649- Token t = factory.fromString(tokenStr);
650659 allSorted.add(t);
651660 tokenToPrimary.put(t, host);
652- Set<Token> hostTokens = primaryToTokens.get(host);
653- if (hostTokens == null) {
654- hostTokens = new HashSet<Token>();
655- primaryToTokens.put(host, hostTokens);
656- }
657- hostTokens.add(t);
658661 } catch (IllegalArgumentException e) {
659662 // If we failed parsing that token, skip it
660663 }
661664 }
662665 }
663-
664666 List<Token> ring = new ArrayList<Token>(allSorted);
665667 Set<TokenRange> tokenRanges = makeTokenRanges(ring, factory);
668+ return build(factory, allTokens, keyspaces, ring, tokenRanges, tokenToPrimary);
669+ }
666670
671+ private static TokenMap build(Token.Factory factory, Map<Host, Set<Token>> allTokens, Collection<KeyspaceMetadata> keyspaces, List<Token> ring, Set<TokenRange> tokenRanges, Map<Token, Host> tokenToPrimary) {
672+ Set<Host> hosts = allTokens.keySet();
667673 Map<String, Map<Token, Set<Host>>> tokenToHosts = new HashMap<String, Map<Token, Set<Host>>>();
668674 Map<ReplicationStrategy, Map<Token, Set<Host>>> replStrategyToHosts = new HashMap<ReplicationStrategy, Map<Token, Set<Host>>>();
669675 Map<String, Map<Host, Set<TokenRange>>> hostsToRanges = new HashMap<String, Map<Host, Set<TokenRange>>>();
@@ -691,17 +697,17 @@
691697 }
692698 hostsToRanges.put(keyspace.getName(), ksRanges);
693699 }
694- return new TokenMap(factory, primaryToTokens, tokenToHosts, hostsToRanges, ring, tokenRanges, hosts);
700+ return new TokenMap(factory, ring, tokenRanges, tokenToPrimary, allTokens, tokenToHosts, hostsToRanges);
695701 }
696702
697703 private Set<Host> getReplicas(String keyspace, Token token) {
698704
699- Map<Token, Set<Host>> keyspaceHosts = tokenToHosts.get(keyspace);
700- if (keyspaceHosts == null)
705+ Map<Token, Set<Host>> tokenToHosts = tokenToHostsByKeyspace.get(keyspace);
706+ if (tokenToHosts == null)
701707 return Collections.emptySet();
702708
703709 // If the token happens to be one of the "primary" tokens, get result directly
704- Set<Host> hosts = keyspaceHosts.get(token);
710+ Set<Host> hosts = tokenToHosts.get(token);
705711 if (hosts != null)
706712 return hosts;
707713
@@ -713,7 +719,7 @@
713719 i = 0;
714720 }
715721
716- return keyspaceHosts.get(ring.get(i));
722+ return tokenToHosts.get(ring.get(i));
717723 }
718724
719725 private static Map<Token, Set<Host>> makeNonReplicatedMap(Map<Token, Host> input) {
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +15 −1
@@ -16,6 +16,8 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
19+import com.datastax.driver.core.utils.MoreFutures;
20+import com.google.common.util.concurrent.Futures;
1921
2022 /**
2123 * Options related to defaults for individual queries.
@@ -299,7 +301,19 @@
299301 boolean wasEnabled = this.metadataEnabled;
300302 this.metadataEnabled = enabled;
301303 if (!wasEnabled && enabled && manager != null) {
302- manager.submitSchemaRefresh(null, null, null, null); // will also refresh token map
304+ // This is roughly the same as what we do in ControlConnection.tryConnect():
305+ // 1. call submitNodeListRefresh() first to
306+ // be able to compute the token map for the first time,
307+ // which will be incomplete due to the lack of keyspace metadata
308+ Futures.addCallback(manager.submitNodeListRefresh(), new MoreFutures.SuccessCallback<Void>() {
309+ @Override
310+ public void onSuccess(Void result) {
311+ // 2. then call submitSchemaRefresh() to
312+ // refresh schema metadata and re-compute the token map
313+ // this time with information about keyspaces
314+ manager.submitSchemaRefresh(null, null, null, null);
315+ }
316+ });
303317 }
304318 return this;
305319 }
modified driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +3 −0
@@ -63,6 +63,9 @@
6363 assert rows.keyspaces != null;
6464 Map<String, KeyspaceMetadata> keyspaces = buildKeyspaces(rows, cassandraVersion, cluster);
6565 updateKeyspaces(metadata, metadata.keyspaces, keyspaces, targetKeyspace);
66+ // If we rebuild all from scratch or have an updated keyspace, rebuild the token map
67+ // since some replication on some keyspace may have changed
68+ metadata.rebuildTokenMap();
6669 } else {
6770 assert targetKeyspace != null;
6871 KeyspaceMetadata keyspace = metadata.keyspaces.get(targetKeyspace);
modified driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +7 −39
@@ -18,11 +18,7 @@
1818 import org.testng.annotations.BeforeMethod;
1919 import org.testng.annotations.Test;
2020
21-import java.util.Collection;
22-
2321 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
24-import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
25-import static com.google.common.collect.Lists.newArrayList;
2622 import static org.mockito.Mockito.*;
2723
2824 @CreateCCM(PER_METHOD)
@@ -31,21 +27,14 @@
3127
3228 private static final int DEBOUNCE_TIME = 2000;
3329
34- QueryOptions queryOptions;
35-
36- Cluster cluster2;
37-
38- Session session2;
30+ private Cluster cluster2;
3931
4032 // Control Connection to be spied.
4133 private ControlConnection controlConnection;
4234
43- // Keyspaces to drop after test completes.
44- private Collection<String> keyspaces = newArrayList();
45-
4635 @BeforeMethod(groups = "short")
4736 public void setup() {
48- queryOptions = new QueryOptions();
37+ QueryOptions queryOptions = new QueryOptions();
4938 queryOptions.setRefreshNodeListIntervalMillis(DEBOUNCE_TIME);
5039 queryOptions.setMaxPendingRefreshNodeListRequests(5);
5140 queryOptions.setRefreshSchemaIntervalMillis(0);
@@ -55,7 +44,8 @@
5544 .withPort(ccm().getBinaryPort())
5645 .withQueryOptions(queryOptions)
5746 .build());
58- session2 = cluster2.connect();
47+
48+ cluster2.init();
5949
6050 // Create a spy of the Cluster's control connection and replace it with the spy.
6151 controlConnection = spy(cluster2.manager.controlConnection);
@@ -63,23 +53,6 @@
6353 reset(controlConnection);
6454 }
6555
66- /**
67- * Ensures that when a keyspace is created that refresh node list request
68- * is debounced and processed within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
69- * + {@link QueryOptions#getRefreshNodeListIntervalMillis()}.
70- *
71- * @jira_ticket JAVA-657
72- * @since 2.0.11
73- */
74- @Test(groups = "short")
75- public void should_debounce_refresh_when_keyspace_created() {
76- String keyspace = "sdrwkc";
77- session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
78- keyspaces.add(keyspace);
79-
80- verify(controlConnection, timeout(DEBOUNCE_TIME + queryOptions.getRefreshSchemaIntervalMillis())).refreshNodeListAndTokenMap();
81- }
82-
8356 /**
8457 * Ensures that when enough refreshNodeList requests have been received
8558 * to reach {@link QueryOptions#getMaxPendingRefreshNodeListRequests()} that a
@@ -90,16 +63,11 @@
9063 */
9164 @Test(groups = "short")
9265 public void should_refresh_when_max_pending_requests_reached() {
93- // Create keyspaces 5 times to cause
94- // refreshNodeListAndTokenMap to be called.
95- String prefix = "srwmprr";
9666 for (int i = 0; i < 5; i++) {
97- String keyspace = prefix + i;
98- session().execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
99- keyspaces.add(keyspace);
67+ cluster2.manager.submitNodeListRefresh();
10068 }
10169
102- // add a 1 second delay to account for executor submit.
103- verify(controlConnection, timeout(1000)).refreshNodeListAndTokenMap();
70+ // add delay to account for executor submit.
71+ verify(controlConnection, timeout(DEBOUNCE_TIME)).refreshNodeListAndTokenMap();
10472 }
10573 }
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +59 −67
@@ -44,7 +44,9 @@
4444 private static final String DROP_TABLE = "DROP TABLE %s.table1";
4545
4646 /**
47- * The maximum time that the test will wait to check that listeners have been notified
47+ * The maximum time that the test will wait to check that listeners have been notified.
48+ * This threshold is intentionally set to a very high value to allow CI tests
49+ * to pass.
4850 */
4951 private static final long NOTIF_TIMEOUT_MS = TimeUnit.MINUTES.toMillis(1);
5052
@@ -89,7 +91,7 @@
8991 cluster2.init();
9092
9193 cluster1.register(listener1 = mock(SchemaChangeListener.class));
92- cluster1.register(listener2 = mock(SchemaChangeListener.class));
94+ cluster2.register(listener2 = mock(SchemaChangeListener.class));
9395 listeners = Lists.newArrayList(listener1, listener2);
9496
9597 schemaDisabledCluster.register(schemaDisabledListener = mock(SchemaChangeListener.class));
@@ -150,7 +152,6 @@
150152 .isInKeyspace(handleId(keyspace))
151153 .hasName("table1");
152154 }
153- refreshSchema();
154155 for (Metadata m : metadatas())
155156 assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull();
156157 }
@@ -166,7 +167,6 @@
166167 .isInKeyspace(handleId(keyspace))
167168 .hasName("table1");
168169 }
169- refreshSchema();
170170 for (Metadata m : metadatas())
171171 assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j");
172172 assert added != null;
@@ -183,7 +183,6 @@
183183 .hasName("table1")
184184 .hasColumn("j");
185185 }
186- refreshSchema();
187186 for (Metadata m : metadatas())
188187 assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j");
189188 }
@@ -198,14 +197,12 @@
198197 .hasName("table1")
199198 .isInKeyspace(handleId(keyspace));
200199 }
201- refreshSchema();
202200 execute(DROP_TABLE, keyspace);
203201 for (SchemaChangeListener listener : listeners) {
204202 ArgumentCaptor<TableMetadata> removed = ArgumentCaptor.forClass(TableMetadata.class);
205203 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(removed.capture());
206204 assertThat(removed.getValue()).hasName("table1");
207205 }
208- refreshSchema();
209206 for (Metadata m : metadatas())
210207 assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull();
211208 }
@@ -221,7 +218,6 @@
221218 assertThat((DataType) added.getValue())
222219 .isUserType(handleId(keyspace), "type1");
223220 }
224- refreshSchema();
225221 for (Metadata m : metadatas())
226222 assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNotNull();
227223 }
@@ -238,7 +234,6 @@
238234 assertThat(previous.getValue().getFieldNames()).doesNotContain("j");
239235 assertThat(current.getValue().getFieldNames()).contains("j");
240236 }
241- refreshSchema();
242237 for (Metadata m : metadatas())
243238 assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j")).isNotNull();
244239 }
@@ -254,7 +249,6 @@
254249 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeRemoved(removed.capture());
255250 assertThat((DataType) removed.getValue()).isUserType(handleId(keyspace), "type1");
256251 }
257- refreshSchema();
258252 for (Metadata m : metadatas())
259253 assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNull();
260254 }
@@ -263,7 +257,6 @@
263257 @CassandraVersion(major = 2.2)
264258 public void should_notify_of_function_creation(String keyspace) {
265259 session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
266-
267260 for (SchemaChangeListener listener : listeners) {
268261 ArgumentCaptor<FunctionMetadata> added = ArgumentCaptor.forClass(FunctionMetadata.class);
269262 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionAdded(added.capture());
@@ -271,7 +264,6 @@
271264 .isInKeyspace(handleId(keyspace))
272265 .hasSignature("\"ID\"(int)");
273266 }
274- refreshSchema();
275267 for (Metadata m : metadatas())
276268 assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()))
277269 .isNotNull();
@@ -280,47 +272,44 @@
280272 @Test(groups = "short", dataProvider = "existingKeyspaceName")
281273 @CassandraVersion(major = 2.2)
282274 public void should_notify_of_function_update(String keyspace) {
283- session1.execute(String.format("CREATE TYPE IF NOT EXISTS %s.user (\"ID\" int, name text)", keyspace));
284- session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return user.getInt(\"ID\");'", keyspace));
285- refreshSchema();
286-
275+ session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
276+ for (SchemaChangeListener listener : listeners) {
277+ ArgumentCaptor<FunctionMetadata> added = ArgumentCaptor.forClass(FunctionMetadata.class);
278+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionAdded(added.capture());
279+ assertThat(added.getValue())
280+ .isInKeyspace(handleId(keyspace))
281+ .hasSignature("\"ID\"(int)");
282+ }
287283 for (Metadata m : metadatas())
288- assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")).getBody())
289- .isEqualTo("return user.getInt(\"ID\");");
290-
291- session1.execute(String.format("CREATE OR REPLACE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java "
292- + "AS 'return 1 + user.getInt(\"ID\");'", keyspace));
293-
284+ assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()))
285+ .isNotNull();
286+ session1.execute(String.format("CREATE OR REPLACE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i + 1;'", keyspace));
294287 for (SchemaChangeListener listener : listeners) {
295288 ArgumentCaptor<FunctionMetadata> current = ArgumentCaptor.forClass(FunctionMetadata.class);
296289 ArgumentCaptor<FunctionMetadata> previous = ArgumentCaptor.forClass(FunctionMetadata.class);
297290 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionChanged(current.capture(), previous.capture());
298- assertThat(previous.getValue()).hasBody("return user.getInt(\"ID\");");
299- assertThat(current.getValue()).hasBody("return 1 + user.getInt(\"ID\");");
291+ assertThat(previous.getValue()).hasBody("return i;");
292+ assertThat(current.getValue()).hasBody("return i + 1;");
300293 }
301- refreshSchema();
302294 for (Metadata m : metadatas())
303- assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")).getBody())
304- .isEqualTo("return 1 + user.getInt(\"ID\");");
295+ assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()).getBody())
296+ .isEqualTo("return i + 1;");
305297 }
306298
307299 @Test(groups = "short", dataProvider = "existingKeyspaceName")
308300 @CassandraVersion(major = 2.2)
309301 public void should_notify_of_function_drop(String keyspace) {
310- session1.execute(String.format("CREATE TYPE IF NOT EXISTS %s.user (\"ID\" int, name text)", keyspace));
311- session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(user user) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return user.getInt(\"ID\");'", keyspace));
302+ session1.execute(String.format("CREATE FUNCTION %s.\"ID\"(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
312303 session1.execute(String.format("DROP FUNCTION %s.\"ID\"", keyspace));
313-
314304 for (SchemaChangeListener listener : listeners) {
315305 ArgumentCaptor<FunctionMetadata> removed = ArgumentCaptor.forClass(FunctionMetadata.class);
316306 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionRemoved(removed.capture());
317307 assertThat(removed.getValue())
318308 .isInKeyspace(handleId(keyspace))
319- .hasSignature("\"ID\"(user)");
309+ .hasSignature("\"ID\"(int)");
320310 }
321- refreshSchema();
322311 for (Metadata m : metadatas())
323- assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", m.getKeyspace(keyspace).getUserType("user")))
312+ assertThat(m.getKeyspace(keyspace).getFunction("\"ID\"", DataType.cint()))
324313 .isNull();
325314 }
326315
@@ -330,7 +319,6 @@
330319 session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
331320 + " AS 'return s+v;'", keyspace));
332321 session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0;", keyspace));
333-
334322 for (SchemaChangeListener listener : listeners) {
335323 ArgumentCaptor<AggregateMetadata> added = ArgumentCaptor.forClass(AggregateMetadata.class);
336324 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateAdded(added.capture());
@@ -338,7 +326,6 @@
338326 .isInKeyspace(handleId(keyspace))
339327 .hasSignature("\"SUM\"(int)");
340328 }
341- refreshSchema();
342329 for (Metadata m : metadatas())
343330 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()))
344331 .isNotNull();
@@ -350,13 +337,17 @@
350337 session1.execute(String.format("CREATE FUNCTION %s.\"PLUS\"(s int, v int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java"
351338 + " AS 'return s+v;'", keyspace));
352339 session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
353- refreshSchema();
340+ for (SchemaChangeListener listener : listeners) {
341+ ArgumentCaptor<AggregateMetadata> added = ArgumentCaptor.forClass(AggregateMetadata.class);
342+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateAdded(added.capture());
343+ assertThat(added.getValue())
344+ .isInKeyspace(handleId(keyspace))
345+ .hasSignature("\"SUM\"(int)");
346+ }
354347 for (Metadata m : metadatas())
355348 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond())
356349 .isEqualTo(0);
357-
358350 session1.execute(String.format("CREATE OR REPLACE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 1", keyspace));
359-
360351 for (SchemaChangeListener listener : listeners) {
361352 ArgumentCaptor<AggregateMetadata> current = ArgumentCaptor.forClass(AggregateMetadata.class);
362353 ArgumentCaptor<AggregateMetadata> previous = ArgumentCaptor.forClass(AggregateMetadata.class);
@@ -364,7 +355,6 @@
364355 assertThat(previous.getValue()).hasInitCond(0);
365356 assertThat(current.getValue()).hasInitCond(1);
366357 }
367- refreshSchema();
368358 for (Metadata m : metadatas())
369359 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()).getInitCond())
370360 .isEqualTo(1);
@@ -377,7 +367,6 @@
377367 + " AS 'return s+v;'", keyspace));
378368 session1.execute(String.format("CREATE AGGREGATE %s.\"SUM\"(int) SFUNC \"PLUS\" STYPE int INITCOND 0", keyspace));
379369 session1.execute(String.format("DROP AGGREGATE %s.\"SUM\"", keyspace));
380-
381370 for (SchemaChangeListener listener : listeners) {
382371 ArgumentCaptor<AggregateMetadata> removed = ArgumentCaptor.forClass(AggregateMetadata.class);
383372 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateRemoved(removed.capture());
@@ -385,8 +374,6 @@
385374 .isInKeyspace(handleId(keyspace))
386375 .hasSignature("\"SUM\"(int)");
387376 }
388-
389- refreshSchema();
390377 for (Metadata m : metadatas())
391378 assertThat(m.getKeyspace(keyspace).getAggregate("\"SUM\"", DataType.cint()))
392379 .isNull();
@@ -397,7 +384,12 @@
397384 public void should_notify_of_view_creation(String keyspace) {
398385 session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
399386 session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace));
400- refreshSchema();
387+ for (SchemaChangeListener listener : listeners) {
388+ ArgumentCaptor<MaterializedViewMetadata> removed = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
389+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onMaterializedViewAdded(removed.capture());
390+ assertThat(removed.getValue())
391+ .hasName("mv1");
392+ }
401393 for (Metadata m : metadatas())
402394 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1")).isNotNull();
403395 }
@@ -407,12 +399,26 @@
407399 public void should_notify_of_view_update(String keyspace) {
408400 session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
409401 session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c) WITH compaction = { 'class' : 'SizeTieredCompactionStrategy' }", keyspace, keyspace));
410- refreshSchema();
402+ for (SchemaChangeListener listener : listeners) {
403+ ArgumentCaptor<MaterializedViewMetadata> removed = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
404+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onMaterializedViewAdded(removed.capture());
405+ assertThat(removed.getValue())
406+ .hasName("mv1");
407+ assertThat(removed.getValue().getOptions().getCompaction().get("class"))
408+ .contains("SizeTieredCompactionStrategy");
409+ }
411410 for (Metadata m : metadatas())
412411 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1").getOptions().getCompaction().get("class")).contains("SizeTieredCompactionStrategy");
413-
414412 session1.execute(String.format("ALTER MATERIALIZED VIEW %s.mv1 WITH compaction = { 'class' : 'LeveledCompactionStrategy' }", keyspace));
415- refreshSchema();
413+ for (SchemaChangeListener listener : listeners) {
414+ ArgumentCaptor<MaterializedViewMetadata> current = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
415+ ArgumentCaptor<MaterializedViewMetadata> previous = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
416+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onMaterializedViewChanged(current.capture(), previous.capture());
417+ assertThat(previous.getValue().getOptions().getCompaction().get("class"))
418+ .contains("SizeTieredCompactionStrategy");
419+ assertThat(current.getValue().getOptions().getCompaction().get("class"))
420+ .contains("LeveledCompactionStrategy");
421+ }
416422 for (Metadata m : metadatas())
417423 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1").getOptions().getCompaction().get("class")).contains("LeveledCompactionStrategy");
418424 }
@@ -423,7 +429,12 @@
423429 session1.execute(String.format("CREATE TABLE %s.table1 (pk int PRIMARY KEY, c int)", keyspace));
424430 session1.execute(String.format("CREATE MATERIALIZED VIEW %s.mv1 AS SELECT c FROM %s.table1 WHERE c IS NOT NULL PRIMARY KEY (pk, c)", keyspace, keyspace));
425431 session1.execute(String.format("DROP MATERIALIZED VIEW %s.mv1", keyspace));
426- refreshSchema();
432+ for (SchemaChangeListener listener : listeners) {
433+ ArgumentCaptor<MaterializedViewMetadata> removed = ArgumentCaptor.forClass(MaterializedViewMetadata.class);
434+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onMaterializedViewRemoved(removed.capture());
435+ assertThat(removed.getValue())
436+ .hasName("mv1");
437+ }
427438 for (Metadata m : metadatas())
428439 assertThat(m.getKeyspace(keyspace).getMaterializedView("mv1")).isNull();
429440 }
@@ -436,7 +447,6 @@
436447 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
437448 assertThat(added.getValue()).hasName(handleId(keyspace));
438449 }
439- refreshSchema();
440450 for (Metadata m : metadatas())
441451 assertThat(m.getKeyspace(keyspace)).isNotNull();
442452 }
@@ -451,7 +461,6 @@
451461 assertThat(added.getValue()).hasName(handleId(keyspace));
452462 }
453463 assert added != null;
454- refreshSchema();
455464 for (Metadata m : metadatas())
456465 assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue();
457466 execute(ALTER_KEYSPACE, keyspace);
@@ -466,7 +475,6 @@
466475 .hasName(handleId(keyspace))
467476 .isNotDurableWrites();
468477 }
469- refreshSchema();
470478 for (Metadata m : metadatas())
471479 assertThat(m.getKeyspace(keyspace)).isNotDurableWrites();
472480 }
@@ -474,14 +482,11 @@
474482 @Test(groups = "short", dataProvider = "newKeyspaceName")
475483 public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException {
476484 execute(CREATE_KEYSPACE, keyspace);
477- ArgumentCaptor<KeyspaceMetadata> added = null;
478485 for (SchemaChangeListener listener : listeners) {
479- added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
486+ ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
480487 verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
481488 assertThat(added.getValue()).hasName(handleId(keyspace));
482489 }
483- assert added != null;
484- refreshSchema();
485490 for (Metadata m : metadatas())
486491 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty();
487492 execute(CREATE_TABLE, keyspace); // to test table drop notifications
@@ -497,14 +502,12 @@
497502 assertThat(ks.getValue())
498503 .hasName(handleId(keyspace));
499504 }
500- refreshSchema();
501505 for (Metadata m : metadatas()) {
502506 assertThat(m.getKeyspace(keyspace)).isNull();
503507 assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty();
504508 }
505509 }
506510
507-
508511 /**
509512 * Ensures that calling {@link Metadata#newToken(String)} on a Cluster that has schema
510513 * metadata disabled will throw a {@link IllegalStateException}.
@@ -588,7 +591,6 @@
588591 schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
589592
590593 verify(schemaDisabledControlConnection, after(1000)).refreshSchema(null, null, null, null);
591- verify(schemaDisabledControlConnection).refreshNodeListAndTokenMap();
592594
593595 // Ensure that there is schema metadata.
594596 assertThat(schemaDisabledCluster.getMetadata().getKeyspace(keyspace)).isNotNull();
@@ -604,7 +606,6 @@
604606 reset(schemaDisabledControlConnection);
605607 schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
606608 verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(null, null, null, null);
607- verify(schemaDisabledControlConnection, never()).refreshNodeListAndTokenMap();
608609 } finally {
609610 // Reset listener mock to not count it's interactions in this test.
610611 reset(schemaDisabledListener);
@@ -643,13 +644,4 @@
643644 return Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata());
644645 }
645646
646- @SuppressWarnings("unchecked")
647- private void refreshSchema() {
648- Futures.getUnchecked(
649- Futures.successfulAsList(
650- cluster1.manager.submitSchemaRefresh(null, null, null, null),
651- cluster2.manager.submitSchemaRefresh(null, null, null, null)));
652- }
653-
654-
655647 }