kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | d4015c5defeea658f641cfea4866bbd9457f23e196e48414e758bdc9ef9c8173 |
|---|---|
| Author | Alexandre Dutra <alexdut@gmail.com> · 2015-08-07 18:31 +02:00 |
| Committer | Alexandre Dutra <alexdut@gmail.com> · 2015-08-07 18:31 +02:00 |
| Parents | 46d73a040f8d, 1b8b88ac513c |
15 files changed
modified changelog/README.md +2 −0
| @@ -29,6 +29,8 @@ | ||
| 29 | 29 | - [improvement] Surface the coordinator used on query failure (JAVA-720) |
| 30 | 30 | - [bug] Handle contact points removed during init (JAVA-792) |
| 31 | 31 | - [improvement] Allow PlainTextAuthProvider to change its credentials at runtime (JAVA-719) |
| 32 | +- [new feature] Make it possible to register for SchemaChange Events (JAVA-151) | |
| 33 | +- [improvement] Downgrade "Asked to rebuild table" log from ERROR to INFO level (JAVA-861) | |
| 32 | 34 | |
| 33 | 35 | Merged from 2.0.10_fixes branch: |
| 34 | 36 |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +59 −5
| @@ -435,6 +435,38 @@ | ||
| 435 | 435 | return this; |
| 436 | 436 | } |
| 437 | 437 | |
| 438 | + /** | |
| 439 | + * Registers the provided listener to be updated with schema change events. | |
| 440 | + * <p> | |
| 441 | + * Registering the same listener multiple times is a no-op. | |
| 442 | + * | |
| 443 | + * @param listener the new {@link SchemaChangeListener} to register. | |
| 444 | + * @return this {@code Cluster} object; | |
| 445 | + */ | |
| 446 | + public Cluster register(SchemaChangeListener listener) { | |
| 447 | + checkNotClosed(manager); | |
| 448 | + listener.onRegister(this); | |
| 449 | + manager.schemaChangeListeners.add(listener); | |
| 450 | + return this; | |
| 451 | + } | |
| 452 | + | |
| 453 | + /** | |
| 454 | + * Unregisters the provided schema change listener from being updated | |
| 455 | + * with schema change events. | |
| 456 | + * <p> | |
| 457 | + * This method is a no-op if {@code listener} hadn't previously be | |
| 458 | + * registered against this Cluster. | |
| 459 | + * | |
| 460 | + * @param listener the {@link SchemaChangeListener} to unregister. | |
| 461 | + * @return this {@code Cluster} object; | |
| 462 | + */ | |
| 463 | + public Cluster unregister(SchemaChangeListener listener) { | |
| 464 | + checkNotClosed(manager); | |
| 465 | + listener.onUnregister(this); | |
| 466 | + manager.schemaChangeListeners.remove(listener); | |
| 467 | + return this; | |
| 468 | + } | |
| 469 | + | |
| 438 | 470 | /** |
| 439 | 471 | * Initiates a shutdown of this cluster instance. |
| 440 | 472 | * <p> |
| @@ -1209,6 +1241,7 @@ | ||
| 1209 | 1241 | |
| 1210 | 1242 | final Set<Host.StateListener> listeners; |
| 1211 | 1243 | final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>(); |
| 1244 | + final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>(); | |
| 1212 | 1245 | |
| 1213 | 1246 | private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) { |
| 1214 | 1247 | this.clusterName = clusterName == null ? generateClusterName() : clusterName; |
| @@ -1433,6 +1466,10 @@ | ||
| 1433 | 1466 | if (translater instanceof CloseableAddressTranslater) |
| 1434 | 1467 | ((CloseableAddressTranslater)translater).close(); |
| 1435 | 1468 | |
| 1469 | + for (SchemaChangeListener listener : schemaChangeListeners) { | |
| 1470 | + listener.onUnregister(Cluster.this); | |
| 1471 | + } | |
| 1472 | + | |
| 1436 | 1473 | // Then we shutdown all connections |
| 1437 | 1474 | List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1); |
| 1438 | 1475 | futures.add(controlConnection.closeAsync()); |
| @@ -2189,15 +2226,32 @@ | ||
| 2189 | 2226 | submitSchemaRefresh(scc.keyspace, scc.table); |
| 2190 | 2227 | break; |
| 2191 | 2228 | case DROPPED: |
| 2192 | - if (scc.table.isEmpty()) | |
| 2193 | - manager.metadata.removeKeyspace(scc.keyspace); | |
| 2194 | - else { | |
| 2229 | + if (scc.table.isEmpty()) { | |
| 2230 | + final KeyspaceMetadata removed = manager.metadata.removeKeyspace(scc.keyspace); | |
| 2231 | + if(removed != null) { | |
| 2232 | + executor.submit(new Runnable() { | |
| 2233 | + @Override | |
| 2234 | + public void run() { | |
| 2235 | + manager.metadata.triggerOnKeyspaceRemoved(removed); | |
| 2236 | + } | |
| 2237 | + }); | |
| 2238 | + } | |
| 2239 | + } else { | |
| 2195 | 2240 | KeyspaceMetadata keyspace = manager.metadata.getKeyspaceInternal(scc.keyspace); |
| 2196 | 2241 | if (keyspace == null) |
| 2197 | 2242 | logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata", |
| 2198 | 2243 | scc.keyspace, scc.table); |
| 2199 | - else | |
| 2200 | - keyspace.removeTable(scc.table); | |
| 2244 | + else { | |
| 2245 | + final TableMetadata removed = keyspace.removeTable(scc.table); | |
| 2246 | + if (removed != null) { | |
| 2247 | + executor.submit(new Runnable() { | |
| 2248 | + @Override | |
| 2249 | + public void run() { | |
| 2250 | + manager.metadata.triggerOnTableRemoved(removed); | |
| 2251 | + } | |
| 2252 | + }); | |
| 2253 | + } | |
| 2254 | + } | |
| 2201 | 2255 | } |
| 2202 | 2256 | break; |
| 2203 | 2257 | case UPDATED: |
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +50 −0
| @@ -103,6 +103,34 @@ | ||
| 103 | 103 | return isStatic; |
| 104 | 104 | } |
| 105 | 105 | |
| 106 | + @Override | |
| 107 | + public boolean equals(Object o) { | |
| 108 | + if (this == o) | |
| 109 | + return true; | |
| 110 | + if (o == null || getClass() != o.getClass()) | |
| 111 | + return false; | |
| 112 | + | |
| 113 | + ColumnMetadata that = (ColumnMetadata)o; | |
| 114 | + | |
| 115 | + if (isStatic != that.isStatic) | |
| 116 | + return false; | |
| 117 | + if (!name.equals(that.name)) | |
| 118 | + return false; | |
| 119 | + if (!type.equals(that.type)) | |
| 120 | + return false; | |
| 121 | + return !(index != null ? !index.equals(that.index) : that.index != null); | |
| 122 | + | |
| 123 | + } | |
| 124 | + | |
| 125 | + @Override | |
| 126 | + public int hashCode() { | |
| 127 | + int result = name.hashCode(); | |
| 128 | + result = 31 * result + type.hashCode(); | |
| 129 | + result = 31 * result + (index != null ? index.hashCode() : 0); | |
| 130 | + result = 31 * result + (isStatic ? 1 : 0); | |
| 131 | + return result; | |
| 132 | + } | |
| 133 | + | |
| 106 | 134 | /** |
| 107 | 135 | * Metadata on a column index. |
| 108 | 136 | */ |
| @@ -177,6 +205,28 @@ | ||
| 177 | 205 | : String.format("CREATE INDEX %s ON %s.%s (%s);", name, ksName, cfName, colName); |
| 178 | 206 | } |
| 179 | 207 | |
| 208 | + @Override | |
| 209 | + public boolean equals(Object o) { | |
| 210 | + if (this == o) | |
| 211 | + return true; | |
| 212 | + if (o == null || getClass() != o.getClass()) | |
| 213 | + return false; | |
| 214 | + | |
| 215 | + IndexMetadata that = (IndexMetadata)o; | |
| 216 | + | |
| 217 | + if (!name.equals(that.name)) | |
| 218 | + return false; | |
| 219 | + return !(customClassName != null ? !customClassName.equals(that.customClassName) : that.customClassName != null); | |
| 220 | + | |
| 221 | + } | |
| 222 | + | |
| 223 | + @Override | |
| 224 | + public int hashCode() { | |
| 225 | + int result = name.hashCode(); | |
| 226 | + result = 31 * result + (customClassName != null ? customClassName.hashCode() : 0); | |
| 227 | + return result; | |
| 228 | + } | |
| 229 | + | |
| 180 | 230 | private static IndexMetadata build(ColumnMetadata column, Map<String, String> indexColumns) { |
| 181 | 231 | if (indexColumns.isEmpty()) |
| 182 | 232 | return null; |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +21 −3
| @@ -82,14 +82,32 @@ | ||
| 82 | 82 | // We'll add it back if CASSANDRA-5358 changes that behavior |
| 83 | 83 | //if (scc.keyspace.equals(session.poolsState.keyspace)) |
| 84 | 84 | // session.poolsState.setKeyspace(null); |
| 85 | - session.cluster.manager.metadata.removeKeyspace(scc.keyspace); | |
| 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 | + }); | |
| 93 | + } | |
| 94 | + | |
| 86 | 95 | } else { |
| 87 | 96 | KeyspaceMetadata keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.keyspace); |
| 88 | 97 | if (keyspace == null) |
| 89 | 98 | logger.warn("Received a DROPPED notification for {}.{}, but this keyspace is unknown in our metadata", |
| 90 | 99 | scc.keyspace, scc.columnFamily); |
| 91 | - else | |
| 92 | - keyspace.removeTable(scc.columnFamily); | |
| 100 | + else { | |
| 101 | + final TableMetadata removed = keyspace.removeTable(scc.columnFamily); | |
| 102 | + if (removed != null) { | |
| 103 | + session.cluster.manager.executor.submit(new Runnable() { | |
| 104 | + @Override | |
| 105 | + public void run() { | |
| 106 | + session.cluster.manager.metadata.triggerOnTableRemoved(removed); | |
| 107 | + } | |
| 108 | + }); | |
| 109 | + } | |
| 110 | + } | |
| 93 | 111 | } |
| 94 | 112 | session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs); |
| 95 | 113 | break; |
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +35 −3
| @@ -37,7 +37,7 @@ | ||
| 37 | 37 | private final ReplicationStrategy strategy; |
| 38 | 38 | private final Map<String, String> replication; |
| 39 | 39 | |
| 40 | - private final Map<String, TableMetadata> tables = new ConcurrentHashMap<String, TableMetadata>(); | |
| 40 | + final Map<String, TableMetadata> tables = new ConcurrentHashMap<String, TableMetadata>(); | |
| 41 | 41 | |
| 42 | 42 | private KeyspaceMetadata(String name, boolean durableWrites, Map<String, String> replication) { |
| 43 | 43 | this.name = name; |
| @@ -97,8 +97,8 @@ | ||
| 97 | 97 | return tables.get(Metadata.handleId(name)); |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | - void removeTable(String table) { | |
| 101 | - tables.remove(table); | |
| 100 | + TableMetadata removeTable(String table) { | |
| 101 | + return tables.remove(table); | |
| 102 | 102 | } |
| 103 | 103 | |
| 104 | 104 | /** |
| @@ -159,6 +159,37 @@ | ||
| 159 | 159 | return sb.toString(); |
| 160 | 160 | } |
| 161 | 161 | |
| 162 | + @Override | |
| 163 | + public boolean equals(Object o) { | |
| 164 | + if (this == o) | |
| 165 | + return true; | |
| 166 | + if (o == null || getClass() != o.getClass()) | |
| 167 | + return false; | |
| 168 | + | |
| 169 | + KeyspaceMetadata that = (KeyspaceMetadata)o; | |
| 170 | + | |
| 171 | + if (durableWrites != that.durableWrites) | |
| 172 | + return false; | |
| 173 | + if (!name.equals(that.name)) | |
| 174 | + return false; | |
| 175 | + if (strategy != null ? !strategy.equals(that.strategy) : that.strategy != null) | |
| 176 | + return false; | |
| 177 | + if (!replication.equals(that.replication)) | |
| 178 | + return false; | |
| 179 | + return tables.equals(that.tables); | |
| 180 | + | |
| 181 | + } | |
| 182 | + | |
| 183 | + @Override | |
| 184 | + public int hashCode() { | |
| 185 | + int result = name.hashCode(); | |
| 186 | + result = 31 * result + (durableWrites ? 1 : 0); | |
| 187 | + result = 31 * result + (strategy != null ? strategy.hashCode() : 0); | |
| 188 | + result = 31 * result + replication.hashCode(); | |
| 189 | + result = 31 * result + tables.hashCode(); | |
| 190 | + return result; | |
| 191 | + } | |
| 192 | + | |
| 162 | 193 | void add(TableMetadata tm) { |
| 163 | 194 | tables.put(tm.getName(), tm); |
| 164 | 195 | } |
| @@ -166,4 +197,5 @@ | ||
| 166 | 197 | ReplicationStrategy replicationStrategy() { |
| 167 | 198 | return strategy; |
| 168 | 199 | } |
| 200 | + | |
| 169 | 201 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +184 −72
| @@ -52,12 +52,35 @@ | ||
| 52 | 52 | } |
| 53 | 53 | |
| 54 | 54 | // Synchronized to make it easy to detect dropped keyspaces |
| 55 | - synchronized void rebuildSchema(String keyspace, String table, ResultSet ks, ResultSet cfs, ResultSet cols, VersionNumber cassandraVersion) { | |
| 56 | - | |
| 57 | - Map<String, List<Row>> cfDefs = new HashMap<String, List<Row>>(); | |
| 58 | - Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>(); | |
| 55 | + synchronized void rebuildSchema(String keyspaceToRebuild, String tableToRebuild, ResultSet ks, ResultSet cfs, ResultSet cols, VersionNumber cassandraVersion) { | |
| 56 | + Map<String, List<Row>> tableRows = groupByKeyspace(cfs); | |
| 57 | + Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = groupByKeyspaceAndTable(cols, cassandraVersion); | |
| 58 | + if (tableToRebuild == null) { | |
| 59 | + // building a keyspace (keyspaceToRebuild != null), or the whole schema (keyspaceToRebuild == null) | |
| 60 | + assert ks != null; | |
| 61 | + Map<String, KeyspaceMetadata> keyspaces = buildKeyspaces(ks, tableRows, colsDefs, cassandraVersion); | |
| 62 | + updateKeyspaces(this.keyspaces, keyspaces, keyspaceToRebuild); | |
| 63 | + } else { | |
| 64 | + // building only a table | |
| 65 | + assert keyspaceToRebuild != null; | |
| 66 | + KeyspaceMetadata keyspace = this.keyspaces.get(keyspaceToRebuild); | |
| 67 | + // If we update a keyspace we don't know about, something went | |
| 68 | + // wrong. Log an error and schedule a full schema rebuild. | |
| 69 | + if (keyspace == null) { | |
| 70 | + logger.info(String.format("Asked to rebuild table %s.%s but I don't know keyspace %s", keyspaceToRebuild, tableToRebuild, keyspaceToRebuild)); | |
| 71 | + cluster.submitSchemaRefresh(null, null); | |
| 72 | + return; | |
| 73 | + } | |
| 74 | + if (tableRows.containsKey(keyspaceToRebuild)) { | |
| 75 | + Map<String, TableMetadata> tables = buildTables(keyspace, tableRows.get(keyspaceToRebuild), colsDefs.get(keyspaceToRebuild), cassandraVersion); | |
| 76 | + updateTables(keyspace.tables, tables, tableToRebuild); | |
| 77 | + } | |
| 78 | + } | |
| 79 | + } | |
| 59 | 80 | |
| 81 | + private Map<String, List<Row>> groupByKeyspace(ResultSet cfs) { | |
| 60 | 82 | // Gather cf defs |
| 83 | + Map<String, List<Row>> cfDefs = new HashMap<String, List<Row>>(); | |
| 61 | 84 | for (Row row : cfs) { |
| 62 | 85 | String ksName = row.getString(KeyspaceMetadata.KS_NAME); |
| 63 | 86 | List<Row> l = cfDefs.get(ksName); |
| @@ -67,8 +90,11 @@ | ||
| 67 | 90 | } |
| 68 | 91 | l.add(row); |
| 69 | 92 | } |
| 93 | + return cfDefs; | |
| 94 | + } | |
| 70 | 95 | |
| 71 | - // Gather columns per Cf | |
| 96 | + private Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupByKeyspaceAndTable(ResultSet cols, VersionNumber cassandraVersion) { | |
| 97 | + Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>(); | |
| 72 | 98 | for (Row row : cols) { |
| 73 | 99 | String ksName = row.getString(KeyspaceMetadata.KS_NAME); |
| 74 | 100 | String cfName = row.getString(TableMetadata.CF_NAME); |
| @@ -85,79 +111,164 @@ | ||
| 85 | 111 | ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion); |
| 86 | 112 | l.put(c.name, c); |
| 87 | 113 | } |
| 88 | - | |
| 89 | - if (table == null) { | |
| 90 | - assert ks != null; | |
| 91 | - Set<String> addedKs = new HashSet<String>(); | |
| 92 | - for (Row ksRow : ks) { | |
| 93 | - String ksName = ksRow.getString(KeyspaceMetadata.KS_NAME); | |
| 94 | - KeyspaceMetadata ksm = KeyspaceMetadata.build(ksRow); | |
| 95 | - | |
| 96 | - if (cfDefs.containsKey(ksName)) { | |
| 97 | - buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion); | |
| 98 | - } | |
| 99 | - addedKs.add(ksName); | |
| 100 | - keyspaces.put(ksName, ksm); | |
| 114 | + return colsDefs; | |
| 115 | + } | |
| 116 | + | |
| 117 | + private Map<String, KeyspaceMetadata> buildKeyspaces(ResultSet keyspaceRows, Map<String, List<Row>> tableRows, Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs, VersionNumber cassandraVersion) { | |
| 118 | + Map<String, KeyspaceMetadata> keyspaces = new LinkedHashMap<String, KeyspaceMetadata>(); | |
| 119 | + for (Row keyspaceRow : keyspaceRows) { | |
| 120 | + KeyspaceMetadata keyspace = KeyspaceMetadata.build(keyspaceRow); | |
| 121 | + Map<String, TableMetadata> tables = buildTables(keyspace, tableRows.get(keyspace.getName()), colsDefs.get(keyspace.getName()), cassandraVersion); | |
| 122 | + for (TableMetadata table : tables.values()) { | |
| 123 | + keyspace.add(table); | |
| 101 | 124 | } |
| 102 | - | |
| 103 | - // If keyspace is null, it means we're rebuilding from scratch, so | |
| 104 | - // remove anything that was not just added as it means it's a dropped keyspace | |
| 105 | - if (keyspace == null) { | |
| 106 | - Iterator<String> iter = keyspaces.keySet().iterator(); | |
| 107 | - while (iter.hasNext()) { | |
| 108 | - if (!addedKs.contains(iter.next())) | |
| 109 | - iter.remove(); | |
| 125 | + keyspaces.put(keyspace.getName(), keyspace); | |
| 126 | + } | |
| 127 | + return keyspaces; | |
| 128 | + } | |
| 129 | + | |
| 130 | + private Map<String, TableMetadata> buildTables(KeyspaceMetadata keyspace, List<Row> tableRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) { | |
| 131 | + Map<String, TableMetadata> tables = new LinkedHashMap<String, TableMetadata>(); | |
| 132 | + if(tableRows != null) { | |
| 133 | + for (Row tableDef : tableRows) { | |
| 134 | + String cfName = tableDef.getString(TableMetadata.CF_NAME); | |
| 135 | + try { | |
| 136 | + Map<String, ColumnMetadata.Raw> cols = colsDefs == null ? null : colsDefs.get(cfName); | |
| 137 | + if (cols == null || cols.isEmpty()) { | |
| 138 | + if (cassandraVersion.getMajor() >= 2) { | |
| 139 | + // In C* >= 2.0, we should never have no columns metadata because at the very least we should | |
| 140 | + // have the metadata corresponding to the default CQL metadata. So if we don't have any columns, | |
| 141 | + // that can only mean that the table got creating concurrently with our schema queries, and the | |
| 142 | + // query for columns metadata reached the node before the table was persisted while the table | |
| 143 | + // metadata one reached it afterwards. We could make the query to the column metadata sequential | |
| 144 | + // with the table metadata instead of in parallel, but it's probably not worth making it slower | |
| 145 | + // all the time to avoid this race since 1) it's very very uncommon and 2) we can just ignore the | |
| 146 | + // incomplete table here for now and it'll get updated next time with no particular consequence | |
| 147 | + // (if the table creation was concurrent with our querying, we'll get a notifciation later and | |
| 148 | + // will reupdate the schema for it anyway). See JAVA-320 for why we need this. | |
| 149 | + continue; | |
| 150 | + } else { | |
| 151 | + // C* 1.2 don't persists default CQL metadata, so it's possible not to have columns (for thirft | |
| 152 | + // tables). But in that case TableMetadata.build() knows how to handle it. | |
| 153 | + cols = Collections.emptyMap(); | |
| 154 | + } | |
| 155 | + } | |
| 156 | + TableMetadata table = TableMetadata.build(keyspace, tableDef, cols, cassandraVersion); | |
| 157 | + tables.put(table.getName(), table); | |
| 158 | + } catch (RuntimeException e) { | |
| 159 | + // See ControlConnection#refreshSchema for why we'd rather not probably this further | |
| 160 | + logger.error(String.format("Error parsing schema for table %s.%s: " | |
| 161 | + + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete", | |
| 162 | + keyspace.getName(), cfName, keyspace.getName(), cfName), e); | |
| 110 | 163 | } |
| 111 | 164 | } |
| 112 | - } else { | |
| 113 | - assert keyspace != null; | |
| 114 | - KeyspaceMetadata ksm = keyspaces.get(keyspace); | |
| 165 | + } | |
| 166 | + return tables; | |
| 167 | + } | |
| 115 | 168 | |
| 116 | - // If we update a keyspace we don't know about, something went | |
| 117 | - // wrong. Log an error an schedule a full schema rebuilt. | |
| 118 | - if (ksm == null) { | |
| 119 | - logger.error(String.format("Asked to rebuild table %s.%s but I don't know keyspace %s", keyspace, table, keyspace)); | |
| 120 | - cluster.submitSchemaRefresh(null, null); | |
| 121 | - return; | |
| 169 | + /** | |
| 170 | + * Update {@code oldKeyspaces} with the changes contained in {@code newKeyspaces}. | |
| 171 | + * This method also takes care of triggering the relevant events | |
| 172 | + * as the updates take place. | |
| 173 | + * | |
| 174 | + * @param oldKeyspaces the set of keyspaces to be updated. | |
| 175 | + * @param newKeyspaces the temporary set of keyspaces built with information gathered | |
| 176 | + * from schema tables. | |
| 177 | + * @param keyspaceToRebuild If we are rebuilding just one keyspace, the update operation will be limited | |
| 178 | + * to this keyspace only (in which case {@code newKeyspaces} shoudl contain only one entry for it) | |
| 179 | + */ | |
| 180 | + private void updateKeyspaces(Map<String, KeyspaceMetadata> oldKeyspaces, Map<String, KeyspaceMetadata> newKeyspaces, String keyspaceToRebuild) { | |
| 181 | + Iterator<KeyspaceMetadata> it = oldKeyspaces.values().iterator(); | |
| 182 | + while (it.hasNext()) { | |
| 183 | + KeyspaceMetadata oldKeyspace = it.next(); | |
| 184 | + String keyspaceName = oldKeyspace.getName(); | |
| 185 | + // If we're rebuilding only a single keyspace, we should only consider that one | |
| 186 | + // because newKeyspaces will only contain that keyspace. | |
| 187 | + if ((keyspaceToRebuild == null || keyspaceToRebuild.equals(keyspaceName)) && !newKeyspaces.containsKey(keyspaceName)) { | |
| 188 | + it.remove(); | |
| 189 | + triggerOnKeyspaceRemoved(oldKeyspace); | |
| 190 | + } | |
| 191 | + } | |
| 192 | + for (KeyspaceMetadata newKeyspace : newKeyspaces.values()) { | |
| 193 | + KeyspaceMetadata oldKeyspace = oldKeyspaces.put(newKeyspace.getName(), newKeyspace); | |
| 194 | + if (oldKeyspace == null) { | |
| 195 | + triggerOnKeyspaceAdded(newKeyspace); | |
| 196 | + } else if (!oldKeyspace.equals(newKeyspace)) { | |
| 197 | + triggerOnKeyspaceChanged(newKeyspace, oldKeyspace); | |
| 122 | 198 | } |
| 199 | + Map<String, TableMetadata> oldTables = oldKeyspace == null ? new HashMap<String, TableMetadata>() : oldKeyspace.tables; | |
| 200 | + Map<String, TableMetadata> newTables = newKeyspace.tables; | |
| 201 | + updateTables(oldTables, newTables, null); | |
| 202 | + } | |
| 203 | + } | |
| 123 | 204 | |
| 124 | - if (cfDefs.containsKey(keyspace)) | |
| 125 | - buildTableMetadata(ksm, cfDefs.get(keyspace), colsDefs.get(keyspace), cassandraVersion); | |
| 126 | - } | |
| 127 | - } | |
| 128 | - | |
| 129 | - private void buildTableMetadata(KeyspaceMetadata ksm, List<Row> cfRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) { | |
| 130 | - for (Row cfRow : cfRows) { | |
| 131 | - String cfName = cfRow.getString(TableMetadata.CF_NAME); | |
| 132 | - try { | |
| 133 | - Map<String, ColumnMetadata.Raw> cols = colsDefs == null ? null : colsDefs.get(cfName); | |
| 134 | - if (cols == null || cols.isEmpty()) { | |
| 135 | - if (cassandraVersion.getMajor() >= 2) { | |
| 136 | - // In C* >= 2.0, we should never have no columns metadata because at the very least we should | |
| 137 | - // have the metadata corresponding to the default CQL metadata. So if we don't have any columns, | |
| 138 | - // that can only mean that the table got creating concurrently with our schema queries, and the | |
| 139 | - // query for columns metadata reached the node before the table was persisted while the table | |
| 140 | - // metadata one reached it afterwards. We could make the query to the column metadata sequential | |
| 141 | - // with the table metadata instead of in parallel, but it's probably not worth making it slower | |
| 142 | - // all the time to avoid this race since 1) it's very very uncommon and 2) we can just ignore the | |
| 143 | - // incomplete table here for now and it'll get updated next time with no particular consequence | |
| 144 | - // (if the table creation was concurrent with our querying, we'll get a notifciation later and | |
| 145 | - // will reupdate the schema for it anyway). See JAVA-320 for why we need this. | |
| 146 | - continue; | |
| 147 | - } else { | |
| 148 | - // C* 1.2 don't persists default CQL metadata, so it's possible not to have columns (for thirft | |
| 149 | - // tables). But in that case TableMetadata.build() knows how to handle it. | |
| 150 | - cols = Collections.<String, ColumnMetadata.Raw>emptyMap(); | |
| 151 | - } | |
| 152 | - } | |
| 153 | - TableMetadata.build(ksm, cfRow, cols, cassandraVersion); | |
| 154 | - } catch (RuntimeException e) { | |
| 155 | - // See ControlConnection#refreshSchema for why we'd rather not probably this further | |
| 156 | - logger.error(String.format("Error parsing schema for table %s.%s: " | |
| 157 | - + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete", | |
| 158 | - ksm.getName(), cfName, ksm.getName(), cfName), e); | |
| 205 | + /** | |
| 206 | + * Update {@code oldTables} with the changes contained in {@code newTables}. | |
| 207 | + * This method also takes care of triggering the relevant events | |
| 208 | + * as the updates take place. | |
| 209 | + * | |
| 210 | + * @param oldTables the set of tables to be updated. | |
| 211 | + * @param newTables the temporary set of tables built with information gathered | |
| 212 | + * from schema tables. | |
| 213 | + * @param tableToRebuild If we are rebuilding just one table, the update operation will be limited | |
| 214 | + * to this table only (in which case {@code newTables} shoudl contain only one entry for it) | |
| 215 | + */ | |
| 216 | + private void updateTables(Map<String, TableMetadata> oldTables, Map<String, TableMetadata> newTables, String tableToRebuild) { | |
| 217 | + Iterator<TableMetadata> it = oldTables.values().iterator(); | |
| 218 | + while (it.hasNext()) { | |
| 219 | + TableMetadata oldTable = it.next(); | |
| 220 | + String tableName = oldTable.getName(); | |
| 221 | + // If we're rebuilding only a single table, we should only consider that one | |
| 222 | + // because newTables will only contain that table. | |
| 223 | + if ((tableToRebuild == null || tableToRebuild.equals(tableName)) && !newTables.containsKey(tableName)) { | |
| 224 | + it.remove(); | |
| 225 | + triggerOnTableRemoved(oldTable); | |
| 159 | 226 | } |
| 160 | 227 | } |
| 228 | + for (TableMetadata newTable : newTables.values()) { | |
| 229 | + TableMetadata oldTable = oldTables.put(newTable.getName(), newTable); | |
| 230 | + if (oldTable == null) { | |
| 231 | + triggerOnTableAdded(newTable); | |
| 232 | + } else if (!oldTable.equals(newTable)) { | |
| 233 | + triggerOnTableChanged(newTable, oldTable); | |
| 234 | + } | |
| 235 | + } | |
| 236 | + } | |
| 237 | + | |
| 238 | + void triggerOnKeyspaceAdded(KeyspaceMetadata keyspace) { | |
| 239 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 240 | + listener.onKeyspaceAdded(keyspace); | |
| 241 | + } | |
| 242 | + } | |
| 243 | + | |
| 244 | + void triggerOnKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous) { | |
| 245 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 246 | + listener.onKeyspaceChanged(current, previous); | |
| 247 | + } | |
| 248 | + } | |
| 249 | + | |
| 250 | + void triggerOnKeyspaceRemoved(KeyspaceMetadata keyspace) { | |
| 251 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 252 | + listener.onKeyspaceRemoved(keyspace); | |
| 253 | + } | |
| 254 | + } | |
| 255 | + | |
| 256 | + void triggerOnTableAdded(TableMetadata table) { | |
| 257 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 258 | + listener.onTableAdded(table); | |
| 259 | + } | |
| 260 | + } | |
| 261 | + | |
| 262 | + void triggerOnTableChanged(TableMetadata current, TableMetadata previous) { | |
| 263 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 264 | + listener.onTableChanged(current, previous); | |
| 265 | + } | |
| 266 | + } | |
| 267 | + | |
| 268 | + void triggerOnTableRemoved(TableMetadata table) { | |
| 269 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 270 | + listener.onTableRemoved(table); | |
| 271 | + } | |
| 161 | 272 | } |
| 162 | 273 | |
| 163 | 274 | synchronized void rebuildTokenMap(String partitioner, Map<Host, Collection<String>> allTokens) { |
| @@ -386,10 +497,11 @@ | ||
| 386 | 497 | return keyspaces.get(keyspace); |
| 387 | 498 | } |
| 388 | 499 | |
| 389 | - void removeKeyspace(String keyspace) { | |
| 390 | - keyspaces.remove(keyspace); | |
| 500 | + KeyspaceMetadata removeKeyspace(String keyspace) { | |
| 501 | + KeyspaceMetadata removed = keyspaces.remove(keyspace); | |
| 391 | 502 | if (tokenMap != null) |
| 392 | 503 | tokenMap.tokenToHosts.remove(keyspace); |
| 504 | + return removed; | |
| 393 | 505 | } |
| 394 | 506 | |
| 395 | 507 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +37 −0
| @@ -87,6 +87,24 @@ | ||
| 87 | 87 | } |
| 88 | 88 | return replicaMap; |
| 89 | 89 | } |
| 90 | + | |
| 91 | + @Override | |
| 92 | + public boolean equals(Object o) { | |
| 93 | + if (this == o) | |
| 94 | + return true; | |
| 95 | + if (o == null || getClass() != o.getClass()) | |
| 96 | + return false; | |
| 97 | + | |
| 98 | + SimpleStrategy that = (SimpleStrategy)o; | |
| 99 | + | |
| 100 | + return replicationFactor == that.replicationFactor; | |
| 101 | + | |
| 102 | + } | |
| 103 | + | |
| 104 | + @Override | |
| 105 | + public int hashCode() { | |
| 106 | + return replicationFactor; | |
| 107 | + } | |
| 90 | 108 | } |
| 91 | 109 | |
| 92 | 110 | static class NetworkTopologyStrategy extends ReplicationStrategy { |
| @@ -197,5 +215,24 @@ | ||
| 197 | 215 | } |
| 198 | 216 | return result; |
| 199 | 217 | } |
| 218 | + | |
| 219 | + @Override | |
| 220 | + public boolean equals(Object o) { | |
| 221 | + if (this == o) | |
| 222 | + return true; | |
| 223 | + if (o == null || getClass() != o.getClass()) | |
| 224 | + return false; | |
| 225 | + | |
| 226 | + NetworkTopologyStrategy that = (NetworkTopologyStrategy)o; | |
| 227 | + | |
| 228 | + return replicationFactors.equals(that.replicationFactors); | |
| 229 | + | |
| 230 | + } | |
| 231 | + | |
| 232 | + @Override | |
| 233 | + public int hashCode() { | |
| 234 | + return replicationFactors.hashCode(); | |
| 235 | + } | |
| 200 | 236 | } |
| 237 | + | |
| 201 | 238 | } |
added driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java +89 −0
| @@ -0,0 +1,89 @@ | ||
| 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 | +/** | |
| 19 | + * Interface for objects that are interested in tracking schema change events in the cluster. | |
| 20 | + * <p> | |
| 21 | + * An implementation of this interface can be registered against a Cluster | |
| 22 | + * object through the {@link com.datastax.driver.core.Cluster#register(SchemaChangeListener)} method. | |
| 23 | + * <p> | |
| 24 | + * Note that the methods defined by this interface will be executed by internal driver threads, and are | |
| 25 | + * therefore expected to have short execution times. If you need to perform long computations or blocking | |
| 26 | + * calls in response to schema change events, it is strongly recommended to schedule them asynchronously | |
| 27 | + * on a separate thread provided by our application code. | |
| 28 | + */ | |
| 29 | +public interface SchemaChangeListener { | |
| 30 | + | |
| 31 | + /** | |
| 32 | + * Called when a keyspace has been added. | |
| 33 | + * | |
| 34 | + * @param keyspace the keyspace that has been added. | |
| 35 | + */ | |
| 36 | + void onKeyspaceAdded(KeyspaceMetadata keyspace); | |
| 37 | + | |
| 38 | + /** | |
| 39 | + * Called when a keyspace has been removed. | |
| 40 | + * | |
| 41 | + * @param keyspace the keyspace that has been removed. | |
| 42 | + */ | |
| 43 | + void onKeyspaceRemoved(KeyspaceMetadata keyspace); | |
| 44 | + | |
| 45 | + /** | |
| 46 | + * Called when a keyspace has changed. | |
| 47 | + * | |
| 48 | + * @param current the keyspace that has changed, in its current form (after the change). | |
| 49 | + * @param previous the keyspace that has changed, in its previous form (before the change). | |
| 50 | + */ | |
| 51 | + void onKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous); | |
| 52 | + | |
| 53 | + /** | |
| 54 | + * Called when a table has been added. | |
| 55 | + * | |
| 56 | + * @param table the table that has been newly added. | |
| 57 | + */ | |
| 58 | + void onTableAdded(TableMetadata table); | |
| 59 | + | |
| 60 | + /** | |
| 61 | + * Called when a table has been removed. | |
| 62 | + * | |
| 63 | + * @param table the table that has been removed. | |
| 64 | + */ | |
| 65 | + void onTableRemoved(TableMetadata table); | |
| 66 | + | |
| 67 | + /** | |
| 68 | + * Called when a table has changed. | |
| 69 | + * | |
| 70 | + * @param current the table that has changed, in its current form (after the change). | |
| 71 | + * @param previous the table that has changed, in its previous form (before the change). | |
| 72 | + */ | |
| 73 | + void onTableChanged(TableMetadata current, TableMetadata previous); | |
| 74 | + | |
| 75 | + /** | |
| 76 | + * Gets invoked when the listener is registered with a cluster. | |
| 77 | + * | |
| 78 | + * @param cluster the cluster that this tracker is registered with. | |
| 79 | + */ | |
| 80 | + void onRegister(Cluster cluster); | |
| 81 | + | |
| 82 | + /** | |
| 83 | + * Gets invoked when the listener is unregistered from a cluster, or at cluster shutdown if | |
| 84 | + * the tracker was not unregistered. | |
| 85 | + * | |
| 86 | + * @param cluster the cluster that this tracker was registered with. | |
| 87 | + */ | |
| 88 | + void onUnregister(Cluster cluster); | |
| 89 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +103 −1
| @@ -179,7 +179,6 @@ | ||
| 179 | 179 | for (ColumnMetadata c : otherColumns) |
| 180 | 180 | columns.put(c.getName(), c); |
| 181 | 181 | |
| 182 | - ksm.add(tm); | |
| 183 | 182 | return tm; |
| 184 | 183 | } |
| 185 | 184 | |
| @@ -371,6 +370,43 @@ | ||
| 371 | 370 | return asCQLQuery(false); |
| 372 | 371 | } |
| 373 | 372 | |
| 373 | + @Override | |
| 374 | + public boolean equals(Object o) { | |
| 375 | + if (this == o) | |
| 376 | + return true; | |
| 377 | + if (o == null || getClass() != o.getClass()) | |
| 378 | + return false; | |
| 379 | + | |
| 380 | + TableMetadata that = (TableMetadata)o; | |
| 381 | + | |
| 382 | + if (!name.equals(that.name)) | |
| 383 | + return false; | |
| 384 | + if (!partitionKey.equals(that.partitionKey)) | |
| 385 | + return false; | |
| 386 | + if (!clusteringColumns.equals(that.clusteringColumns)) | |
| 387 | + return false; | |
| 388 | + if (!columns.equals(that.columns)) | |
| 389 | + return false; | |
| 390 | + if (!options.equals(that.options)) | |
| 391 | + return false; | |
| 392 | + if (!clusteringOrder.equals(that.clusteringOrder)) | |
| 393 | + return false; | |
| 394 | + return cassandraVersion.equals(that.cassandraVersion); | |
| 395 | + | |
| 396 | + } | |
| 397 | + | |
| 398 | + @Override | |
| 399 | + public int hashCode() { | |
| 400 | + int result = name.hashCode(); | |
| 401 | + result = 31 * result + partitionKey.hashCode(); | |
| 402 | + result = 31 * result + clusteringColumns.hashCode(); | |
| 403 | + result = 31 * result + columns.hashCode(); | |
| 404 | + result = 31 * result + options.hashCode(); | |
| 405 | + result = 31 * result + clusteringOrder.hashCode(); | |
| 406 | + result = 31 * result + cassandraVersion.hashCode(); | |
| 407 | + return result; | |
| 408 | + } | |
| 409 | + | |
| 374 | 410 | private String asCQLQuery(boolean formatted) { |
| 375 | 411 | StringBuilder sb = new StringBuilder(); |
| 376 | 412 | |
| @@ -695,5 +731,71 @@ | ||
| 695 | 731 | public Map<String, String> getCompression() { |
| 696 | 732 | return new HashMap<String, String>(compression); |
| 697 | 733 | } |
| 734 | + | |
| 735 | + @Override | |
| 736 | + public boolean equals(Object o) { | |
| 737 | + if (this == o) | |
| 738 | + return true; | |
| 739 | + if (o == null || getClass() != o.getClass()) | |
| 740 | + return false; | |
| 741 | + | |
| 742 | + Options options = (Options)o; | |
| 743 | + | |
| 744 | + if (isCompactStorage != options.isCompactStorage) | |
| 745 | + return false; | |
| 746 | + if (Double.compare(options.readRepair, readRepair) != 0) | |
| 747 | + return false; | |
| 748 | + if (Double.compare(options.localReadRepair, localReadRepair) != 0) | |
| 749 | + return false; | |
| 750 | + if (replicateOnWrite != options.replicateOnWrite) | |
| 751 | + return false; | |
| 752 | + if (gcGrace != options.gcGrace) | |
| 753 | + return false; | |
| 754 | + if (Double.compare(options.bfFpChance, bfFpChance) != 0) | |
| 755 | + return false; | |
| 756 | + if (populateCacheOnFlush != options.populateCacheOnFlush) | |
| 757 | + return false; | |
| 758 | + if (memtableFlushPeriodMs != options.memtableFlushPeriodMs) | |
| 759 | + return false; | |
| 760 | + if (defaultTTL != options.defaultTTL) | |
| 761 | + return false; | |
| 762 | + if (indexInterval != options.indexInterval) | |
| 763 | + return false; | |
| 764 | + if (comment != null ? !comment.equals(options.comment) : options.comment != null) | |
| 765 | + return false; | |
| 766 | + if (caching != null ? !caching.equals(options.caching) : options.caching != null) | |
| 767 | + return false; | |
| 768 | + if (speculativeRetry != null ? !speculativeRetry.equals(options.speculativeRetry) : options.speculativeRetry != null) | |
| 769 | + return false; | |
| 770 | + if (compaction != null ? !compaction.equals(options.compaction) : options.compaction != null) | |
| 771 | + return false; | |
| 772 | + return !(compression != null ? !compression.equals(options.compression) : options.compression != null); | |
| 773 | + | |
| 774 | + } | |
| 775 | + | |
| 776 | + @Override | |
| 777 | + public int hashCode() { | |
| 778 | + int result; | |
| 779 | + long temp; | |
| 780 | + result = (isCompactStorage ? 1 : 0); | |
| 781 | + result = 31 * result + (comment != null ? comment.hashCode() : 0); | |
| 782 | + temp = Double.doubleToLongBits(readRepair); | |
| 783 | + result = 31 * result + (int)(temp ^ (temp >>> 32)); | |
| 784 | + temp = Double.doubleToLongBits(localReadRepair); | |
| 785 | + result = 31 * result + (int)(temp ^ (temp >>> 32)); | |
| 786 | + result = 31 * result + (replicateOnWrite ? 1 : 0); | |
| 787 | + result = 31 * result + gcGrace; | |
| 788 | + temp = Double.doubleToLongBits(bfFpChance); | |
| 789 | + result = 31 * result + (int)(temp ^ (temp >>> 32)); | |
| 790 | + result = 31 * result + (caching != null ? caching.hashCode() : 0); | |
| 791 | + result = 31 * result + (populateCacheOnFlush ? 1 : 0); | |
| 792 | + result = 31 * result + memtableFlushPeriodMs; | |
| 793 | + result = 31 * result + defaultTTL; | |
| 794 | + result = 31 * result + (speculativeRetry != null ? speculativeRetry.hashCode() : 0); | |
| 795 | + result = 31 * result + indexInterval; | |
| 796 | + result = 31 * result + (compaction != null ? compaction.hashCode() : 0); | |
| 797 | + result = 31 * result + (compression != null ? compression.hashCode() : 0); | |
| 798 | + return result; | |
| 799 | + } | |
| 698 | 800 | } |
| 699 | 801 | } |
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +8 −0
| @@ -30,4 +30,12 @@ | ||
| 30 | 30 | public static TokenRangeAssert assertThat(TokenRange range) { |
| 31 | 31 | return new TokenRangeAssert(range); |
| 32 | 32 | } |
| 33 | + | |
| 34 | + public static KeyspaceMetadataAssert assertThat(KeyspaceMetadata metadata) { | |
| 35 | + return new KeyspaceMetadataAssert(metadata); | |
| 36 | + } | |
| 37 | + | |
| 38 | + public static TableMetadataAssert assertThat(TableMetadata metadata) { | |
| 39 | + return new TableMetadataAssert(metadata); | |
| 40 | + } | |
| 33 | 41 | } |
added driver-core/src/test/java/com/datastax/driver/core/KeyspaceMetadataAssert.java +41 −0
| @@ -0,0 +1,41 @@ | ||
| 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 org.assertj.core.api.AbstractAssert; | |
| 19 | + | |
| 20 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 21 | + | |
| 22 | +public class KeyspaceMetadataAssert extends AbstractAssert<KeyspaceMetadataAssert, KeyspaceMetadata> { | |
| 23 | + protected KeyspaceMetadataAssert(KeyspaceMetadata actual) { | |
| 24 | + super(actual, KeyspaceMetadataAssert.class); | |
| 25 | + } | |
| 26 | + | |
| 27 | + public KeyspaceMetadataAssert hasName(String name) { | |
| 28 | + assertThat(actual.getName()).isEqualTo(name); | |
| 29 | + return this; | |
| 30 | + } | |
| 31 | + | |
| 32 | + public KeyspaceMetadataAssert isDurableWrites() { | |
| 33 | + assertThat(actual.isDurableWrites()).isTrue(); | |
| 34 | + return this; | |
| 35 | + } | |
| 36 | + | |
| 37 | + public KeyspaceMetadataAssert isNotDurableWrites() { | |
| 38 | + assertThat(actual.isDurableWrites()).isFalse(); | |
| 39 | + return this; | |
| 40 | + } | |
| 41 | +} |
added driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java +217 −0
| @@ -0,0 +1,217 @@ | ||
| 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.util.Collections; | |
| 19 | +import java.util.Iterator; | |
| 20 | +import java.util.concurrent.TimeUnit; | |
| 21 | + | |
| 22 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 23 | +import org.mockito.ArgumentCaptor; | |
| 24 | +import org.testng.annotations.Test; | |
| 25 | + | |
| 26 | +import static org.mockito.Matchers.any; | |
| 27 | +import static org.mockito.Mockito.mock; | |
| 28 | +import static org.mockito.Mockito.reset; | |
| 29 | +import static org.mockito.Mockito.timeout; | |
| 30 | +import static org.mockito.Mockito.verify; | |
| 31 | +import static org.testng.Assert.fail; | |
| 32 | + | |
| 33 | +import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy; | |
| 34 | +import com.datastax.driver.core.policies.LoadBalancingPolicy; | |
| 35 | +import com.datastax.driver.core.policies.Policies; | |
| 36 | + | |
| 37 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 38 | +import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; | |
| 39 | + | |
| 40 | +public class SchemaChangesCCTest { | |
| 41 | + | |
| 42 | + private static final int NOTIF_TIMEOUT_MS = 5000; | |
| 43 | + | |
| 44 | + /** | |
| 45 | + * Validates that any schema change events made while the control connection is down are | |
| 46 | + * propagated when the control connection is re-established. | |
| 47 | + * <p> | |
| 48 | + * | |
| 49 | + * Note that on control connection recovery not all schema changes are propagated. For example, | |
| 50 | + * if a table was altered and then dropped only a drop event would be received as that is all | |
| 51 | + * that can be discerned. | |
| 52 | + * | |
| 53 | + * @test_category control_connection, schema | |
| 54 | + * @expected_result keyspace and table add, drop, and remove events are propagated on control connection reconnect. | |
| 55 | + * @jira_ticket JAVA-151 | |
| 56 | + * @since 2.0.11, 2.1.8, 2.2.1 | |
| 57 | + */ | |
| 58 | + @Test(groups="long") | |
| 59 | + public void should_receive_changes_made_while_control_connection_is_down_on_reconnect() throws Exception { | |
| 60 | + ToggleablePolicy lbPolicy = new ToggleablePolicy(Policies.defaultLoadBalancingPolicy()); | |
| 61 | + | |
| 62 | + CCMBridge ccm = CCMBridge.builder("SchemaChangesCCTest").withNodes(2).build(); | |
| 63 | + Cluster.Builder builder = Cluster.builder() | |
| 64 | + .withLoadBalancingPolicy(lbPolicy); | |
| 65 | + Cluster cluster = builder.addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 66 | + // Put cluster2 control connection on node 2 so it doesn't go down (to prevent noise for debugging). | |
| 67 | + Cluster cluster2 = builder.addContactPoint(CCMBridge.ipOfNode(2)).build(); | |
| 68 | + try { | |
| 69 | + SchemaChangeListener listener = mock(SchemaChangeListener.class); | |
| 70 | + | |
| 71 | + cluster.init(); | |
| 72 | + cluster.register(listener); | |
| 73 | + | |
| 74 | + Session session2 = cluster2.connect(); | |
| 75 | + // Create two keyspaces to experiment with. | |
| 76 | + session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks1", 1)); | |
| 77 | + session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks2", 1)); | |
| 78 | + session2.execute("create table ks1.tbl1 (k text primary key, v text)"); | |
| 79 | + session2.execute("create table ks1.tbl2 (k text primary key, v text)"); | |
| 80 | + | |
| 81 | + // Wait for both create events to be received. | |
| 82 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onKeyspaceAdded(any(KeyspaceMetadata.class)); | |
| 83 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onTableAdded(any(TableMetadata.class)); | |
| 84 | + | |
| 85 | + | |
| 86 | + KeyspaceMetadata prealteredKeyspace = cluster.getMetadata().getKeyspace("ks1"); | |
| 87 | + KeyspaceMetadata predroppedKeyspace = cluster.getMetadata().getKeyspace("ks2"); | |
| 88 | + TableMetadata prealteredTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl1"); | |
| 89 | + TableMetadata predroppedTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl2"); | |
| 90 | + | |
| 91 | + // Enable returning empty query plan for default statements. This will | |
| 92 | + // prevent the control connection from being able to reconnect. | |
| 93 | + lbPolicy.returnEmptyQueryPlan = true; | |
| 94 | + | |
| 95 | + // Stop node 1, which hosts the control connection. | |
| 96 | + ccm.stop(1); | |
| 97 | + assertThat(cluster).host(1).goesDownWithin(20, TimeUnit.SECONDS); | |
| 98 | + | |
| 99 | + // Ensure control connection is down. | |
| 100 | + assertThat(cluster.manager.controlConnection.isOpen()).isFalse(); | |
| 101 | + | |
| 102 | + // Perform some schema changes that we'll validate when the control connection comes back. | |
| 103 | + session2.execute("drop keyspace ks2"); | |
| 104 | + session2.execute("drop table ks1.tbl2"); | |
| 105 | + session2.execute("alter keyspace ks1 with durable_writes=false"); | |
| 106 | + session2.execute("alter table ks1.tbl1 alter v type blob"); | |
| 107 | + session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks3", 1)); | |
| 108 | + session2.execute("create table ks1.tbl3 (k text primary key, v text)"); | |
| 109 | + | |
| 110 | + // Reset the mock to clear invocations. (sanity check to ensure all events happen after CC comes back up) | |
| 111 | + reset(listener); | |
| 112 | + | |
| 113 | + // Switch the flag so the control connection may now be established. | |
| 114 | + lbPolicy.returnEmptyQueryPlan = false; | |
| 115 | + | |
| 116 | + // Poll on the control connection and wait for it to be reestablished. | |
| 117 | + long maxControlConnectionWait = 60000; | |
| 118 | + long startTime = System.currentTimeMillis(); | |
| 119 | + while(!cluster.manager.controlConnection.isOpen() && System.currentTimeMillis() - startTime < maxControlConnectionWait) { | |
| 120 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 121 | + } | |
| 122 | + | |
| 123 | + assertThat(cluster.manager.controlConnection.isOpen()) | |
| 124 | + .as("Control connection was not opened after %dms.", maxControlConnectionWait) | |
| 125 | + .isTrue(); | |
| 126 | + | |
| 127 | + // Ensure the drop keyspace event shows up. | |
| 128 | + ArgumentCaptor<KeyspaceMetadata> removedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 129 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(removedKeyspace.capture()); | |
| 130 | + assertThat(removedKeyspace.getValue()) | |
| 131 | + .hasName("ks2") | |
| 132 | + .isEqualTo(predroppedKeyspace); | |
| 133 | + | |
| 134 | + // Ensure the drop table event shows up. | |
| 135 | + ArgumentCaptor<TableMetadata> droppedTable = ArgumentCaptor.forClass(TableMetadata.class); | |
| 136 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(droppedTable.capture()); | |
| 137 | + | |
| 138 | + assertThat(droppedTable.getValue()) | |
| 139 | + .isInKeyspace("ks1") | |
| 140 | + .hasName("tbl2") | |
| 141 | + .isEqualTo(predroppedTable); | |
| 142 | + | |
| 143 | + // Ensure that the alter keyspace event shows up. | |
| 144 | + ArgumentCaptor<KeyspaceMetadata> alteredKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 145 | + ArgumentCaptor<KeyspaceMetadata> originalKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 146 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(alteredKeyspace.capture(), originalKeyspace.capture()); | |
| 147 | + | |
| 148 | + // Previous metadata should match the metadata observed before disconnect. | |
| 149 | + assertThat(originalKeyspace.getValue()) | |
| 150 | + .hasName("ks1") | |
| 151 | + .isDurableWrites() | |
| 152 | + .isEqualTo(prealteredKeyspace); | |
| 153 | + | |
| 154 | + // New metadata should reflect that the durable writes attribute changed. | |
| 155 | + assertThat(alteredKeyspace.getValue()) | |
| 156 | + .hasName("ks1") | |
| 157 | + .isNotDurableWrites(); | |
| 158 | + | |
| 159 | + // Ensure the alter table event shows up. | |
| 160 | + ArgumentCaptor<TableMetadata> alteredTable = ArgumentCaptor.forClass(TableMetadata.class); | |
| 161 | + ArgumentCaptor<TableMetadata> originalTable = ArgumentCaptor.forClass(TableMetadata.class); | |
| 162 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(alteredTable.capture(), originalTable.capture()); | |
| 163 | + | |
| 164 | + // Previous metadata should match the metadata observed before disconnect. | |
| 165 | + assertThat(originalTable.getValue()) | |
| 166 | + .isInKeyspace("ks1") | |
| 167 | + .hasName("tbl1") | |
| 168 | + .hasColumn("v", DataType.text()) | |
| 169 | + .isEqualTo(prealteredTable); | |
| 170 | + | |
| 171 | + // New metadata should reflect that the column type changed. | |
| 172 | + assertThat(alteredTable.getValue()) | |
| 173 | + .isInKeyspace("ks1") | |
| 174 | + .hasName("tbl1") | |
| 175 | + .hasColumn("v", DataType.blob()); | |
| 176 | + | |
| 177 | + // Ensure the add keyspace event shows up. | |
| 178 | + ArgumentCaptor<KeyspaceMetadata> addedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 179 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(addedKeyspace.capture()); | |
| 180 | + | |
| 181 | + assertThat(addedKeyspace.getValue()).hasName("ks3"); | |
| 182 | + | |
| 183 | + // Ensure the add table event shows up. | |
| 184 | + ArgumentCaptor<TableMetadata> addedTable = ArgumentCaptor.forClass(TableMetadata.class); | |
| 185 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(addedTable.capture()); | |
| 186 | + | |
| 187 | + assertThat(addedTable.getValue()) | |
| 188 | + .isInKeyspace("ks1") | |
| 189 | + .hasName("tbl3"); | |
| 190 | + } finally { | |
| 191 | + cluster.close(); | |
| 192 | + ccm.remove(); | |
| 193 | + } | |
| 194 | + } | |
| 195 | + | |
| 196 | + /** | |
| 197 | + * A load balancing policy that can be "disabled" by having its query plan return no hosts when | |
| 198 | + * given the 'DEFAULT' statement. This statement is used for retrieving query plan | |
| 199 | + * and for finding what hosts to use for control connection. | |
| 200 | + */ | |
| 201 | + public static class ToggleablePolicy extends DelegatingLoadBalancingPolicy { | |
| 202 | + | |
| 203 | + volatile boolean returnEmptyQueryPlan; | |
| 204 | + | |
| 205 | + public ToggleablePolicy(LoadBalancingPolicy delegate) { | |
| 206 | + super(delegate); | |
| 207 | + } | |
| 208 | + | |
| 209 | + @Override | |
| 210 | + public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 211 | + if (returnEmptyQueryPlan && statement == Statement.DEFAULT) | |
| 212 | + return Collections.<Host>emptyList().iterator(); | |
| 213 | + else | |
| 214 | + return super.newQueryPlan(loggedKeyspace, statement); | |
| 215 | + } | |
| 216 | + } | |
| 217 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +168 −68
| @@ -15,52 +15,81 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.util.Collection; | |
| 19 | +import java.util.Collections; | |
| 18 | 20 | import java.util.List; |
| 19 | 21 | |
| 20 | 22 | import com.google.common.collect.Lists; |
| 21 | 23 | import com.google.common.util.concurrent.Futures; |
| 22 | 24 | import com.google.common.util.concurrent.ListenableFuture; |
| 25 | +import org.mockito.ArgumentCaptor; | |
| 23 | 26 | import org.testng.annotations.*; |
| 24 | 27 | |
| 28 | +import static org.mockito.Mockito.mock; | |
| 29 | +import static org.mockito.Mockito.reset; | |
| 30 | +import static org.mockito.Mockito.timeout; | |
| 31 | +import static org.mockito.Mockito.verify; | |
| 32 | + | |
| 25 | 33 | import com.datastax.driver.core.utils.Bytes; |
| 26 | 34 | |
| 27 | 35 | import static com.datastax.driver.core.Assertions.assertThat; |
| 36 | +import static com.datastax.driver.core.Metadata.handleId; | |
| 37 | + | |
| 38 | +public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 39 | + | |
| 40 | + private static final String CREATE_KEYSPACE = "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }"; | |
| 41 | + private static final String ALTER_KEYSPACE = "ALTER KEYSPACE %s WITH durable_writes = false"; | |
| 42 | + private static final String DROP_KEYSPACE = "DROP KEYSPACE %s"; | |
| 43 | + | |
| 44 | + private static final String CREATE_TABLE = "CREATE TABLE %s.table1(i int primary key)"; | |
| 45 | + private static final String ALTER_TABLE = "ALTER TABLE %s.table1 ADD j int"; | |
| 46 | + private static final String DROP_TABLE = "DROP TABLE %s.table1"; | |
| 28 | 47 | |
| 29 | -public class SchemaChangesTest { | |
| 30 | - private static final String CREATE_KEYSPACE = | |
| 31 | - "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }"; | |
| 48 | + /** The maximum time that the test will wait to check that listeners have been notified */ | |
| 49 | + private static final int NOTIF_TIMEOUT_MS = 5000; | |
| 32 | 50 | |
| 33 | - CCMBridge ccm; | |
| 34 | - Cluster cluster; | |
| 51 | + Cluster cluster1; | |
| 35 | 52 | Cluster cluster2; // a second cluster to check that other clients also get notified |
| 36 | 53 | |
| 37 | 54 | // The metadatas of the two clusters (we'll test that they're kept in sync) |
| 38 | 55 | List<Metadata> metadatas; |
| 39 | 56 | |
| 40 | - Session session; | |
| 57 | + Session session1; | |
| 58 | + | |
| 59 | + SchemaChangeListener listener1; | |
| 60 | + SchemaChangeListener listener2; | |
| 61 | + | |
| 62 | + List<SchemaChangeListener> listeners; | |
| 63 | + | |
| 64 | + @Override | |
| 65 | + protected Collection<String> getTableDefinitions() { | |
| 66 | + return Lists.newArrayList(); | |
| 67 | + } | |
| 41 | 68 | |
| 42 | 69 | @BeforeClass(groups = "short") |
| 43 | - public void setup() { | |
| 44 | - ccm = CCMBridge.builder("schemaChangesTest").withNodes(1).build(); | |
| 70 | + public void setup() throws InterruptedException { | |
| 71 | + Cluster.Builder builder = configure(Cluster.builder()).addContactPointsWithPorts(Collections.singletonList(hostAddress)); | |
| 72 | + cluster1 = builder.build(); | |
| 73 | + cluster2 = builder.build(); | |
| 74 | + | |
| 75 | + metadatas = Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata()); | |
| 45 | 76 | |
| 46 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 47 | - cluster2 = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 77 | + session1 = cluster1.connect(); | |
| 48 | 78 | |
| 49 | - metadatas = Lists.newArrayList(cluster.getMetadata(), cluster2.getMetadata()); | |
| 79 | + cluster1.register(listener1 = mock(SchemaChangeListener.class)); | |
| 80 | + cluster1.register(listener2 = mock(SchemaChangeListener.class)); | |
| 81 | + listeners = Lists.newArrayList(listener1, listener2); | |
| 50 | 82 | |
| 51 | - session = cluster.connect(); | |
| 52 | - session.execute(String.format(CREATE_KEYSPACE, "lowercase")); | |
| 53 | - session.execute(String.format(CREATE_KEYSPACE, "\"CaseSensitive\"")); | |
| 83 | + execute(CREATE_KEYSPACE, "lowercase"); | |
| 84 | + execute(CREATE_KEYSPACE, "\"CaseSensitive\""); | |
| 54 | 85 | } |
| 55 | 86 | |
| 56 | 87 | @AfterClass(groups = "short") |
| 57 | 88 | public void teardown() { |
| 58 | - if (cluster != null) | |
| 59 | - cluster.close(); | |
| 89 | + if (cluster1 != null) | |
| 90 | + cluster1.close(); | |
| 60 | 91 | if (cluster2 != null) |
| 61 | 92 | cluster2.close(); |
| 62 | - if (ccm != null) | |
| 63 | - ccm.remove(); | |
| 64 | 93 | } |
| 65 | 94 | |
| 66 | 95 | @DataProvider(name = "existingKeyspaceName") |
| @@ -68,87 +97,158 @@ | ||
| 68 | 97 | return new Object[][]{ { "lowercase" }, { "\"CaseSensitive\"" } }; |
| 69 | 98 | } |
| 70 | 99 | |
| 71 | - @Test(groups = "short", dataProvider = "existingKeyspaceName") | |
| 72 | - public void should_notify_of_table_creation(String keyspace) { | |
| 73 | - session.execute(String.format("CREATE TABLE %s.table1(i int primary key)", keyspace)); | |
| 100 | + @DataProvider(name = "newKeyspaceName") | |
| 101 | + public static Object[][] newKeyspaceName() { | |
| 102 | + return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } }; | |
| 103 | + } | |
| 74 | 104 | |
| 75 | - for (Metadata m : metadatas) | |
| 76 | - assertThat(m.getKeyspace(keyspace).getTable("table1")) | |
| 77 | - .isNotNull(); | |
| 105 | + @BeforeMethod(groups = "short") | |
| 106 | + public void resetListeners() { | |
| 107 | + for (SchemaChangeListener listener : listeners) { | |
| 108 | + reset(listener); | |
| 109 | + } | |
| 78 | 110 | } |
| 79 | 111 | |
| 80 | 112 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 81 | - public void should_notify_of_table_update(String keyspace) { | |
| 82 | - session.execute(String.format("CREATE TABLE %s.table1(i int primary key)", keyspace)); | |
| 83 | - session.execute(String.format("ALTER TABLE %s.table1 ADD j int", keyspace)); | |
| 84 | - | |
| 113 | + public void should_notify_of_table_creation(String keyspace) throws InterruptedException { | |
| 114 | + execute(CREATE_TABLE, keyspace); | |
| 115 | + for (SchemaChangeListener listener : listeners) { | |
| 116 | + ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class); | |
| 117 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture()); | |
| 118 | + assertThat(added.getValue()) | |
| 119 | + .isInKeyspace(handleId(keyspace)) | |
| 120 | + .hasName("table1"); | |
| 121 | + } | |
| 85 | 122 | for (Metadata m : metadatas) |
| 86 | - assertThat(m.getKeyspace(keyspace).getTable("table1").getColumn("j")) | |
| 87 | - .isNotNull(); | |
| 123 | + assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull(); | |
| 88 | 124 | } |
| 89 | 125 | |
| 90 | 126 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 91 | - public void should_notify_of_table_drop(String keyspace) { | |
| 92 | - session.execute(String.format("CREATE TABLE %s.table1(i int primary key)", keyspace)); | |
| 93 | - session.execute(String.format("DROP TABLE %s.table1", keyspace)); | |
| 94 | - | |
| 127 | + public void should_notify_of_table_update(String keyspace) throws InterruptedException { | |
| 128 | + execute(CREATE_TABLE, keyspace); | |
| 95 | 129 | for (Metadata m : metadatas) |
| 96 | - assertThat(m.getKeyspace(keyspace).getTable("table1")) | |
| 97 | - .isNull(); | |
| 130 | + assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j"); | |
| 131 | + ArgumentCaptor<TableMetadata> added = null; | |
| 132 | + for (SchemaChangeListener listener : listeners) { | |
| 133 | + added = ArgumentCaptor.forClass(TableMetadata.class); | |
| 134 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture()); | |
| 135 | + assertThat(added.getValue()) | |
| 136 | + .isInKeyspace(handleId(keyspace)) | |
| 137 | + .hasName("table1"); | |
| 138 | + } | |
| 139 | + execute(ALTER_TABLE, keyspace); | |
| 140 | + for (SchemaChangeListener listener : listeners) { | |
| 141 | + ArgumentCaptor<TableMetadata> current = ArgumentCaptor.forClass(TableMetadata.class); | |
| 142 | + ArgumentCaptor<TableMetadata> previous = ArgumentCaptor.forClass(TableMetadata.class); | |
| 143 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(current.capture(), previous.capture()); | |
| 144 | + assertThat(previous.getValue()) | |
| 145 | + .isEqualTo(added.getValue()) | |
| 146 | + .hasNoColumn("j"); | |
| 147 | + assertThat(current.getValue()) | |
| 148 | + .isInKeyspace(handleId(keyspace)) | |
| 149 | + .hasName("table1") | |
| 150 | + .hasColumn("j"); | |
| 151 | + } | |
| 152 | + for (Metadata m : metadatas) | |
| 153 | + assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j"); | |
| 98 | 154 | } |
| 99 | 155 | |
| 100 | - @DataProvider(name = "newKeyspaceName") | |
| 101 | - public static Object[][] newKeyspaceName() { | |
| 102 | - return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } }; | |
| 156 | + @Test(groups = "short", dataProvider = "existingKeyspaceName") | |
| 157 | + public void should_notify_of_table_drop(String keyspace) throws InterruptedException { | |
| 158 | + execute(CREATE_TABLE, keyspace); | |
| 159 | + for (SchemaChangeListener listener : listeners) { | |
| 160 | + ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class); | |
| 161 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture()); | |
| 162 | + assertThat(added.getValue()) | |
| 163 | + .hasName("table1") | |
| 164 | + .isInKeyspace(handleId(keyspace)); | |
| 165 | + } | |
| 166 | + execute(DROP_TABLE, keyspace); | |
| 167 | + for (Metadata m : metadatas) | |
| 168 | + assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull(); | |
| 169 | + for (SchemaChangeListener listener : listeners) { | |
| 170 | + ArgumentCaptor<TableMetadata> removed = ArgumentCaptor.forClass(TableMetadata.class); | |
| 171 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(removed.capture()); | |
| 172 | + assertThat(removed.getValue()).hasName("table1"); | |
| 173 | + } | |
| 103 | 174 | } |
| 104 | 175 | |
| 105 | 176 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 106 | - public void should_notify_of_keyspace_creation(String keyspace) { | |
| 107 | - session.execute(String.format(CREATE_KEYSPACE, keyspace)); | |
| 108 | - | |
| 177 | + public void should_notify_of_keyspace_creation(String keyspace) throws InterruptedException { | |
| 178 | + execute(CREATE_KEYSPACE, keyspace); | |
| 109 | 179 | for (Metadata m : metadatas) |
| 110 | - assertThat(m.getKeyspace(keyspace)) | |
| 111 | - .isNotNull(); | |
| 180 | + assertThat(m.getKeyspace(keyspace)).isNotNull(); | |
| 181 | + for (SchemaChangeListener listener : listeners) { | |
| 182 | + ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 183 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); | |
| 184 | + assertThat(added.getValue()).hasName(handleId(keyspace)); | |
| 185 | + } | |
| 112 | 186 | } |
| 113 | 187 | |
| 114 | 188 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 115 | - public void should_notify_of_keyspace_update(String keyspace) { | |
| 116 | - session.execute(String.format(CREATE_KEYSPACE, keyspace)); | |
| 189 | + public void should_notify_of_keyspace_update(String keyspace) throws InterruptedException { | |
| 190 | + execute(CREATE_KEYSPACE, keyspace); | |
| 191 | + ArgumentCaptor<KeyspaceMetadata> added = null; | |
| 192 | + for (SchemaChangeListener listener : listeners) { | |
| 193 | + added = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 194 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); | |
| 195 | + assertThat(added.getValue()).hasName(handleId(keyspace)); | |
| 196 | + } | |
| 117 | 197 | for (Metadata m : metadatas) |
| 118 | - assertThat(m.getKeyspace(keyspace).isDurableWrites()) | |
| 119 | - .isTrue(); | |
| 120 | - | |
| 121 | - session.execute(String.format("ALTER KEYSPACE %s WITH durable_writes = false", keyspace)); | |
| 198 | + assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue(); | |
| 199 | + execute(ALTER_KEYSPACE, keyspace); | |
| 200 | + for (SchemaChangeListener listener : listeners) { | |
| 201 | + ArgumentCaptor<KeyspaceMetadata> current = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 202 | + ArgumentCaptor<KeyspaceMetadata> previous = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 203 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(current.capture(), previous.capture()); | |
| 204 | + assertThat(previous.getValue()) | |
| 205 | + .isEqualTo(added.getValue()) | |
| 206 | + .isDurableWrites(); | |
| 207 | + assertThat(current.getValue()) | |
| 208 | + .hasName(handleId(keyspace)) | |
| 209 | + .isNotDurableWrites(); | |
| 210 | + } | |
| 122 | 211 | for (Metadata m : metadatas) |
| 123 | - assertThat(m.getKeyspace(keyspace).isDurableWrites()) | |
| 124 | - .isFalse(); | |
| 212 | + assertThat(m.getKeyspace(keyspace)).isNotDurableWrites(); | |
| 125 | 213 | } |
| 126 | 214 | |
| 127 | 215 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 128 | - public void should_notify_of_keyspace_drop(String keyspace) { | |
| 129 | - session.execute(String.format(CREATE_KEYSPACE, keyspace)); | |
| 216 | + public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException { | |
| 217 | + execute(CREATE_KEYSPACE, keyspace); | |
| 130 | 218 | for (Metadata m : metadatas) |
| 131 | - assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))) | |
| 132 | - .isNotEmpty(); | |
| 133 | - | |
| 134 | - session.execute(String.format("DROP KEYSPACE %s", keyspace)); | |
| 135 | - | |
| 219 | + assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty(); | |
| 220 | + execute(CREATE_TABLE, keyspace); // to test table drop notifications | |
| 221 | + execute(DROP_KEYSPACE, keyspace); | |
| 222 | + for (SchemaChangeListener listener : listeners) { | |
| 223 | + ArgumentCaptor<TableMetadata> table = ArgumentCaptor.forClass(TableMetadata.class); | |
| 224 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(table.capture()); | |
| 225 | + assertThat(table.getValue()) | |
| 226 | + .hasName("table1") | |
| 227 | + .isInKeyspace(handleId(keyspace)); | |
| 228 | + | |
| 229 | + ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 230 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture()); | |
| 231 | + assertThat(ks.getValue()) | |
| 232 | + .hasName(handleId(keyspace)); | |
| 233 | + } | |
| 136 | 234 | for (Metadata m : metadatas) { |
| 137 | - assertThat(m.getKeyspace(keyspace)) | |
| 138 | - .isNull(); | |
| 139 | - assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))) | |
| 140 | - .isEmpty(); | |
| 235 | + assertThat(m.getKeyspace(keyspace)).isNull(); | |
| 236 | + assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty(); | |
| 141 | 237 | } |
| 142 | 238 | } |
| 143 | 239 | |
| 144 | 240 | @AfterMethod(groups = "short") |
| 145 | - public void cleanup() { | |
| 241 | + public void cleanup() throws InterruptedException { | |
| 146 | 242 | ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList( |
| 147 | - session.executeAsync("DROP TABLE lowercase.table1"), | |
| 148 | - session.executeAsync("DROP TABLE \"CaseSensitive\".table1"), | |
| 149 | - session.executeAsync("DROP KEYSPACE lowercase2"), | |
| 150 | - session.executeAsync("DROP KEYSPACE \"CaseSensitive2\"") | |
| 243 | + session1.executeAsync("DROP TABLE lowercase.table1"), | |
| 244 | + session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"), | |
| 245 | + session1.executeAsync("DROP KEYSPACE lowercase2"), | |
| 246 | + session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"") | |
| 151 | 247 | )); |
| 152 | 248 | Futures.getUnchecked(f); |
| 153 | 249 | } |
| 250 | + | |
| 251 | + private void execute(String cql, String keyspace) throws InterruptedException { | |
| 252 | + session1.execute(String.format(cql, keyspace)); | |
| 253 | + } | |
| 154 | 254 | } |
added driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java +53 −0
| @@ -0,0 +1,53 @@ | ||
| 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 org.assertj.core.api.AbstractAssert; | |
| 19 | + | |
| 20 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 21 | + | |
| 22 | +public class TableMetadataAssert extends AbstractAssert<TableMetadataAssert, TableMetadata> { | |
| 23 | + protected TableMetadataAssert(TableMetadata actual) { | |
| 24 | + super(actual, TableMetadataAssert.class); | |
| 25 | + } | |
| 26 | + | |
| 27 | + public TableMetadataAssert hasName(String name) { | |
| 28 | + assertThat(actual.getName()).isEqualTo(name); | |
| 29 | + return this; | |
| 30 | + } | |
| 31 | + | |
| 32 | + public TableMetadataAssert isInKeyspace(String keyspaceName) { | |
| 33 | + assertThat(actual.getKeyspace().getName()).isEqualTo(keyspaceName); | |
| 34 | + return this; | |
| 35 | + } | |
| 36 | + | |
| 37 | + public TableMetadataAssert hasColumn(String columnName) { | |
| 38 | + assertThat(actual.getColumn(columnName)).isNotNull(); | |
| 39 | + return this; | |
| 40 | + } | |
| 41 | + | |
| 42 | + public TableMetadataAssert hasColumn(String columnName, DataType dataType) { | |
| 43 | + ColumnMetadata column = actual.getColumn(columnName); | |
| 44 | + assertThat(column).isNotNull(); | |
| 45 | + assertThat(column.getType()).isEqualTo(dataType); | |
| 46 | + return this; | |
| 47 | + } | |
| 48 | + | |
| 49 | + public TableMetadataAssert hasNoColumn(String columnName) { | |
| 50 | + assertThat(actual.getColumn(columnName)).isNull(); | |
| 51 | + return this; | |
| 52 | + } | |
| 53 | +} |
modified features/metadata/README.md +23 −0
| @@ -27,6 +27,29 @@ | ||
| 27 | 27 | via a push notification. It refreshes the schema directly (there is no |
| 28 | 28 | need to wait for schema agreement since Cassandra has already done it). |
| 29 | 29 | |
| 30 | +#### Subscribing to schema changes | |
| 31 | + | |
| 32 | +Users interested in being notified of schema changes can implement the | |
| 33 | +[SchemaChangeListener][SchemaChangeListener] interface. | |
| 34 | + | |
| 35 | +Every listener must [be registered][registerListener] against a `Cluster` instance: | |
| 36 | + | |
| 37 | +```java | |
| 38 | +Cluster cluster = ... | |
| 39 | +SchemaChangeListener myListener = ... | |
| 40 | +cluster.register(myListener); | |
| 41 | +``` | |
| 42 | + | |
| 43 | +Once registered, the listener will be notified of all schema changes detected by the driver, | |
| 44 | +regardless of where they originate from. | |
| 45 | + | |
| 46 | +Note that it is preferable to register a listener only *after* the cluster is fully initialized, | |
| 47 | +otherwise the listener could be notified with a great deal of "Added" events as | |
| 48 | +the driver builds the schema metadata from scratch for the first time. | |
| 49 | + | |
| 50 | +[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SchemaChangeListener.html | |
| 51 | +[registerListener]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener) | |
| 52 | + | |
| 30 | 53 | #### Schema agreement |
| 31 | 54 | |
| 32 | 55 | Schema changes need to be propagated to all nodes in the cluster. Once |