kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 2e4fff5155ad2e9948583227cbd6414a349d34a4881eb2f73dba60561aab3385 |
|---|---|
| Author | Alexandre Dutra <adutra@users.noreply.github.com> · 2016-01-14 16:03 +01:00 |
| Committer | Alexandre Dutra <adutra@users.noreply.github.com> · 2016-01-14 16:03 +01:00 |
| Parents | 8b203d17759a, 8dda5388dd39 |
128 files changed
modified build.yaml +2 −0
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | ccm.path=$CCM_JAVA_HOME/bin |
| 21 | 21 | failIfNoTests=false |
| 22 | 22 | maven.test.failure.ignore=true |
| 23 | + maven.javadoc.skip=true | |
| 23 | 24 | - type: maven |
| 24 | 25 | version: 3.2.5 |
| 25 | 26 | goals: verify --fail-never -Pisolated |
| @@ -31,6 +32,7 @@ | ||
| 31 | 32 | ccm.path=$CCM_JAVA_HOME/bin |
| 32 | 33 | failIfNoTests=false |
| 33 | 34 | maven.test.failure.ignore=true |
| 35 | + maven.javadoc.skip=true | |
| 34 | 36 | - xunit: |
| 35 | 37 | - "**/target/surefire-reports/TEST-*.xml" |
| 36 | 38 | - "**/target/failsafe-reports/TEST-*.xml" |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +2 −2
| @@ -48,7 +48,8 @@ | ||
| 48 | 48 | */ |
| 49 | 49 | private final AtomicReference<ListenableFuture<?>> currentAttempt; |
| 50 | 50 | |
| 51 | - private final HandlerFuture handlerFuture = new HandlerFuture(); | |
| 51 | + @VisibleForTesting | |
| 52 | + final HandlerFuture handlerFuture = new HandlerFuture(); | |
| 52 | 53 | |
| 53 | 54 | private final long initialDelayMs; |
| 54 | 55 | |
| @@ -131,7 +132,6 @@ | ||
| 131 | 132 | |
| 132 | 133 | if (handlerFuture.isCancelled()) { |
| 133 | 134 | logger.debug("Got cancelled, stopping"); |
| 134 | - currentAttempt.compareAndSet(handlerFuture, null); | |
| 135 | 135 | return; |
| 136 | 136 | } |
| 137 | 137 |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +28 −2
| @@ -937,10 +937,36 @@ | ||
| 937 | 937 | * points. Contrarily to other {@code addContactPoints} methods, this method |
| 938 | 938 | * allow to provide a different port for each contact points. Since Cassandra |
| 939 | 939 | * nodes must always all listen on the same port, this is rarelly what you |
| 940 | - * want and most use should prefer other {@code addContactPoints} methods to | |
| 940 | + * want and most users should prefer other {@code addContactPoints} methods to | |
| 941 | 941 | * this one. However, this can be useful if the Cassandra nodes are behind |
| 942 | 942 | * a router and are not accessed directly. Note that if you are in this |
| 943 | - * situtation (Cassandra nodes are behind a router, not directly accessible), | |
| 943 | + * situation (Cassandra nodes are behind a router, not directly accessible), | |
| 944 | + * you almost surely want to provide a specific {@code AddressTranslater} | |
| 945 | + * (through {@link #withAddressTranslater}) to translate actual Cassandra node | |
| 946 | + * addresses to the addresses the driver should use, otherwise the driver | |
| 947 | + * will not be able to auto-detect new nodes (and will generally not function | |
| 948 | + * optimally). | |
| 949 | + * | |
| 950 | + * @param addresses addresses of the nodes to add as contact point | |
| 951 | + * @return this Builder | |
| 952 | + * @see Builder#addContactPoint | |
| 953 | + */ | |
| 954 | + public Builder addContactPointsWithPorts(InetSocketAddress... addresses) { | |
| 955 | + Collections.addAll(this.addresses, addresses); | |
| 956 | + return this; | |
| 957 | + } | |
| 958 | + | |
| 959 | + /** | |
| 960 | + * Adds contact points. | |
| 961 | + * <p/> | |
| 962 | + * See {@link Builder#addContactPoint} for more details on contact | |
| 963 | + * points. Contrarily to other {@code addContactPoints} methods, this method | |
| 964 | + * allow to provide a different port for each contact points. Since Cassandra | |
| 965 | + * nodes must always all listen on the same port, this is rarelly what you | |
| 966 | + * want and most users should prefer other {@code addContactPoints} methods to | |
| 967 | + * this one. However, this can be useful if the Cassandra nodes are behind | |
| 968 | + * a router and are not accessed directly. Note that if you are in this | |
| 969 | + * situation (Cassandra nodes are behind a router, not directly accessible), | |
| 944 | 970 | * you almost surely want to provide a specific {@code AddressTranslater} |
| 945 | 971 | * (through {@link #withAddressTranslater}) to translate actual Cassandra node |
| 946 | 972 | * addresses to the addresses the driver should use, otherwise the driver |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +1 −0
| @@ -739,6 +739,7 @@ | ||
| 739 | 739 | * Same as open, but associate the created connection to the provided connection pool. |
| 740 | 740 | */ |
| 741 | 741 | public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| 742 | + | |
| 742 | 743 | pool.host.convictionPolicy.signalConnectionsOpening(1); |
| 743 | 744 | Connection connection = new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool); |
| 744 | 745 | try { |
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +3 −1
| @@ -126,8 +126,10 @@ | ||
| 126 | 126 | |
| 127 | 127 | @Override |
| 128 | 128 | boolean canReconnectNow() { |
| 129 | - return nextReconnectionTime == Long.MIN_VALUE || | |
| 129 | + boolean canReconnectNow = nextReconnectionTime == Long.MIN_VALUE || | |
| 130 | 130 | System.nanoTime() >= nextReconnectionTime; |
| 131 | + Host.statesLogger.trace("canReconnectNow={}", canReconnectNow); | |
| 132 | + return canReconnectNow; | |
| 131 | 133 | } |
| 132 | 134 | |
| 133 | 135 | static class Factory implements ConvictionPolicy.Factory { |
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolVersion.java +1 −1
| @@ -28,7 +28,7 @@ | ||
| 28 | 28 | |
| 29 | 29 | V1("1.2.0", 1), |
| 30 | 30 | V2("2.0.0", 2), |
| 31 | - V3("2.1.0", 3),; | |
| 31 | + V3("2.1.0", 3); | |
| 32 | 32 | |
| 33 | 33 | /** |
| 34 | 34 | * The most recent protocol version supported by the driver. |
modified driver-core/src/test/java/com/datastax/driver/core/AbstractPoliciesTest.java +61 −50
| @@ -15,47 +15,55 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import org.testng.annotations.BeforeMethod; | |
| 19 | + | |
| 18 | 20 | import java.net.InetAddress; |
| 19 | 21 | import java.nio.ByteBuffer; |
| 20 | 22 | import java.util.HashMap; |
| 21 | 23 | import java.util.Map; |
| 24 | +import java.util.concurrent.Callable; | |
| 22 | 25 | |
| 23 | 26 | import static com.datastax.driver.core.TestUtils.*; |
| 24 | 27 | import static com.datastax.driver.core.querybuilder.QueryBuilder.batch; |
| 25 | 28 | import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto; |
| 26 | 29 | import static org.testng.Assert.*; |
| 27 | 30 | |
| 28 | -public abstract class AbstractPoliciesTest { | |
| 31 | +public abstract class AbstractPoliciesTest extends CCMTestsSupport { | |
| 32 | + | |
| 29 | 33 | private static final boolean DEBUG = false; |
| 30 | 34 | |
| 31 | 35 | protected Map<InetAddress, Integer> coordinators = new HashMap<InetAddress, Integer>(); |
| 32 | - protected PreparedStatement prepared; | |
| 33 | 36 | |
| 37 | + protected PreparedStatement prepared; | |
| 34 | 38 | |
| 35 | - /** | |
| 36 | - * Create schemas for the policy tests, depending on replication factors/strategies. | |
| 37 | - */ | |
| 38 | - public static void createSchema(Session session) { | |
| 39 | - createSchema(session, 1); | |
| 40 | - } | |
| 41 | - | |
| 42 | - public static void createSchema(Session session, int replicationFactor) { | |
| 43 | - session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, SIMPLE_KEYSPACE, replicationFactor)); | |
| 44 | - session.execute("USE " + SIMPLE_KEYSPACE); | |
| 39 | + protected void createSchema(int replicationFactor) { | |
| 40 | + final String ks = TestUtils.getAvailableKeyspaceName(); | |
| 41 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ks, replicationFactor)); | |
| 42 | + // tests fail randomly here with InvalidQueryException: Keyspace 'xxx' does not exist | |
| 43 | + ConditionChecker.awaitUntil(new Callable<Boolean>() { | |
| 44 | + @Override | |
| 45 | + public Boolean call() { | |
| 46 | + return cluster.getMetadata().getKeyspace(ks) != null; | |
| 47 | + } | |
| 48 | + }, 60000); | |
| 49 | + session.execute("USE " + ks); | |
| 45 | 50 | session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", SIMPLE_TABLE)); |
| 46 | 51 | } |
| 47 | 52 | |
| 48 | - public static void createMultiDCSchema(Session session) { | |
| 49 | - createMultiDCSchema(session, 1, 1); | |
| 50 | - } | |
| 51 | - | |
| 52 | - public static void createMultiDCSchema(Session session, int dc1RF, int dc2RF) { | |
| 53 | - session.execute(String.format(CREATE_KEYSPACE_GENERIC_FORMAT, SIMPLE_KEYSPACE, "NetworkTopologyStrategy", String.format("'dc1' : %d, 'dc2' : %d", dc1RF, dc2RF))); | |
| 54 | - session.execute("USE " + SIMPLE_KEYSPACE); | |
| 53 | + protected void createMultiDCSchema(int dc1RF, int dc2RF) { | |
| 54 | + final String ks = TestUtils.getAvailableKeyspaceName(); | |
| 55 | + session.execute(String.format(CREATE_KEYSPACE_GENERIC_FORMAT, ks, "NetworkTopologyStrategy", String.format("'dc1' : %d, 'dc2' : %d", dc1RF, dc2RF))); | |
| 56 | + // tests fail randomly here with InvalidQueryException: Keyspace 'xxx' does not exist | |
| 57 | + ConditionChecker.awaitUntil(new Callable<Boolean>() { | |
| 58 | + @Override | |
| 59 | + public Boolean call() { | |
| 60 | + return cluster.getMetadata().getKeyspace(ks) != null; | |
| 61 | + } | |
| 62 | + }, 60000); | |
| 63 | + session.execute("USE " + ks); | |
| 55 | 64 | session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, i int)", SIMPLE_TABLE)); |
| 56 | 65 | } |
| 57 | 66 | |
| 58 | - | |
| 59 | 67 | /** |
| 60 | 68 | * Coordinator management/count |
| 61 | 69 | */ |
| @@ -65,6 +73,7 @@ | ||
| 65 | 73 | coordinators.put(coordinator, n == null ? 1 : n + 1); |
| 66 | 74 | } |
| 67 | 75 | |
| 76 | + @BeforeMethod(groups = "long") | |
| 68 | 77 | protected void resetCoordinators() { |
| 69 | 78 | coordinators = new HashMap<InetAddress, Integer>(); |
| 70 | 79 | } |
| @@ -120,12 +129,12 @@ | ||
| 120 | 129 | else { |
| 121 | 130 | |
| 122 | 131 | if (n == queried) { |
| 123 | - if (found == true) | |
| 124 | - throw new AssertionError(String.format("Found 2 nodes with " + n + " queries in " + queriedMapString())); | |
| 132 | + if (found) | |
| 133 | + throw new AssertionError(String.format("Found 2 nodes with %s queries in %s", n, queriedMapString())); | |
| 125 | 134 | found = true; |
| 126 | 135 | } else { |
| 127 | 136 | if (queried != 0) |
| 128 | - throw new AssertionError(String.format("Host " + addr + " should have be queried: " + queriedMapString())); | |
| 137 | + throw new AssertionError(String.format("Host %s should have be queried: %s", addr, queriedMapString())); | |
| 129 | 138 | } |
| 130 | 139 | } |
| 131 | 140 | } |
| @@ -147,72 +156,74 @@ | ||
| 147 | 156 | /** |
| 148 | 157 | * Init methods that handle writes using batch and consistency options. |
| 149 | 158 | */ |
| 150 | - protected void init(CCMBridge.CCMCluster c, int n) { | |
| 151 | - write(c, n, false, ConsistencyLevel.ONE); | |
| 152 | - prepared = c.session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(ConsistencyLevel.ONE); | |
| 159 | + protected void init(int n) { | |
| 160 | + init(n, false, ConsistencyLevel.ONE); | |
| 161 | + } | |
| 162 | + | |
| 163 | + protected void init(int n, boolean batch) { | |
| 164 | + init(n, batch, ConsistencyLevel.ONE); | |
| 153 | 165 | } |
| 154 | 166 | |
| 155 | - protected void init(CCMBridge.CCMCluster c, int n, boolean batch) { | |
| 156 | - write(c, n, batch, ConsistencyLevel.ONE); | |
| 157 | - prepared = c.session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(ConsistencyLevel.ONE); | |
| 167 | + protected void init(int n, ConsistencyLevel cl) { | |
| 168 | + write(n, false, cl); | |
| 158 | 169 | } |
| 159 | 170 | |
| 160 | - protected void init(CCMBridge.CCMCluster c, int n, ConsistencyLevel cl) { | |
| 161 | - write(c, n, false, cl); | |
| 162 | - prepared = c.session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(cl); | |
| 171 | + protected void init(int n, boolean batch, ConsistencyLevel cl) { | |
| 172 | + write(n, batch, cl); | |
| 173 | + prepared = session.prepare("SELECT * FROM " + SIMPLE_TABLE + " WHERE k = ?").setConsistencyLevel(cl); | |
| 163 | 174 | } |
| 164 | 175 | |
| 165 | - protected void write(CCMBridge.CCMCluster c, int n) { | |
| 166 | - write(c, n, false, ConsistencyLevel.ONE); | |
| 176 | + protected void write(int n) { | |
| 177 | + write(n, false, ConsistencyLevel.ONE); | |
| 167 | 178 | } |
| 168 | 179 | |
| 169 | - protected void write(CCMBridge.CCMCluster c, int n, boolean batch) { | |
| 170 | - write(c, n, batch, ConsistencyLevel.ONE); | |
| 180 | + protected void write(int n, boolean batch) { | |
| 181 | + write(n, batch, ConsistencyLevel.ONE); | |
| 171 | 182 | } |
| 172 | 183 | |
| 173 | - protected void write(CCMBridge.CCMCluster c, int n, ConsistencyLevel cl) { | |
| 174 | - write(c, n, false, cl); | |
| 184 | + protected void write(int n, ConsistencyLevel cl) { | |
| 185 | + write(n, false, cl); | |
| 175 | 186 | } |
| 176 | 187 | |
| 177 | - protected void write(CCMBridge.CCMCluster c, int n, boolean batch, ConsistencyLevel cl) { | |
| 188 | + protected void write(int n, boolean batch, ConsistencyLevel cl) { | |
| 178 | 189 | // We don't use insert for our test because the resultSet don't ship the queriedHost |
| 179 | 190 | // Also note that we don't use tracing because this would trigger requests that screw up the test |
| 180 | 191 | for (int i = 0; i < n; ++i) |
| 181 | 192 | if (batch) |
| 182 | 193 | // BUG: WriteType == SIMPLE |
| 183 | - c.session.execute(batch() | |
| 194 | + session.execute(batch() | |
| 184 | 195 | .add(insertInto(SIMPLE_TABLE).values(new String[]{"k", "i"}, new Object[]{0, 0})) |
| 185 | 196 | .setConsistencyLevel(cl)); |
| 186 | 197 | else |
| 187 | - c.session.execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl)); | |
| 198 | + session.execute(new SimpleStatement(String.format("INSERT INTO %s(k, i) VALUES (0, 0)", SIMPLE_TABLE)).setConsistencyLevel(cl)); | |
| 188 | 199 | } |
| 189 | 200 | |
| 190 | 201 | |
| 191 | 202 | /** |
| 192 | 203 | * Query methods that handle reads based on PreparedStatements and/or ConsistencyLevels. |
| 193 | 204 | */ |
| 194 | - protected void query(CCMBridge.CCMCluster c, int n) { | |
| 195 | - query(c, n, false, ConsistencyLevel.ONE); | |
| 205 | + protected void query(int n) { | |
| 206 | + query(n, false, ConsistencyLevel.ONE); | |
| 196 | 207 | } |
| 197 | 208 | |
| 198 | - protected void query(CCMBridge.CCMCluster c, int n, boolean usePrepared) { | |
| 199 | - query(c, n, usePrepared, ConsistencyLevel.ONE); | |
| 209 | + protected void query(int n, boolean usePrepared) { | |
| 210 | + query(n, usePrepared, ConsistencyLevel.ONE); | |
| 200 | 211 | } |
| 201 | 212 | |
| 202 | - protected void query(CCMBridge.CCMCluster c, int n, ConsistencyLevel cl) { | |
| 203 | - query(c, n, false, cl); | |
| 213 | + protected void query(int n, ConsistencyLevel cl) { | |
| 214 | + query(n, false, cl); | |
| 204 | 215 | } |
| 205 | 216 | |
| 206 | - protected void query(CCMBridge.CCMCluster c, int n, boolean usePrepared, ConsistencyLevel cl) { | |
| 217 | + protected void query(int n, boolean usePrepared, ConsistencyLevel cl) { | |
| 207 | 218 | if (usePrepared) { |
| 208 | 219 | BoundStatement bs = prepared.bind(0); |
| 209 | 220 | for (int i = 0; i < n; ++i) |
| 210 | - addCoordinator(c.session.execute(bs)); | |
| 221 | + addCoordinator(session.execute(bs)); | |
| 211 | 222 | } else { |
| 212 | 223 | ByteBuffer routingKey = ByteBuffer.allocate(4); |
| 213 | 224 | routingKey.putInt(0, 0); |
| 214 | 225 | for (int i = 0; i < n; ++i) |
| 215 | - addCoordinator(c.session.execute(new SimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl))); | |
| 226 | + addCoordinator(session.execute(new SimpleStatement(String.format("SELECT * FROM %s WHERE k = 0", SIMPLE_TABLE)).setRoutingKey(routingKey).setConsistencyLevel(cl))); | |
| 216 | 227 | } |
| 217 | 228 | } |
| 218 | 229 | } |
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +13 −12
| @@ -21,7 +21,6 @@ | ||
| 21 | 21 | import com.google.common.util.concurrent.Futures; |
| 22 | 22 | import com.google.common.util.concurrent.ListenableFuture; |
| 23 | 23 | import com.google.common.util.concurrent.SettableFuture; |
| 24 | -import com.google.common.util.concurrent.Uninterruptibles; | |
| 25 | 24 | import org.slf4j.Logger; |
| 26 | 25 | import org.slf4j.LoggerFactory; |
| 27 | 26 | import org.testng.annotations.AfterMethod; |
| @@ -29,10 +28,7 @@ | ||
| 29 | 28 | import org.testng.annotations.Test; |
| 30 | 29 | |
| 31 | 30 | import java.net.InetSocketAddress; |
| 32 | -import java.util.concurrent.CyclicBarrier; | |
| 33 | -import java.util.concurrent.Executors; | |
| 34 | -import java.util.concurrent.ScheduledExecutorService; | |
| 35 | -import java.util.concurrent.TimeUnit; | |
| 31 | +import java.util.concurrent.*; | |
| 36 | 32 | import java.util.concurrent.atomic.AtomicReference; |
| 37 | 33 | |
| 38 | 34 | import static org.assertj.core.api.Assertions.assertThat; |
| @@ -67,7 +63,7 @@ | ||
| 67 | 63 | }; |
| 68 | 64 | } |
| 69 | 65 | |
| 70 | - @AfterMethod(groups = {"unit", "short"}) | |
| 66 | + @AfterMethod(groups = {"unit", "short"}, alwaysRun = true) | |
| 71 | 67 | public void tearDown() { |
| 72 | 68 | if (future.get() != null) |
| 73 | 69 | future.get().cancel(false); |
| @@ -136,7 +132,7 @@ | ||
| 136 | 132 | handler.start(); |
| 137 | 133 | |
| 138 | 134 | // Wait for the initial schedule of a reconnect. |
| 139 | - verify(executor, timeout(1000)).schedule(handler, 0, TimeUnit.MILLISECONDS); | |
| 135 | + verify(executor, timeout(10000)).schedule(handler, 0, TimeUnit.MILLISECONDS); | |
| 140 | 136 | |
| 141 | 137 | // Force a failed reconnect. |
| 142 | 138 | schedule.tick(); |
| @@ -150,10 +146,16 @@ | ||
| 150 | 146 | |
| 151 | 147 | // Ensure reconnect is scheduled (slight timing window after handling failed reconnect |
| 152 | 148 | // and scheduling next reconnect). |
| 153 | - verify(executor, timeout(1000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS); | |
| 149 | + verify(executor, timeout(10000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS); | |
| 150 | + | |
| 151 | + // Wait until nextTry is assigned after schedule completes. | |
| 152 | + ConditionChecker.awaitUntil(new Callable<Boolean>() { | |
| 153 | + @Override | |
| 154 | + public Boolean call() throws Exception { | |
| 155 | + return handler.handlerFuture.nextTry != null; | |
| 156 | + } | |
| 157 | + }, 10000); | |
| 154 | 158 | |
| 155 | - // Add a short delay to account for nextTry being assigned after schedule completes. | |
| 156 | - Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS); | |
| 157 | 159 | future.get().cancel(false); |
| 158 | 160 | |
| 159 | 161 | // Should immediately return as the future was cancelled while the task was scheduled. |
| @@ -165,6 +167,7 @@ | ||
| 165 | 167 | |
| 166 | 168 | // The future will be marked cancelled and thus not executed. |
| 167 | 169 | ListenableFuture<?> currentAttempt = future.get(); |
| 170 | + | |
| 168 | 171 | assertThat(currentAttempt).isInstanceOf(HandlerFuture.class); |
| 169 | 172 | HandlerFuture handlerFuture = (HandlerFuture) currentAttempt; |
| 170 | 173 | assertThat(handlerFuture.isCancelled()); |
| @@ -327,8 +330,6 @@ | ||
| 327 | 330 | SUCCEED, THROW_EXCEPTION |
| 328 | 331 | } |
| 329 | 332 | |
| 330 | - ; | |
| 331 | - | |
| 332 | 333 | private final CyclicBarrier barrier = new CyclicBarrier(2); |
| 333 | 334 | |
| 334 | 335 | volatile ReconnectBehavior nextReconnect; |
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +2 −2
| @@ -30,7 +30,7 @@ | ||
| 30 | 30 | import static org.testng.Assert.assertEquals; |
| 31 | 31 | import static org.testng.Assert.assertTrue; |
| 32 | 32 | |
| 33 | -public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 33 | +public class AsyncQueryTest extends CCMTestsSupport { | |
| 34 | 34 | |
| 35 | 35 | @DataProvider(name = "keyspace") |
| 36 | 36 | public static Object[][] keyspace() { |
| @@ -38,7 +38,7 @@ | ||
| 38 | 38 | } |
| 39 | 39 | |
| 40 | 40 | @Override |
| 41 | - protected Collection<String> getTableDefinitions() { | |
| 41 | + public Collection<String> createTestFixtures() { | |
| 42 | 42 | List<String> definitions = Lists.newArrayList(); |
| 43 | 43 | |
| 44 | 44 | for (Object[] objects : keyspace()) { |
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +32 −58
| @@ -16,84 +16,58 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 19 | -import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 20 | -import org.slf4j.Logger; | |
| 21 | -import org.slf4j.LoggerFactory; | |
| 22 | -import org.testng.annotations.AfterClass; | |
| 23 | -import org.testng.annotations.BeforeClass; | |
| 19 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 20 | +import org.testng.annotations.BeforeMethod; | |
| 24 | 21 | import org.testng.annotations.Test; |
| 25 | 22 | |
| 26 | 23 | import java.util.concurrent.TimeUnit; |
| 27 | 24 | |
| 25 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 26 | + | |
| 28 | 27 | /** |
| 29 | 28 | * Tests for authenticated cluster access |
| 30 | 29 | */ |
| 31 | -public class AuthenticationTest { | |
| 32 | - | |
| 33 | - private static final Logger logger = LoggerFactory.getLogger(AuthenticationTest.class); | |
| 34 | - | |
| 35 | - private CCMBridge ccm; | |
| 36 | - | |
| 37 | - /** | |
| 38 | - * creates a cluster and turns on password authentication before starting it. | |
| 39 | - */ | |
| 40 | - @BeforeClass(groups = "short") | |
| 41 | - public void setupClusterWithAuthentication() throws InterruptedException { | |
| 42 | - ccm = CCMBridge.builder("test") | |
| 43 | - .withCassandraConfiguration("authenticator", "PasswordAuthenticator") | |
| 44 | - .notStarted() | |
| 45 | - .build(); | |
| 46 | - ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0"); | |
| 47 | - | |
| 48 | - // Even though we've override the default user setup delay, still wait | |
| 49 | - // one second to make sure we don't race | |
| 50 | - TimeUnit.SECONDS.sleep(1); | |
| 51 | - } | |
| 52 | - | |
| 53 | - @AfterClass(groups = "short") | |
| 54 | - public void shutdownCluster() { | |
| 55 | - if (ccm != null) | |
| 56 | - ccm.stop(); | |
| 30 | +@CreateCCM(PER_METHOD) | |
| 31 | +@CCMConfig( | |
| 32 | + config = "authenticator:PasswordAuthenticator", | |
| 33 | + jvmArgs = "-Dcassandra.superuser_setup_delay_ms=0", | |
| 34 | + createCluster = false) | |
| 35 | +public class AuthenticationTest extends CCMTestsSupport { | |
| 36 | + | |
| 37 | + | |
| 38 | + @BeforeMethod(groups = "short") | |
| 39 | + public void sleepIf12() { | |
| 40 | + // For C* 1.2, sleep before attempting to connect as there is a small delay between | |
| 41 | + // user being created. | |
| 42 | + if (ccm.getVersion().getMajor() < 2) { | |
| 43 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 44 | + } | |
| 57 | 45 | } |
| 58 | 46 | |
| 59 | 47 | @Test(groups = "short") |
| 60 | 48 | public void should_connect_with_credentials() throws InterruptedException { |
| 61 | - Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 49 | + Cluster cluster = register(Cluster.builder() | |
| 50 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 62 | 51 | .withCredentials("cassandra", "cassandra") |
| 63 | - .build(); | |
| 64 | - try { | |
| 65 | - cluster.connect(); | |
| 66 | - } catch (NoHostAvailableException e) { | |
| 67 | - logger.error(e.getCustomMessage(1, true, true)); | |
| 68 | - } finally { | |
| 69 | - cluster.close(); | |
| 70 | - } | |
| 52 | + .build()); | |
| 53 | + cluster.connect(); | |
| 71 | 54 | } |
| 72 | 55 | |
| 73 | 56 | @Test(groups = "short", expectedExceptions = AuthenticationException.class) |
| 74 | 57 | public void should_fail_to_connect_with_wrong_credentials() throws InterruptedException { |
| 75 | - Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 58 | + Cluster cluster = register(Cluster.builder() | |
| 59 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 76 | 60 | .withCredentials("bogus", "bogus") |
| 77 | - .build(); | |
| 78 | - try { | |
| 79 | - cluster.connect(); | |
| 80 | - } catch (NoHostAvailableException e) { | |
| 81 | - logger.error(e.getCustomMessage(1, true, true)); | |
| 82 | - } finally { | |
| 83 | - cluster.close(); | |
| 84 | - } | |
| 61 | + .build()); | |
| 62 | + cluster.connect(); | |
| 85 | 63 | } |
| 86 | 64 | |
| 87 | 65 | @Test(groups = "short", expectedExceptions = AuthenticationException.class) |
| 88 | 66 | public void should_fail_to_connect_without_credentials() throws InterruptedException { |
| 89 | - Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 90 | - .build(); | |
| 91 | - try { | |
| 92 | - cluster.connect(); | |
| 93 | - } catch (NoHostAvailableException e) { | |
| 94 | - logger.error(e.getCustomMessage(1, true, true)); | |
| 95 | - } finally { | |
| 96 | - cluster.close(); | |
| 97 | - } | |
| 67 | + Cluster cluster = register(Cluster.builder() | |
| 68 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 69 | + .build()); | |
| 70 | + cluster.connect(); | |
| 98 | 71 | } |
| 72 | + | |
| 99 | 73 | } |
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +21 −38
| @@ -22,18 +22,20 @@ | ||
| 22 | 22 | import java.util.Collection; |
| 23 | 23 | import java.util.Collections; |
| 24 | 24 | |
| 25 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 25 | 26 | import static org.testng.Assert.assertEquals; |
| 26 | 27 | import static org.testng.Assert.assertTrue; |
| 27 | 28 | |
| 28 | -public class BatchStatementTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 29 | +@CreateCCM(PER_METHOD) | |
| 30 | +public class BatchStatementTest extends CCMTestsSupport { | |
| 29 | 31 | |
| 30 | 32 | @Override |
| 31 | - protected Collection<String> getTableDefinitions() { | |
| 33 | + public Collection<String> createTestFixtures() { | |
| 32 | 34 | return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))"); |
| 33 | 35 | } |
| 34 | 36 | |
| 35 | 37 | @Test(groups = "short") |
| 36 | - public void simpleBatchTest() throws Throwable { | |
| 38 | + public void simpleBatchTest() { | |
| 37 | 39 | try { |
| 38 | 40 | PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?)"); |
| 39 | 41 | |
| @@ -65,52 +67,33 @@ | ||
| 65 | 67 | |
| 66 | 68 | assertTrue(rs.isExhausted()); |
| 67 | 69 | |
| 68 | - session.execute("DELETE FROM test WHERE k='key1'"); | |
| 69 | - session.execute("DELETE FROM test WHERE k='key2'"); | |
| 70 | - | |
| 71 | 70 | } catch (UnsupportedFeatureException e) { |
| 72 | 71 | // This is expected when testing the protocol v1 |
| 73 | - if (cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum() != ProtocolVersion.V1) | |
| 74 | - throw e; | |
| 75 | - } catch (Throwable t) { | |
| 76 | - errorOut(); | |
| 77 | - throw t; | |
| 72 | + assertEquals(cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(), ProtocolVersion.V1); | |
| 78 | 73 | } |
| 79 | 74 | } |
| 80 | 75 | |
| 81 | 76 | @Test(groups = "short") |
| 82 | 77 | @CassandraVersion(major = 2.0, minor = 9, description = "This will only work with C* 2.0.9 (CASSANDRA-7337)") |
| 83 | - public void casBatchTest() throws Throwable { | |
| 84 | - try { | |
| 85 | - PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS"); | |
| 78 | + public void casBatchTest() { | |
| 79 | + PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS"); | |
| 86 | 80 | |
| 87 | - BatchStatement batch = new BatchStatement(); | |
| 88 | - | |
| 89 | - batch.add(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0)); | |
| 90 | - batch.add(st.bind("key1", 1)); | |
| 91 | - batch.add(st.bind("key1", 2)); | |
| 81 | + BatchStatement batch = new BatchStatement(); | |
| 92 | 82 | |
| 93 | - assertEquals(3, batch.size()); | |
| 83 | + batch.add(new SimpleStatement("INSERT INTO test (k, v) VALUES (?, ?)", "key1", 0)); | |
| 84 | + batch.add(st.bind("key1", 1)); | |
| 85 | + batch.add(st.bind("key1", 2)); | |
| 94 | 86 | |
| 95 | - ResultSet rs = session.execute(batch); | |
| 96 | - Row r = rs.one(); | |
| 97 | - assertTrue(!r.isNull("[applied]")); | |
| 98 | - assertEquals(r.getBool("[applied]"), true); | |
| 87 | + assertEquals(3, batch.size()); | |
| 99 | 88 | |
| 100 | - rs = session.execute(batch); | |
| 101 | - r = rs.one(); | |
| 102 | - assertTrue(!r.isNull("[applied]")); | |
| 103 | - assertEquals(r.getBool("[applied]"), false); | |
| 89 | + ResultSet rs = session.execute(batch); | |
| 90 | + Row r = rs.one(); | |
| 91 | + assertTrue(!r.isNull("[applied]")); | |
| 92 | + assertEquals(r.getBool("[applied]"), true); | |
| 104 | 93 | |
| 105 | - } catch (UnsupportedFeatureException e) { | |
| 106 | - // This is expected when testing the protocol v1 | |
| 107 | - if (cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum() != ProtocolVersion.V1) | |
| 108 | - throw e; | |
| 109 | - } catch (Throwable t) { | |
| 110 | - errorOut(); | |
| 111 | - throw t; | |
| 112 | - } finally { | |
| 113 | - session.execute("DELETE FROM test WHERE k='key1'"); | |
| 114 | - } | |
| 94 | + rs = session.execute(batch); | |
| 95 | + r = rs.one(); | |
| 96 | + assertTrue(!r.isNull("[applied]")); | |
| 97 | + assertEquals(r.getBool("[applied]"), false); | |
| 115 | 98 | } |
| 116 | 99 | } |
modified driver-core/src/test/java/com/datastax/driver/core/BoundStatementTest.java +3 −3
| @@ -25,12 +25,12 @@ | ||
| 25 | 25 | import static org.assertj.core.api.Assertions.assertThat; |
| 26 | 26 | import static org.assertj.core.api.Assertions.fail; |
| 27 | 27 | |
| 28 | -public class BoundStatementTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 28 | +public class BoundStatementTest extends CCMTestsSupport { | |
| 29 | 29 | |
| 30 | 30 | PreparedStatement prepared; |
| 31 | 31 | |
| 32 | 32 | @Override |
| 33 | - protected Collection<String> getTableDefinitions() { | |
| 33 | + public Collection<String> createTestFixtures() { | |
| 34 | 34 | return Lists.newArrayList("CREATE TABLE foo (k int primary key, v1 text, v2 list<int>)"); |
| 35 | 35 | } |
| 36 | 36 | |
| @@ -66,4 +66,4 @@ | ||
| 66 | 66 | fail("Expected index error"); |
| 67 | 67 | } catch (IndexOutOfBoundsException e) { /* expected */ } |
| 68 | 68 | } |
| 69 | -} | |
| No newline at the end of the file | ||
| 69 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +464 −435
| @@ -15,10 +15,9 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.exceptions.AlreadyExistsException; | |
| 19 | -import com.datastax.driver.core.exceptions.DriverException; | |
| 20 | -import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 18 | +import com.datastax.driver.core.policies.AddressTranslater; | |
| 21 | 19 | import com.google.common.base.Joiner; |
| 20 | +import com.google.common.base.Throwables; | |
| 22 | 21 | import com.google.common.collect.ImmutableMap; |
| 23 | 22 | import com.google.common.collect.Maps; |
| 24 | 23 | import com.google.common.io.ByteStreams; |
| @@ -27,29 +26,18 @@ | ||
| 27 | 26 | import org.apache.commons.exec.*; |
| 28 | 27 | import org.slf4j.Logger; |
| 29 | 28 | import org.slf4j.LoggerFactory; |
| 30 | -import org.testng.annotations.AfterClass; | |
| 31 | -import org.testng.annotations.BeforeClass; | |
| 32 | 29 | |
| 33 | 30 | import java.io.*; |
| 34 | -import java.net.InetAddress; | |
| 35 | 31 | import java.net.InetSocketAddress; |
| 36 | -import java.net.Socket; | |
| 37 | -import java.net.UnknownHostException; | |
| 38 | -import java.util.Collection; | |
| 39 | -import java.util.Collections; | |
| 40 | -import java.util.Map; | |
| 41 | -import java.util.concurrent.TimeUnit; | |
| 42 | -import java.util.concurrent.atomic.AtomicLong; | |
| 43 | - | |
| 44 | -import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; | |
| 45 | -import static com.datastax.driver.core.TestUtils.SIMPLE_KEYSPACE; | |
| 46 | -import static org.testng.Assert.fail; | |
| 47 | - | |
| 48 | -public class CCMBridge { | |
| 32 | +import java.util.*; | |
| 33 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 49 | 34 | |
| 50 | - private static final Logger logger = LoggerFactory.getLogger(CCMBridge.class); | |
| 35 | +import static com.datastax.driver.core.TestUtils.executeNoFail; | |
| 36 | +import static com.datastax.driver.core.TestUtils.findAvailablePort; | |
| 37 | + | |
| 38 | +public class CCMBridge implements Closeable { | |
| 51 | 39 | |
| 52 | - public static final String IP_PREFIX; | |
| 40 | + private static final Logger logger = LoggerFactory.getLogger(CCMBridge.class); | |
| 53 | 41 | |
| 54 | 42 | private static final String CASSANDRA_VERSION; |
| 55 | 43 | |
| @@ -153,7 +141,7 @@ | ||
| 153 | 141 | installArgs.append("-v git:"); |
| 154 | 142 | installArgs.append(branch.trim().replaceAll("\"", "")); |
| 155 | 143 | } else { |
| 156 | - installArgs.append("-v"); | |
| 144 | + installArgs.append("-v "); | |
| 157 | 145 | installArgs.append(CASSANDRA_VERSION); |
| 158 | 146 | } |
| 159 | 147 | |
| @@ -163,12 +151,6 @@ | ||
| 163 | 151 | |
| 164 | 152 | CASSANDRA_INSTALL_ARGS = installArgs.toString(); |
| 165 | 153 | |
| 166 | - String ip_prefix = System.getProperty("ipprefix"); | |
| 167 | - if (ip_prefix == null || ip_prefix.isEmpty()) { | |
| 168 | - ip_prefix = "127.0.1."; | |
| 169 | - } | |
| 170 | - IP_PREFIX = ip_prefix; | |
| 171 | - | |
| 172 | 154 | // Inherit the current environment. |
| 173 | 155 | Map<String, String> envMap = Maps.newHashMap(new ProcessBuilder().environment()); |
| 174 | 156 | // If ccm.path is set, override the PATH variable with it. |
| @@ -214,13 +196,38 @@ | ||
| 214 | 196 | return osName != null && osName.startsWith("Windows"); |
| 215 | 197 | } |
| 216 | 198 | |
| 199 | + private final String clusterName; | |
| 200 | + | |
| 201 | + private final VersionNumber version; | |
| 202 | + | |
| 203 | + private final int storagePort; | |
| 204 | + | |
| 205 | + private final int thriftPort; | |
| 206 | + | |
| 207 | + private final int binaryPort; | |
| 208 | + | |
| 217 | 209 | private final File ccmDir; |
| 218 | 210 | |
| 219 | 211 | private final boolean isDSE; |
| 220 | 212 | |
| 221 | - private CCMBridge(boolean isDSE) { | |
| 222 | - this.ccmDir = Files.createTempDir(); | |
| 213 | + private final String jvmArgs; | |
| 214 | + | |
| 215 | + private final int initialNumberOfNodes; | |
| 216 | + | |
| 217 | + private boolean keepLogs = false; | |
| 218 | + | |
| 219 | + private boolean closed = false; | |
| 220 | + | |
| 221 | + private CCMBridge(String clusterName, boolean isDSE, VersionNumber version, int storagePort, int thriftPort, int binaryPort, String jvmArgs, int initialNumberOfNodes) { | |
| 222 | + this.clusterName = clusterName; | |
| 223 | + this.version = version; | |
| 224 | + this.storagePort = storagePort; | |
| 225 | + this.thriftPort = thriftPort; | |
| 226 | + this.binaryPort = binaryPort; | |
| 223 | 227 | this.isDSE = isDSE; |
| 228 | + this.jvmArgs = jvmArgs; | |
| 229 | + this.initialNumberOfNodes = initialNumberOfNodes; | |
| 230 | + this.ccmDir = Files.createTempDir(); | |
| 224 | 231 | } |
| 225 | 232 | |
| 226 | 233 | /** |
| @@ -280,153 +287,232 @@ | ||
| 280 | 287 | return CASSANDRA_INSTALL_ARGS; |
| 281 | 288 | } |
| 282 | 289 | |
| 290 | + public static Builder builder() { | |
| 291 | + return new Builder(); | |
| 292 | + } | |
| 293 | + | |
| 283 | 294 | /** |
| 284 | - * <p> | |
| 285 | - * Extracts a keystore from the classpath into a temporary file. | |
| 286 | - * </p> | |
| 295 | + * Returns the address of the {@code nth} host in the CCM cluster (counting from 1, i.e., | |
| 296 | + * {@code getHostAddress(1)} returns the address of the first node. | |
| 287 | 297 | * <p/> |
| 288 | - * <p> | |
| 289 | - * This is needed as the keystore could be part of a built test jar used by other | |
| 290 | - * projects, and they need to be extracted to a file system so cassandra may use them. | |
| 291 | - * </p> | |
| 298 | + * In multi-DC setups, nodes are numbered in ascending order of their datacenter number. | |
| 299 | + * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4. | |
| 292 | 300 | * |
| 293 | - * @param storePath Path in classpath where the keystore exists. | |
| 294 | - * @return The generated File. | |
| 301 | + * @return the address of the {@code nth} host in the cluster. | |
| 295 | 302 | */ |
| 296 | - private static File createTempStore(String storePath) { | |
| 297 | - File f = null; | |
| 298 | - Closer closer = Closer.create(); | |
| 299 | - try { | |
| 300 | - InputStream trustStoreIs = CCMBridge.class.getResourceAsStream(storePath); | |
| 301 | - closer.register(trustStoreIs); | |
| 302 | - f = File.createTempFile("server", ".store"); | |
| 303 | - logger.debug("Created store file {} for {}.", f, storePath); | |
| 304 | - OutputStream trustStoreOs = new FileOutputStream(f); | |
| 305 | - closer.register(trustStoreOs); | |
| 306 | - ByteStreams.copy(trustStoreIs, trustStoreOs); | |
| 307 | - } catch (IOException e) { | |
| 308 | - logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e); | |
| 309 | - } finally { | |
| 310 | - try { | |
| 311 | - closer.close(); | |
| 312 | - } catch (IOException e) { | |
| 313 | - logger.warn("Failure closing streams.", e); | |
| 303 | + public InetSocketAddress addressOfNode(int n) { | |
| 304 | + return new InetSocketAddress(TestUtils.ipOfNode(n), binaryPort); | |
| 305 | + } | |
| 306 | + | |
| 307 | + /** | |
| 308 | + * Returns an {@link AddressTranslater} to use when tests must manually create | |
| 309 | + * {@link Cluster} instances. | |
| 310 | + * <p/> | |
| 311 | + * This translator is necessary because hosts in this cluster do not necessarily use standard ports. | |
| 312 | + * | |
| 313 | + * @return an {@link AddressTranslater} to use when tests must manually create | |
| 314 | + * {@link Cluster} instances. | |
| 315 | + */ | |
| 316 | + public AddressTranslater addressTranslator() { | |
| 317 | + return new AddressTranslater() { | |
| 318 | + @Override | |
| 319 | + public InetSocketAddress translate(InetSocketAddress address) { | |
| 320 | + return new InetSocketAddress(address.getAddress(), getBinaryPort()); | |
| 314 | 321 | } |
| 315 | - } | |
| 316 | - return f; | |
| 322 | + }; | |
| 323 | + } | |
| 324 | + | |
| 325 | + /** | |
| 326 | + * Returns the Cassandra version of this CCM cluster. | |
| 327 | + * <p/> | |
| 328 | + * By default the version is equal to {@link #getCassandraVersion()}. | |
| 329 | + * | |
| 330 | + * @return The version of this CCM cluster. | |
| 331 | + */ | |
| 332 | + public VersionNumber getVersion() { | |
| 333 | + return version; | |
| 334 | + } | |
| 335 | + | |
| 336 | + /** | |
| 337 | + * The number of nodes that were initially created with this CCM instance. | |
| 338 | + * <p/> | |
| 339 | + * This does not account for nodes created or removed during the cluster's lifecycle. | |
| 340 | + * | |
| 341 | + * @return The number of nodes that were initially created with this CCM instance. | |
| 342 | + */ | |
| 343 | + public int getInitialNumberOfNodes() { | |
| 344 | + return initialNumberOfNodes; | |
| 345 | + } | |
| 346 | + | |
| 347 | + public File getCcmDir() { | |
| 348 | + return ccmDir; | |
| 349 | + } | |
| 350 | + | |
| 351 | + public File getClusterDir() { | |
| 352 | + return new File(ccmDir, clusterName); | |
| 353 | + } | |
| 354 | + | |
| 355 | + public File getNodeDir(int n) { | |
| 356 | + return new File(getClusterDir(), "node" + n); | |
| 317 | 357 | } |
| 318 | 358 | |
| 319 | - public static Builder builder(String clusterName) { | |
| 320 | - return new Builder(clusterName); | |
| 359 | + public File getNodeConfDir(int n) { | |
| 360 | + return new File(getNodeDir(n), "conf"); | |
| 321 | 361 | } |
| 322 | 362 | |
| 323 | - public static CCMBridge.CCMCluster buildCluster(int nbNodes, Cluster.Builder builder) { | |
| 324 | - return CCMCluster.create(nbNodes, builder); | |
| 363 | + public int getStoragePort() { | |
| 364 | + return storagePort; | |
| 325 | 365 | } |
| 326 | 366 | |
| 327 | - public static CCMBridge.CCMCluster buildCluster(int nbNodesDC1, int nbNodesDC2, Cluster.Builder builder) { | |
| 328 | - return CCMCluster.create(nbNodesDC1, nbNodesDC2, builder); | |
| 367 | + public int getThriftPort() { | |
| 368 | + return thriftPort; | |
| 369 | + } | |
| 370 | + | |
| 371 | + public int getBinaryPort() { | |
| 372 | + return binaryPort; | |
| 373 | + } | |
| 374 | + | |
| 375 | + public void setKeepLogs(boolean keepLogs) { | |
| 376 | + this.keepLogs = keepLogs; | |
| 377 | + } | |
| 378 | + | |
| 379 | + @Override | |
| 380 | + public synchronized void close() { | |
| 381 | + if (closed) | |
| 382 | + return; | |
| 383 | + logger.debug("Closing: " + this); | |
| 384 | + if (keepLogs) { | |
| 385 | + executeNoFail(new Runnable() { | |
| 386 | + @Override | |
| 387 | + public void run() { | |
| 388 | + stop(); | |
| 389 | + } | |
| 390 | + }, false); | |
| 391 | + logger.info("Error during tests, kept C* logs in " + getCcmDir()); | |
| 392 | + } else { | |
| 393 | + executeNoFail(new Runnable() { | |
| 394 | + @Override | |
| 395 | + public void run() { | |
| 396 | + remove(); | |
| 397 | + } | |
| 398 | + }, false); | |
| 399 | + executeNoFail(new Runnable() { | |
| 400 | + @Override | |
| 401 | + public void run() { | |
| 402 | + org.assertj.core.util.Files.delete(getCcmDir()); | |
| 403 | + } | |
| 404 | + }, false); | |
| 405 | + } | |
| 406 | + closed = true; | |
| 407 | + logger.debug("Closed: " + this); | |
| 329 | 408 | } |
| 330 | 409 | |
| 331 | 410 | public void start() { |
| 332 | - execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto"); | |
| 411 | + logger.debug("Starting: " + this); | |
| 412 | + execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs); | |
| 333 | 413 | } |
| 334 | 414 | |
| 335 | - public void stop() { | |
| 415 | + public synchronized void stop() { | |
| 416 | + if (closed) | |
| 417 | + return; | |
| 418 | + logger.debug("Stopping: " + this); | |
| 336 | 419 | execute(CCM_COMMAND + " stop"); |
| 420 | + closed = true; | |
| 337 | 421 | } |
| 338 | 422 | |
| 339 | - public void forceStop() { | |
| 423 | + public synchronized void forceStop() { | |
| 424 | + if (closed) | |
| 425 | + return; | |
| 426 | + logger.debug("Force stopping: " + this); | |
| 340 | 427 | execute(CCM_COMMAND + " stop --not-gently"); |
| 428 | + closed = true; | |
| 341 | 429 | } |
| 342 | 430 | |
| 343 | 431 | public void start(int n) { |
| 344 | - logger.info("Starting: " + IP_PREFIX + n); | |
| 345 | - execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n); | |
| 346 | - } | |
| 347 | - | |
| 348 | - public void start(int n, String... jvmArg) { | |
| 349 | - StringBuilder jvmArgs = new StringBuilder(""); | |
| 350 | - for (int i = 0; i < jvmArg.length; i++) { | |
| 351 | - jvmArgs.append(" --jvm_arg="); | |
| 352 | - jvmArgs.append(jvmArg[i]); | |
| 353 | - } | |
| 354 | - logger.info("Starting: " + IP_PREFIX + n + " with " + jvmArgs); | |
| 355 | - execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto %s", n, jvmArgs.toString()); | |
| 432 | + logger.debug(String.format("Starting: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this)); | |
| 433 | + execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs, n); | |
| 356 | 434 | } |
| 357 | 435 | |
| 358 | 436 | public void stop(int n) { |
| 359 | - logger.info("Stopping: " + IP_PREFIX + n); | |
| 437 | + logger.debug(String.format("Stopping: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this)); | |
| 360 | 438 | execute(CCM_COMMAND + " node%d stop", n); |
| 361 | 439 | } |
| 362 | 440 | |
| 363 | - public void stop(String clusterName) { | |
| 364 | - logger.info("Stopping Cluster : " + clusterName); | |
| 365 | - execute(CCM_COMMAND + " stop " + clusterName); | |
| 366 | - } | |
| 367 | - | |
| 368 | 441 | public void forceStop(int n) { |
| 369 | - logger.info("Force stopping: " + IP_PREFIX + n); | |
| 442 | + logger.debug(String.format("Force stopping: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this)); | |
| 370 | 443 | execute(CCM_COMMAND + " node%d stop --not-gently", n); |
| 371 | 444 | } |
| 372 | 445 | |
| 373 | - public void remove() { | |
| 446 | + public synchronized void remove() { | |
| 374 | 447 | stop(); |
| 448 | + logger.debug("Removing: " + this); | |
| 375 | 449 | execute(CCM_COMMAND + " remove"); |
| 376 | 450 | } |
| 377 | 451 | |
| 378 | - public void remove(String clusterName) { | |
| 379 | - stop(clusterName); | |
| 380 | - execute(CCM_COMMAND + " remove " + clusterName); | |
| 381 | - } | |
| 382 | - | |
| 383 | 452 | public void remove(int n) { |
| 384 | - logger.info("Removing: " + IP_PREFIX + n); | |
| 453 | + logger.debug(String.format("Removing: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this)); | |
| 385 | 454 | execute(CCM_COMMAND + " node%d remove", n); |
| 386 | 455 | } |
| 387 | 456 | |
| 388 | - public void bootstrapNode(int n) { | |
| 389 | - bootstrapNode(n, null); | |
| 390 | - } | |
| 391 | - | |
| 392 | - public void bootstrapNode(int n, String dc) { | |
| 393 | - if (dc == null) | |
| 394 | - execute(CCM_COMMAND + " add node%d -i %s%d -j %d -r %d -b -s" + (isDSE ? " --dse" : ""), n, IP_PREFIX, n, 7000 + 100 * n, 8000 + 100 * n); | |
| 395 | - else | |
| 396 | - execute(CCM_COMMAND + " add node%d -i %s%d -j %d -b -d %s -s" + (isDSE ? " --dse" : ""), n, IP_PREFIX, n, 7000 + 100 * n, dc); | |
| 397 | - execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n); | |
| 457 | + public void add(int n) { | |
| 458 | + add(1, n); | |
| 398 | 459 | } |
| 399 | 460 | |
| 400 | - public void bootstrapNodeWithPorts(int n, int thriftPort, int storagePort, int binaryPort, int jmxPort, int remoteDebugPort) { | |
| 401 | - String thriftItf = IP_PREFIX + n + ":" + thriftPort; | |
| 402 | - String storageItf = IP_PREFIX + n + ":" + storagePort; | |
| 403 | - String binaryItf = IP_PREFIX + n + ":" + binaryPort; | |
| 404 | - String remoteLogItf = IP_PREFIX + n + ":" + remoteDebugPort; | |
| 405 | - execute(CCM_COMMAND + " add node%d -i %s%d -b -t %s -l %s --binary-itf %s -j %d -r %s -s" + (isDSE ? " --dse" : ""), | |
| 406 | - n, IP_PREFIX, n, thriftItf, storageItf, binaryItf, jmxPort, remoteLogItf); | |
| 407 | - execute(CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto", n); | |
| 461 | + public void add(int dc, int n) { | |
| 462 | + logger.debug(String.format("Adding: node %s (%s%s:%s) to %s", n, TestUtils.IP_PREFIX, n, binaryPort, this)); | |
| 463 | + String thriftItf = TestUtils.ipOfNode(n) + ":" + thriftPort; | |
| 464 | + String storageItf = TestUtils.ipOfNode(n) + ":" + storagePort; | |
| 465 | + String binaryItf = TestUtils.ipOfNode(n) + ":" + binaryPort; | |
| 466 | + String remoteLogItf = TestUtils.ipOfNode(n) + ":" + TestUtils.findAvailablePort(); | |
| 467 | + execute(CCM_COMMAND + " add node%d -d dc%s -i %s%d -t %s -l %s --binary-itf %s -j %d -r %s -s -b" + (isDSE ? " --dse" : ""), | |
| 468 | + n, dc, TestUtils.IP_PREFIX, n, thriftItf, storageItf, binaryItf, TestUtils.findAvailablePort(), remoteLogItf); | |
| 408 | 469 | } |
| 409 | 470 | |
| 410 | 471 | public void decommissionNode(int n) { |
| 472 | + logger.debug(String.format("Decommissioning: node %s (%s%s:%s) from %s", n, TestUtils.IP_PREFIX, n, binaryPort, this)); | |
| 411 | 473 | execute(CCM_COMMAND + " node%d decommission", n); |
| 412 | 474 | } |
| 413 | 475 | |
| 414 | - public void updateConfig(Map<String, String> configs) { | |
| 476 | + public void updateConfig(Map<String, Object> configs) { | |
| 415 | 477 | StringBuilder confStr = new StringBuilder(); |
| 416 | - for (Map.Entry<String, String> entry : configs.entrySet()) { | |
| 417 | - confStr.append(entry.getKey() + ":" + entry.getValue() + " "); | |
| 478 | + for (Map.Entry<String, Object> entry : configs.entrySet()) { | |
| 479 | + confStr | |
| 480 | + .append(entry.getKey()) | |
| 481 | + .append(":") | |
| 482 | + .append(entry.getValue()) | |
| 483 | + .append(" "); | |
| 418 | 484 | } |
| 419 | 485 | execute(CCM_COMMAND + " updateconf " + confStr); |
| 420 | 486 | } |
| 421 | 487 | |
| 422 | - public void updateDSEConfig(Map<String, String> configs) { | |
| 488 | + public void updateDSEConfig(Map<String, Object> configs) { | |
| 423 | 489 | StringBuilder confStr = new StringBuilder(); |
| 424 | - for (Map.Entry<String, String> entry : configs.entrySet()) { | |
| 425 | - confStr.append(entry.getKey() + ":" + entry.getValue() + " "); | |
| 490 | + for (Map.Entry<String, Object> entry : configs.entrySet()) { | |
| 491 | + confStr | |
| 492 | + .append(entry.getKey()) | |
| 493 | + .append(":") | |
| 494 | + .append(entry.getValue()) | |
| 495 | + .append(" "); | |
| 426 | 496 | } |
| 427 | 497 | execute(CCM_COMMAND + " updatedseconf " + confStr); |
| 428 | 498 | } |
| 429 | 499 | |
| 500 | + public void updateNodeConfig(int n, String key, Object value) { | |
| 501 | + updateNodeConfig(n, ImmutableMap.<String, Object>builder().put(key, value).build()); | |
| 502 | + } | |
| 503 | + | |
| 504 | + public void updateNodeConfig(int n, Map<String, Object> configs) { | |
| 505 | + StringBuilder confStr = new StringBuilder(); | |
| 506 | + for (Map.Entry<String, Object> entry : configs.entrySet()) { | |
| 507 | + confStr | |
| 508 | + .append(entry.getKey()) | |
| 509 | + .append(":") | |
| 510 | + .append(entry.getValue()) | |
| 511 | + .append(" "); | |
| 512 | + } | |
| 513 | + execute(CCM_COMMAND + " node%s updateconf %s", n, confStr); | |
| 514 | + } | |
| 515 | + | |
| 430 | 516 | public void setWorkload(int node, String workload) { |
| 431 | 517 | execute(CCM_COMMAND + " node%d setworkload %s", node, workload); |
| 432 | 518 | } |
| @@ -434,6 +520,9 @@ | ||
| 434 | 520 | private void execute(String command, Object... args) { |
| 435 | 521 | |
| 436 | 522 | String fullCommand = String.format(command, args) + " --config-dir=" + ccmDir; |
| 523 | + Closer closer = Closer.create(); | |
| 524 | + // 5 minutes timeout | |
| 525 | + ExecuteWatchdog watchDog = new ExecuteWatchdog(5 * 60 * 1000); | |
| 437 | 526 | try { |
| 438 | 527 | logger.debug("Executing: " + fullCommand); |
| 439 | 528 | CommandLine cli = CommandLine.parse(fullCommand); |
| @@ -451,9 +540,11 @@ | ||
| 451 | 540 | logger.error("ccmerr> " + line); |
| 452 | 541 | } |
| 453 | 542 | }; |
| 454 | - | |
| 543 | + closer.register(outStream); | |
| 544 | + closer.register(errStream); | |
| 455 | 545 | ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream); |
| 456 | 546 | executor.setStreamHandler(streamHandler); |
| 547 | + executor.setWatchdog(watchDog); | |
| 457 | 548 | |
| 458 | 549 | int retValue = executor.execute(cli, ENVIRONMENT_MAP); |
| 459 | 550 | if (retValue != 0) { |
| @@ -461,7 +552,15 @@ | ||
| 461 | 552 | throw new RuntimeException(); |
| 462 | 553 | } |
| 463 | 554 | } catch (IOException e) { |
| 555 | + if (watchDog.killedProcess()) | |
| 556 | + logger.error("The command {} was killed after 5 minutes", fullCommand); | |
| 464 | 557 | throw new RuntimeException(String.format("The command %s failed to execute", fullCommand), e); |
| 558 | + } finally { | |
| 559 | + try { | |
| 560 | + closer.close(); | |
| 561 | + } catch (IOException e) { | |
| 562 | + Throwables.propagate(e); | |
| 563 | + } | |
| 465 | 564 | } |
| 466 | 565 | } |
| 467 | 566 | |
| @@ -469,319 +568,83 @@ | ||
| 469 | 568 | * Waits for a host to be up by pinging the TCP socket directly, without using the Java driver's API. |
| 470 | 569 | */ |
| 471 | 570 | public void waitForUp(int node) { |
| 472 | - try { | |
| 473 | - InetAddress address = InetAddress.getByName(ipOfNode(node)); | |
| 474 | - CCMBridge.busyWaitForPort(address, 9042, true); | |
| 475 | - } catch (UnknownHostException e) { | |
| 476 | - fail("Unknown host " + ipOfNode(node) + "( node " + node + " of CCMBridge)"); | |
| 477 | - } | |
| 571 | + TestUtils.waitUntilPortIsUp(addressOfNode(node)); | |
| 478 | 572 | } |
| 479 | 573 | |
| 480 | 574 | /** |
| 481 | 575 | * Waits for a host to be down by pinging the TCP socket directly, without using the Java driver's API. |
| 482 | 576 | */ |
| 483 | 577 | public void waitForDown(int node) { |
| 484 | - try { | |
| 485 | - InetAddress address = InetAddress.getByName(ipOfNode(node)); | |
| 486 | - CCMBridge.busyWaitForPort(address, 9042, false); | |
| 487 | - } catch (UnknownHostException e) { | |
| 488 | - fail("Unknown host " + ipOfNode(node) + "( node " + node + " of CCMBridge)"); | |
| 489 | - } | |
| 490 | - } | |
| 491 | - | |
| 492 | - private static void busyWaitForPort(InetAddress address, int port, boolean expectedConnectionState) { | |
| 493 | - long maxAcceptableWaitTime = TimeUnit.SECONDS.toMillis(10); | |
| 494 | - long waitQuantum = TimeUnit.MILLISECONDS.toMillis(500); | |
| 495 | - long waitTimeSoFar = 0; | |
| 496 | - boolean connectionState = !expectedConnectionState; | |
| 497 | - | |
| 498 | - while (connectionState != expectedConnectionState && waitTimeSoFar < maxAcceptableWaitTime) { | |
| 499 | - connectionState = CCMBridge.pingPort(address, port); | |
| 500 | - try { | |
| 501 | - Thread.sleep(waitQuantum); | |
| 502 | - waitTimeSoFar += waitQuantum; | |
| 503 | - } catch (InterruptedException e) { | |
| 504 | - throw new RuntimeException("Interrupted while pinging " + address + ":" + port, e); | |
| 505 | - } | |
| 506 | - } | |
| 578 | + TestUtils.waitUntilPortIsDown(addressOfNode(node)); | |
| 507 | 579 | } |
| 508 | 580 | |
| 509 | - private static boolean pingPort(InetAddress address, int port) { | |
| 510 | - logger.debug("Trying {}:{}...", address, port); | |
| 511 | - boolean connectionSuccessful = false; | |
| 512 | - Socket socket = null; | |
| 581 | + /** | |
| 582 | + * <p> | |
| 583 | + * Extracts a keystore from the classpath into a temporary file. | |
| 584 | + * </p> | |
| 585 | + * <p/> | |
| 586 | + * <p> | |
| 587 | + * This is needed as the keystore could be part of a built test jar used by other | |
| 588 | + * projects, and they need to be extracted to a file system so cassandra may use them. | |
| 589 | + * </p> | |
| 590 | + * | |
| 591 | + * @param storePath Path in classpath where the keystore exists. | |
| 592 | + * @return The generated File. | |
| 593 | + */ | |
| 594 | + private static File createTempStore(String storePath) { | |
| 595 | + File f = null; | |
| 596 | + Closer closer = Closer.create(); | |
| 513 | 597 | try { |
| 514 | - socket = new Socket(address, port); | |
| 515 | - connectionSuccessful = true; | |
| 516 | - logger.debug("Successfully connected"); | |
| 598 | + InputStream trustStoreIs = CCMBridge.class.getResourceAsStream(storePath); | |
| 599 | + closer.register(trustStoreIs); | |
| 600 | + f = File.createTempFile("server", ".store"); | |
| 601 | + logger.debug("Created store file {} for {}.", f, storePath); | |
| 602 | + OutputStream trustStoreOs = new FileOutputStream(f); | |
| 603 | + closer.register(trustStoreOs); | |
| 604 | + ByteStreams.copy(trustStoreIs, trustStoreOs); | |
| 517 | 605 | } catch (IOException e) { |
| 518 | - logger.debug("Connection failed"); | |
| 606 | + logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e); | |
| 519 | 607 | } finally { |
| 520 | - if (socket != null) | |
| 521 | - try { | |
| 522 | - socket.close(); | |
| 523 | - } catch (IOException e) { | |
| 524 | - logger.warn("Error closing socket to " + address); | |
| 525 | - } | |
| 526 | - } | |
| 527 | - return connectionSuccessful; | |
| 528 | - } | |
| 529 | - | |
| 530 | - public static String ipOfNode(int nodeNumber) { | |
| 531 | - return IP_PREFIX + Integer.toString(nodeNumber); | |
| 532 | - } | |
| 533 | - | |
| 534 | - public static class terminationHook extends Thread { | |
| 535 | - @Override | |
| 536 | - public void run() { | |
| 537 | - logger.debug("shut down hook task.."); | |
| 538 | - | |
| 539 | - if (PerClassSingleNodeCluster.cluster != null) { | |
| 540 | - PerClassSingleNodeCluster.cluster.close(); | |
| 541 | - } | |
| 542 | - if (PerClassSingleNodeCluster.ccmBridge == null) { | |
| 543 | - logger.error("No cluster to discard"); | |
| 544 | - } else if (PerClassSingleNodeCluster.erroredOut) { | |
| 545 | - PerClassSingleNodeCluster.ccmBridge.remove("test-class"); | |
| 546 | - logger.info("Error during tests, kept C* logs in " + PerClassSingleNodeCluster.ccmBridge.ccmDir); | |
| 547 | - } else { | |
| 548 | - PerClassSingleNodeCluster.ccmBridge.remove("test-class"); | |
| 549 | - PerClassSingleNodeCluster.ccmBridge.ccmDir.delete(); | |
| 550 | - } | |
| 551 | - | |
| 552 | - } | |
| 553 | - } | |
| 554 | - | |
| 555 | - // One cluster for the whole test class | |
| 556 | - public static abstract class PerClassSingleNodeCluster { | |
| 557 | - | |
| 558 | - protected static CCMBridge ccmBridge; | |
| 559 | - private static boolean erroredOut; | |
| 560 | - private static boolean clusterInitialized = false; | |
| 561 | - private static AtomicLong ksNumber; | |
| 562 | - protected String keyspace; | |
| 563 | - | |
| 564 | - protected static InetSocketAddress hostAddress; | |
| 565 | - protected static int[] ports; | |
| 566 | - | |
| 567 | - protected static Cluster cluster; | |
| 568 | - protected static Session session; | |
| 569 | - | |
| 570 | - protected final VersionNumber cassandraVersion = VersionNumber.parse(System.getProperty("cassandra.version")); | |
| 571 | - | |
| 572 | - protected abstract Collection<String> getTableDefinitions(); | |
| 573 | - | |
| 574 | - // Give individual tests a chance to customize the cluster configuration | |
| 575 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 576 | - return builder; | |
| 577 | - } | |
| 578 | - | |
| 579 | - public void errorOut() { | |
| 580 | - erroredOut = true; | |
| 581 | - } | |
| 582 | - | |
| 583 | - @BeforeClass(groups = {"isolated", "short", "long"}) | |
| 584 | - public void beforeClass() { | |
| 585 | - maybeInitCluster(); | |
| 586 | - initKeyspace(); | |
| 587 | - } | |
| 588 | - | |
| 589 | - @AfterClass(groups = {"isolated", "short", "long"}) | |
| 590 | - public void afterClass() { | |
| 591 | - try { | |
| 592 | - clearSimpleKeyspace(); | |
| 593 | - } finally { | |
| 594 | - if (cluster != null) { | |
| 595 | - cluster.close(); | |
| 596 | - } | |
| 597 | - } | |
| 598 | - } | |
| 599 | - | |
| 600 | - private void maybeInitCluster() { | |
| 601 | - if (!clusterInitialized) { | |
| 602 | - try { | |
| 603 | - //launch ccm cluster | |
| 604 | - ccmBridge = CCMBridge.builder("test-class").withoutNodes().notStarted().build(); | |
| 605 | - | |
| 606 | - ports = new int[5]; | |
| 607 | - for (int i = 0; i < 5; i++) { | |
| 608 | - ports[i] = TestUtils.findAvailablePort(11000 + i); | |
| 609 | - } | |
| 610 | - | |
| 611 | - ccmBridge.bootstrapNodeWithPorts(1, ports[0], ports[1], ports[2], ports[3], ports[4]); | |
| 612 | - ksNumber = new AtomicLong(0); | |
| 613 | - erroredOut = false; | |
| 614 | - hostAddress = new InetSocketAddress(InetAddress.getByName(IP_PREFIX + 1), ports[2]); | |
| 615 | - | |
| 616 | - Runtime r = Runtime.getRuntime(); | |
| 617 | - r.addShutdownHook(new terminationHook()); | |
| 618 | - clusterInitialized = true; | |
| 619 | - | |
| 620 | - } catch (UnknownHostException e) { | |
| 621 | - throw new RuntimeException(e); | |
| 622 | - } | |
| 623 | - } | |
| 624 | - | |
| 625 | - } | |
| 626 | - | |
| 627 | - | |
| 628 | - private void initKeyspace() { | |
| 629 | 608 | try { |
| 630 | - Cluster.Builder builder = Cluster.builder(); | |
| 631 | - | |
| 632 | - builder = configure(builder); | |
| 633 | - | |
| 634 | - cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 635 | - .withNettyOptions(TestUtils.nonQuietClusterCloseOptions) | |
| 636 | - .build(); | |
| 637 | - session = cluster.connect(); | |
| 638 | - keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet(); | |
| 639 | - session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); | |
| 640 | - | |
| 641 | - session.execute("USE " + keyspace); | |
| 642 | - for (String tableDef : getTableDefinitions()) { | |
| 643 | - try { | |
| 644 | - session.execute(tableDef); | |
| 645 | - } catch (AlreadyExistsException e) { | |
| 646 | - // It's ok, ignore | |
| 647 | - } | |
| 648 | - } | |
| 649 | - } catch (AlreadyExistsException e) { | |
| 650 | - // It's ok, ignore (not supposed to go there) | |
| 651 | - } catch (NoHostAvailableException e) { | |
| 652 | - erroredOut = true; | |
| 653 | - for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet()) | |
| 654 | - logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue()); | |
| 655 | - throw new RuntimeException(e); | |
| 656 | - } catch (DriverException e) { | |
| 657 | - erroredOut = true; | |
| 658 | - throw e; | |
| 659 | - } | |
| 660 | - } | |
| 661 | - | |
| 662 | - private void clearSimpleKeyspace() { | |
| 663 | - if (keyspace != null) { | |
| 664 | - logger.debug("Removing keyspace {}.", keyspace); | |
| 665 | - // Temporarily extend read timeout to 1 minute to accommodate dropping keyspaces and | |
| 666 | - // tables being slow, particularly in a CI environment. | |
| 667 | - int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis(); | |
| 668 | - cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000); | |
| 669 | - try { | |
| 670 | - KeyspaceMetadata ksm = cluster.getMetadata().getKeyspace(keyspace); | |
| 671 | - if (ksm != null) { | |
| 672 | - // drop each table individually as this seems to be more dependable than dropping | |
| 673 | - // the entire keyspace at once if it has many tables. | |
| 674 | - if (ksm.getTables().size() > 10) { | |
| 675 | - for (TableMetadata table : ksm.getTables()) { | |
| 676 | - logger.debug("Dropping table {}.{}.", keyspace, table.getName()); | |
| 677 | - session.execute("DROP TABLE " + keyspace + "." + table.getName()); | |
| 678 | - } | |
| 679 | - } | |
| 680 | - } | |
| 681 | - logger.debug("Dropping keyspace {}.", keyspace); | |
| 682 | - session.execute("DROP KEYSPACE " + keyspace); | |
| 683 | - } finally { | |
| 684 | - cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout); | |
| 685 | - } | |
| 609 | + closer.close(); | |
| 610 | + } catch (IOException e) { | |
| 611 | + logger.warn("Failure closing streams.", e); | |
| 686 | 612 | } |
| 687 | 613 | } |
| 614 | + return f; | |
| 688 | 615 | } |
| 689 | 616 | |
| 690 | - public static class CCMCluster { | |
| 691 | - | |
| 692 | - public final Cluster cluster; | |
| 693 | - public final Session session; | |
| 694 | - | |
| 695 | - public final CCMBridge cassandraCluster; | |
| 696 | - | |
| 697 | - private boolean erroredOut; | |
| 698 | - | |
| 699 | - public static CCMCluster create(int nbNodes, Cluster.Builder builder) { | |
| 700 | - if (nbNodes == 0) | |
| 701 | - throw new IllegalArgumentException(); | |
| 702 | - | |
| 703 | - CCMBridge ccm = CCMBridge.builder("test").withNodes(nbNodes).build(); | |
| 704 | - return new CCMCluster(ccm, builder, nbNodes); | |
| 705 | - } | |
| 706 | - | |
| 707 | - public static CCMCluster create(int nbNodesDC1, int nbNodesDC2, Cluster.Builder builder) { | |
| 708 | - if (nbNodesDC1 == 0) | |
| 709 | - throw new IllegalArgumentException(); | |
| 710 | - | |
| 711 | - CCMBridge ccm = CCMBridge.builder("test").withNodes(nbNodesDC1, nbNodesDC2).build(); | |
| 712 | - return new CCMCluster(ccm, builder, nbNodesDC1 + nbNodesDC2); | |
| 713 | - } | |
| 714 | - | |
| 715 | - public static CCMCluster create(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) { | |
| 716 | - return new CCMCluster(cassandraCluster, builder, totalNodes); | |
| 717 | - } | |
| 718 | - | |
| 719 | - private CCMCluster(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) { | |
| 720 | - this.cassandraCluster = cassandraCluster; | |
| 721 | - try { | |
| 722 | - String[] contactPoints = new String[totalNodes]; | |
| 723 | - for (int i = 0; i < totalNodes; i++) | |
| 724 | - contactPoints[i] = IP_PREFIX + (i + 1); | |
| 725 | - | |
| 726 | - try { | |
| 727 | - Thread.sleep(1000); | |
| 728 | - } catch (InterruptedException e) { | |
| 729 | - fail("Unexpected interruption"); | |
| 730 | - } | |
| 731 | - this.cluster = builder.addContactPoints(contactPoints).build(); | |
| 732 | - this.session = cluster.connect(); | |
| 733 | - } catch (NoHostAvailableException e) { | |
| 734 | - for (Map.Entry<InetSocketAddress, Throwable> entry : e.getErrors().entrySet()) | |
| 735 | - logger.info("Error connecting to " + entry.getKey() + ": " + entry.getValue()); | |
| 736 | - discard(); | |
| 737 | - throw new RuntimeException(e); | |
| 738 | - } | |
| 739 | - } | |
| 740 | - | |
| 741 | - public void errorOut() { | |
| 742 | - erroredOut = true; | |
| 743 | - } | |
| 744 | - | |
| 745 | - public void discard() { | |
| 746 | - if (cluster != null) | |
| 747 | - cluster.close(); | |
| 748 | - | |
| 749 | - if (cassandraCluster == null) { | |
| 750 | - logger.error("No cluster to discard"); | |
| 751 | - } else if (erroredOut) { | |
| 752 | - cassandraCluster.stop(); | |
| 753 | - logger.info("Error during tests, kept C* logs in " + cassandraCluster.ccmDir); | |
| 754 | - } else { | |
| 755 | - cassandraCluster.remove(); | |
| 756 | - cassandraCluster.ccmDir.delete(); | |
| 757 | - } | |
| 758 | - } | |
| 617 | + @Override | |
| 618 | + public String toString() { | |
| 619 | + return "CCM cluster " + clusterName; | |
| 759 | 620 | } |
| 760 | 621 | |
| 761 | 622 | /** |
| 762 | - * use {@link #builder(String)} to get an instance | |
| 623 | + * use {@link #builder()} to get an instance | |
| 763 | 624 | */ |
| 764 | 625 | public static class Builder { |
| 765 | - private final String clusterName; | |
| 766 | - private Integer[] nodes = {1}; | |
| 626 | + private static final AtomicInteger COUNTER = new AtomicInteger(0); | |
| 627 | + private final String clusterName = "test_" + COUNTER.incrementAndGet(); | |
| 628 | + int[] nodes = {1}; | |
| 767 | 629 | private boolean start = true; |
| 768 | - private boolean isDSE = IS_DSE; | |
| 769 | - private String cassandraInstallArgs = CASSANDRA_INSTALL_ARGS; | |
| 770 | - private String[] startOptions = new String[0]; | |
| 771 | - | |
| 772 | - private Map<String, String> cassandraConfiguration = Maps.newHashMap(); | |
| 773 | - | |
| 774 | - private Map<String, String> dseConfiguration = Maps.newHashMap(); | |
| 775 | - | |
| 776 | - | |
| 777 | - Builder(String clusterName) { | |
| 778 | - this.clusterName = clusterName; | |
| 630 | + private boolean isDSE = isDSE(); | |
| 631 | + private String cassandraVersion = getCassandraVersion(); | |
| 632 | + private Set<String> createOptions = new LinkedHashSet<String>(); | |
| 633 | + private Set<String> jvmArgs = new LinkedHashSet<String>(); | |
| 634 | + private final Map<String, Object> cassandraConfiguration = Maps.newHashMap(); | |
| 635 | + private final Map<String, Object> dseConfiguration = Maps.newHashMap(); | |
| 636 | + // -1 means random | |
| 637 | + private int thriftPort = -1; | |
| 638 | + private int binaryPort = -1; | |
| 639 | + private int storagePort = -1; | |
| 640 | + | |
| 641 | + private Builder() { | |
| 779 | 642 | } |
| 780 | 643 | |
| 781 | 644 | /** |
| 782 | - * Number of nodes for each DC. Defaults to [1] (1 DC with 1 node) | |
| 645 | + * Number of hosts for each DC. Defaults to [1] (1 DC with 1 node) | |
| 783 | 646 | */ |
| 784 | - public Builder withNodes(Integer... nodes) { | |
| 647 | + public Builder withNodes(int... nodes) { | |
| 785 | 648 | this.nodes = nodes; |
| 786 | 649 | return this; |
| 787 | 650 | } |
| @@ -790,21 +653,30 @@ | ||
| 790 | 653 | return withNodes(); |
| 791 | 654 | } |
| 792 | 655 | |
| 793 | - public Builder withSSL(boolean requireClientAuth) { | |
| 656 | + /** | |
| 657 | + * Enables SSL encryption. | |
| 658 | + */ | |
| 659 | + public Builder withSSL() { | |
| 794 | 660 | cassandraConfiguration.put("client_encryption_options.enabled", "true"); |
| 795 | 661 | cassandraConfiguration.put("client_encryption_options.keystore", DEFAULT_SERVER_KEYSTORE_FILE.getAbsolutePath()); |
| 796 | 662 | cassandraConfiguration.put("client_encryption_options.keystore_password", DEFAULT_SERVER_KEYSTORE_PASSWORD); |
| 663 | + return this; | |
| 664 | + } | |
| 797 | 665 | |
| 798 | - if (requireClientAuth) { | |
| 799 | - cassandraConfiguration.put("client_encryption_options.require_client_auth", "true"); | |
| 800 | - cassandraConfiguration.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath()); | |
| 801 | - cassandraConfiguration.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD); | |
| 802 | - } | |
| 666 | + /** | |
| 667 | + * Enables client authentication. | |
| 668 | + * This also enables encryption ({@link #withSSL()}. | |
| 669 | + */ | |
| 670 | + public Builder withAuth() { | |
| 671 | + withSSL(); | |
| 672 | + cassandraConfiguration.put("client_encryption_options.require_client_auth", "true"); | |
| 673 | + cassandraConfiguration.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath()); | |
| 674 | + cassandraConfiguration.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD); | |
| 803 | 675 | return this; |
| 804 | 676 | } |
| 805 | 677 | |
| 806 | 678 | /** |
| 807 | - * Whether to start the cluster immediately (defaults to true if this is never called) | |
| 679 | + * Whether to start the cluster immediately (defaults to true if this is never called). | |
| 808 | 680 | */ |
| 809 | 681 | public Builder notStarted() { |
| 810 | 682 | this.start = false; |
| @@ -812,46 +684,96 @@ | ||
| 812 | 684 | } |
| 813 | 685 | |
| 814 | 686 | /** |
| 815 | - * Defaults to system property cassandra.version | |
| 687 | + * Sets this cluster to be a DSE cluster (defaults to {@link #isDSE()} if this is never called). | |
| 816 | 688 | */ |
| 817 | - public Builder withCassandraVersion(String cassandraVersion) { | |
| 818 | - this.cassandraInstallArgs = "-v " + cassandraVersion; | |
| 819 | - this.isDSE = false; | |
| 689 | + public Builder withDSE() { | |
| 690 | + this.isDSE = true; | |
| 820 | 691 | return this; |
| 821 | 692 | } |
| 822 | 693 | |
| 823 | - public Builder withDSEVersion(String dseVersion) { | |
| 824 | - this.cassandraInstallArgs = "-v " + dseVersion + " --dse"; | |
| 825 | - this.isDSE = true; | |
| 694 | + /** | |
| 695 | + * The Cassandra or DSE version to use. | |
| 696 | + * | |
| 697 | + * Defaults to {@link #getCassandraVersion()}. | |
| 698 | + */ | |
| 699 | + public Builder withVersion(String cassandraVersion) { | |
| 700 | + this.cassandraVersion = cassandraVersion; | |
| 826 | 701 | return this; |
| 827 | 702 | } |
| 828 | 703 | |
| 829 | 704 | /** |
| 830 | - * Free-form options that will be added at the end of the start command | |
| 705 | + * Free-form options that will be added at the end of the {@code ccm create} command. | |
| 831 | 706 | */ |
| 832 | - public Builder withStartOptions(String... options) { | |
| 833 | - this.startOptions = options; | |
| 707 | + public Builder withCreateOptions(String... createOptions) { | |
| 708 | + Collections.addAll(this.createOptions, createOptions); | |
| 834 | 709 | return this; |
| 835 | 710 | } |
| 836 | 711 | |
| 837 | 712 | /** |
| 838 | 713 | * Customizes entries in cassandra.yaml (can be called multiple times) |
| 839 | 714 | */ |
| 840 | - public Builder withCassandraConfiguration(String key, String value) { | |
| 715 | + public Builder withCassandraConfiguration(String key, Object value) { | |
| 841 | 716 | this.cassandraConfiguration.put(key, value); |
| 842 | 717 | return this; |
| 843 | 718 | } |
| 844 | 719 | |
| 845 | - public Builder withDSEConfiguration(String key, String value) { | |
| 720 | + /** | |
| 721 | + * Customizes entries in dse.yaml (can be called multiple times) | |
| 722 | + */ | |
| 723 | + public Builder withDSEConfiguration(String key, Object value) { | |
| 846 | 724 | this.dseConfiguration.put(key, value); |
| 847 | 725 | return this; |
| 848 | 726 | } |
| 849 | 727 | |
| 728 | + /** | |
| 729 | + * JVM args to use when starting hosts. | |
| 730 | + * System properties should be provided one by one, as a string in the form: | |
| 731 | + * {@code -Dname=value}. | |
| 732 | + */ | |
| 733 | + public Builder withJvmArgs(String... jvmArgs) { | |
| 734 | + Collections.addAll(this.jvmArgs, jvmArgs); | |
| 735 | + return this; | |
| 736 | + } | |
| 737 | + | |
| 738 | + public Builder withStoragePort(int port) { | |
| 739 | + storagePort = port; | |
| 740 | + return this; | |
| 741 | + } | |
| 742 | + | |
| 743 | + public Builder withThriftPort(int port) { | |
| 744 | + thriftPort = port; | |
| 745 | + return this; | |
| 746 | + } | |
| 747 | + | |
| 748 | + public Builder withBinaryPort(int port) { | |
| 749 | + binaryPort = port; | |
| 750 | + return this; | |
| 751 | + } | |
| 752 | + | |
| 850 | 753 | public CCMBridge build() { |
| 851 | - CCMBridge ccm = new CCMBridge(isDSE); | |
| 754 | + // be careful NOT to alter internal state (hashCode/equals) during build! | |
| 755 | + int initialNumberOfNodes = 0; | |
| 756 | + for (int nodesPerDc : nodes) { | |
| 757 | + initialNumberOfNodes += nodesPerDc; | |
| 758 | + } | |
| 759 | + int storagePort = this.storagePort == -1 ? findAvailablePort() : this.storagePort; | |
| 760 | + int thriftPort = this.thriftPort == -1 ? findAvailablePort() : this.thriftPort; | |
| 761 | + int binaryPort = this.binaryPort == -1 ? findAvailablePort() : this.binaryPort; | |
| 762 | + VersionNumber version = VersionNumber.parse(cassandraVersion); | |
| 763 | + final CCMBridge ccm = new CCMBridge(clusterName, isDSE, version, storagePort, thriftPort, binaryPort, joinJvmArgs(), initialNumberOfNodes); | |
| 764 | + Runtime.getRuntime().addShutdownHook(new Thread() { | |
| 765 | + @Override | |
| 766 | + public void run() { | |
| 767 | + ccm.close(); | |
| 768 | + } | |
| 769 | + }); | |
| 852 | 770 | ccm.execute(buildCreateCommand()); |
| 853 | - if (!cassandraConfiguration.isEmpty()) | |
| 854 | - ccm.updateConfig(cassandraConfiguration); | |
| 771 | + updateNodeConf(ccm); | |
| 772 | + HashMap<String, Object> config = new HashMap<String, Object>(cassandraConfiguration); | |
| 773 | + config.put("storage_port", storagePort); | |
| 774 | + config.put("rpc_port", thriftPort); | |
| 775 | + config.put("native_transport_port", binaryPort); | |
| 776 | + ccm.updateConfig(config); | |
| 855 | 777 | if (!dseConfiguration.isEmpty()) |
| 856 | 778 | ccm.updateDSEConfig(dseConfiguration); |
| 857 | 779 | if (start) |
| @@ -859,16 +781,123 @@ | ||
| 859 | 781 | return ccm; |
| 860 | 782 | } |
| 861 | 783 | |
| 784 | + private String joinJvmArgs() { | |
| 785 | + StringBuilder allJvmArgs = new StringBuilder(""); | |
| 786 | + for (String jvmArg : jvmArgs) { | |
| 787 | + allJvmArgs.append(" --jvm_arg="); | |
| 788 | + allJvmArgs.append(jvmArg); | |
| 789 | + } | |
| 790 | + return allJvmArgs.toString(); | |
| 791 | + } | |
| 792 | + | |
| 862 | 793 | private String buildCreateCommand() { |
| 863 | 794 | StringBuilder result = new StringBuilder(CCM_COMMAND + " create"); |
| 864 | - result.append(" " + clusterName); | |
| 865 | - result.append(" -i" + IP_PREFIX); | |
| 866 | - result.append(" " + cassandraInstallArgs); | |
| 867 | - if (nodes.length > 0) | |
| 868 | - result.append(" -n " + Joiner.on(":").join(nodes)); | |
| 869 | - if (startOptions.length > 0) | |
| 870 | - result.append(" " + Joiner.on(" ").join(startOptions)); | |
| 795 | + result.append(" ").append(clusterName); | |
| 796 | + result.append(" -i ").append(TestUtils.IP_PREFIX); | |
| 797 | + result.append(" "); | |
| 798 | + if (cassandraVersion != null) | |
| 799 | + result.append("-v ").append(cassandraVersion); | |
| 800 | + else | |
| 801 | + result.append(CASSANDRA_INSTALL_ARGS); | |
| 802 | + if (nodes.length > 0) { | |
| 803 | + result.append(" -n "); | |
| 804 | + for (int i = 0; i < nodes.length; i++) { | |
| 805 | + int node = nodes[i]; | |
| 806 | + if (i > 0) | |
| 807 | + result.append(':'); | |
| 808 | + result.append(node); | |
| 809 | + } | |
| 810 | + } | |
| 811 | + if (!createOptions.isEmpty()) | |
| 812 | + result.append(" ").append(Joiner.on(" ").join(createOptions)); | |
| 871 | 813 | return result.toString(); |
| 872 | 814 | } |
| 815 | + | |
| 816 | + /** | |
| 817 | + * This is a workaround for an oddity in CCM: | |
| 818 | + * when we create a cluster with -n option and | |
| 819 | + * non-standard ports, the node.conf files are not updated accordingly. | |
| 820 | + */ | |
| 821 | + private void updateNodeConf(CCMBridge ccm) { | |
| 822 | + int n = 1; | |
| 823 | + Closer closer = Closer.create(); | |
| 824 | + try { | |
| 825 | + for (int dc = 1; dc <= nodes.length; dc++) { | |
| 826 | + int nodesInDc = nodes[dc - 1]; | |
| 827 | + for (int i = 0; i < nodesInDc; i++) { | |
| 828 | + int jmxPort = findAvailablePort(); | |
| 829 | + int debugPort = findAvailablePort(); | |
| 830 | + logger.debug("Node {} in cluster {} using JMX port {} and debug port {}", n, clusterName, jmxPort, debugPort); | |
| 831 | + File nodeConf = new File(ccm.getNodeDir(n), "node.conf"); | |
| 832 | + File nodeConf2 = new File(ccm.getNodeDir(n), "node.conf.tmp"); | |
| 833 | + BufferedReader br = closer.register(new BufferedReader(new FileReader(nodeConf))); | |
| 834 | + PrintWriter pw = closer.register(new PrintWriter(new FileWriter(nodeConf2))); | |
| 835 | + String line; | |
| 836 | + while ((line = br.readLine()) != null) { | |
| 837 | + line = line | |
| 838 | + .replace("9042", Integer.toString(ccm.binaryPort)) | |
| 839 | + .replace("9160", Integer.toString(ccm.thriftPort)) | |
| 840 | + .replace("7000", Integer.toString(ccm.storagePort)); | |
| 841 | + if (line.startsWith("jmx_port")) { | |
| 842 | + line = String.format("jmx_port: '%s'", jmxPort); | |
| 843 | + } else if (line.startsWith("remote_debug_port")) { | |
| 844 | + line = String.format("remote_debug_port: %s:%s", TestUtils.ipOfNode(n), debugPort); | |
| 845 | + } | |
| 846 | + pw.println(line); | |
| 847 | + } | |
| 848 | + pw.flush(); | |
| 849 | + pw.close(); | |
| 850 | + Files.move(nodeConf2, nodeConf); | |
| 851 | + n++; | |
| 852 | + } | |
| 853 | + } | |
| 854 | + } catch (IOException e) { | |
| 855 | + Throwables.propagate(e); | |
| 856 | + } finally { | |
| 857 | + try { | |
| 858 | + closer.close(); | |
| 859 | + } catch (IOException e) { | |
| 860 | + Throwables.propagate(e); | |
| 861 | + } | |
| 862 | + } | |
| 863 | + } | |
| 864 | + | |
| 865 | + @Override | |
| 866 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 867 | + public boolean equals(Object o) { | |
| 868 | + // do not include cluster name and start, only | |
| 869 | + // properties relevant to the settings of the cluster | |
| 870 | + if (this == o) return true; | |
| 871 | + if (o == null || getClass() != o.getClass()) return false; | |
| 872 | + Builder builder = (Builder) o; | |
| 873 | + if (isDSE != builder.isDSE) return false; | |
| 874 | + if (thriftPort != builder.thriftPort) return false; | |
| 875 | + if (binaryPort != builder.binaryPort) return false; | |
| 876 | + if (storagePort != builder.storagePort) return false; | |
| 877 | + if (!Arrays.equals(nodes, builder.nodes)) return false; | |
| 878 | + if (!createOptions.equals(builder.createOptions)) return false; | |
| 879 | + if (!jvmArgs.equals(builder.jvmArgs)) return false; | |
| 880 | + if (!dseConfiguration.equals(builder.dseConfiguration)) return false; | |
| 881 | + if (!cassandraConfiguration.equals(builder.cassandraConfiguration)) return false; | |
| 882 | + return cassandraVersion.equals(builder.cassandraVersion); | |
| 883 | + } | |
| 884 | + | |
| 885 | + @Override | |
| 886 | + public int hashCode() { | |
| 887 | + // do not include cluster name and start, only | |
| 888 | + // properties relevant to the settings of the cluster | |
| 889 | + int result = Arrays.hashCode(nodes); | |
| 890 | + result = 31 * result + (isDSE ? 1 : 0); | |
| 891 | + result = 31 * result + createOptions.hashCode(); | |
| 892 | + result = 31 * result + jvmArgs.hashCode(); | |
| 893 | + result = 31 * result + cassandraConfiguration.hashCode(); | |
| 894 | + result = 31 * result + dseConfiguration.hashCode(); | |
| 895 | + result = 31 * result + thriftPort; | |
| 896 | + result = 31 * result + binaryPort; | |
| 897 | + result = 31 * result + storagePort; | |
| 898 | + result = 31 * result + cassandraVersion.hashCode(); | |
| 899 | + return result; | |
| 900 | + } | |
| 873 | 901 | } |
| 902 | + | |
| 874 | 903 | } |
added driver-core/src/test/java/com/datastax/driver/core/CCMConfig.java +240 −0
| @@ -0,0 +1,240 @@ | ||
| 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.lang.annotation.Retention; | |
| 19 | +import java.lang.annotation.Target; | |
| 20 | + | |
| 21 | +import static java.lang.annotation.ElementType.METHOD; | |
| 22 | +import static java.lang.annotation.ElementType.TYPE; | |
| 23 | +import static java.lang.annotation.RetentionPolicy.RUNTIME; | |
| 24 | + | |
| 25 | +/** | |
| 26 | + * The configuration to use when running tests with {@link CCMTestsSupport}. | |
| 27 | + */ | |
| 28 | +@Retention(RUNTIME) | |
| 29 | +@Target({TYPE, METHOD}) | |
| 30 | +public @interface CCMConfig { | |
| 31 | + | |
| 32 | + final class Undefined { | |
| 33 | + } | |
| 34 | + | |
| 35 | + /** | |
| 36 | + * The number of nodes to create, per data center. | |
| 37 | + * If not set, this defaults to {1}, i.e., one data center with one node. | |
| 38 | + * | |
| 39 | + * @return The number of nodes to create, per data center. | |
| 40 | + */ | |
| 41 | + int[] numberOfNodes() default {}; | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * The C* or DSE version to use; defaults to the version defined by | |
| 45 | + * the System property {@code cassandra.version}. | |
| 46 | + * | |
| 47 | + * @return The C* or DSE version to use | |
| 48 | + * @see CCMBridge#getCassandraVersion() | |
| 49 | + */ | |
| 50 | + String version() default ""; | |
| 51 | + | |
| 52 | + /** | |
| 53 | + * Whether to launch a DSE instance rather than an OSS C*. | |
| 54 | + * | |
| 55 | + * @return {@code true} to launch a DSE instance, {@code false} to launch an OSS C* instance (default). | |
| 56 | + */ | |
| 57 | + boolean[] dse() default {}; | |
| 58 | + | |
| 59 | + /** | |
| 60 | + * Configuration items to add to cassandra.yaml configuration file. | |
| 61 | + * Each configuration item must be in the form {@code key:value}. | |
| 62 | + * | |
| 63 | + * @return Configuration items to add to cassandra.yaml configuration file. | |
| 64 | + */ | |
| 65 | + String[] config() default {}; | |
| 66 | + | |
| 67 | + /** | |
| 68 | + * Configuration items to add to dse.yaml configuration file. | |
| 69 | + * Each configuration item must be in the form {@code key:value}. | |
| 70 | + * | |
| 71 | + * @return Configuration items to add to dse.yaml configuration file. | |
| 72 | + */ | |
| 73 | + String[] dseConfig() default {}; | |
| 74 | + | |
| 75 | + /** | |
| 76 | + * JVM args to use when starting hosts. | |
| 77 | + * System properties should be provided one by one, in the form | |
| 78 | + * {@code -Dname=value}. | |
| 79 | + * | |
| 80 | + * @return JVM args to use when starting hosts. | |
| 81 | + */ | |
| 82 | + String[] jvmArgs() default {}; | |
| 83 | + | |
| 84 | + /** | |
| 85 | + * Free-form options that will be added at the end of the {@code ccm create} command. | |
| 86 | + * | |
| 87 | + * @return Free-form options that will be added at the end of the {@code ccm create} command. | |
| 88 | + */ | |
| 89 | + String[] options() default {}; | |
| 90 | + | |
| 91 | + /** | |
| 92 | + * Whether to use SSL encryption. | |
| 93 | + * | |
| 94 | + * @return {@code true} to use encryption, {@code false} to use unencrypted communication (default). | |
| 95 | + */ | |
| 96 | + boolean[] ssl() default {}; | |
| 97 | + | |
| 98 | + /** | |
| 99 | + * Whether to use authentication. Implies the use of SSL encryption. | |
| 100 | + * | |
| 101 | + * @return {@code true} to use authentication, {@code false} to use unauthenticated communication (default). | |
| 102 | + */ | |
| 103 | + boolean[] auth() default {}; | |
| 104 | + | |
| 105 | + /** | |
| 106 | + * Returns {@code true} if a {@link CCMBridge} instance should be automatically created, {@code false} otherwise. | |
| 107 | + * <p/> | |
| 108 | + * If {@code true}, a CCM cluster builder will be created or retrieved from the cache. | |
| 109 | + * If {@code false}, no CCM cluster will be activated for this test; this can be useful | |
| 110 | + * when some tests in a test class require CCM, while others don't but are in one of the allowed | |
| 111 | + * CCM test groups ("short" for example). | |
| 112 | + * <p/> | |
| 113 | + * The cluster will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS}, | |
| 114 | + * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD}, | |
| 115 | + * | |
| 116 | + * @return {@code true} if a {@link Cluster} instance should be automatically created, {@code false} otherwise. | |
| 117 | + */ | |
| 118 | + boolean[] createCcm() default {}; | |
| 119 | + | |
| 120 | + /** | |
| 121 | + * Returns {@code true} if a {@link Cluster} instance should be automatically created, {@code false} otherwise. | |
| 122 | + * <p/> | |
| 123 | + * If {@code true}, a cluster builder will be obtained by invoking the method | |
| 124 | + * specified by {@link #clusterProvider()} and {@link #clusterProviderClass()}. | |
| 125 | + * <p/> | |
| 126 | + * The CCM cluster will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS}, | |
| 127 | + * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD}, | |
| 128 | + * | |
| 129 | + * @return {@code true} if a {@link Cluster} instance should be automatically created, {@code false} otherwise. | |
| 130 | + */ | |
| 131 | + boolean[] createCluster() default {}; | |
| 132 | + | |
| 133 | + /** | |
| 134 | + * Returns {@code true} if a {@link Session} instance should be automatically created, {@code false} otherwise. | |
| 135 | + * <p/> | |
| 136 | + * If {@code true}, a cluster builder will be obtained by invoking the method | |
| 137 | + * specified by {@link #clusterProvider()} and {@link #clusterProviderClass()}, | |
| 138 | + * and then the session will be created through {@link Cluster#connect()}. | |
| 139 | + * <p/> | |
| 140 | + * The session will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS}, | |
| 141 | + * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD}, | |
| 142 | + * | |
| 143 | + * @return {@code true} if a {@link Session} instance should be automatically created, {@code false} otherwise. | |
| 144 | + */ | |
| 145 | + boolean[] createSession() default {}; | |
| 146 | + | |
| 147 | + /** | |
| 148 | + * Returns {@code true} if a test keyspace should be automatically created, {@code false} otherwise. | |
| 149 | + * <p/> | |
| 150 | + * If {@code true}, a cluster builder will be obtained by invoking the method | |
| 151 | + * specified by {@link #clusterProvider()} and {@link #clusterProviderClass()}, | |
| 152 | + * then a session will be created through {@link Cluster#connect()}, | |
| 153 | + * and this session will be used to create the test keyspace. | |
| 154 | + * <p/> | |
| 155 | + * The keyspace will be created once for the whole class if CCM test mode is {@link CreateCCM.TestMode#PER_CLASS}, | |
| 156 | + * or once per test method, if the CCM test mode is {@link CreateCCM.TestMode#PER_METHOD}, | |
| 157 | + * <p/> | |
| 158 | + * The test keyspace will be automatically populated upon creation with fixtures provided by | |
| 159 | + * {@link #fixturesProvider()} and {@link #fixturesProviderClass()}. | |
| 160 | + * | |
| 161 | + * @return {@code true} if a test keyspace should be automatically created, {@code false} otherwise. | |
| 162 | + */ | |
| 163 | + boolean[] createKeyspace() default {}; | |
| 164 | + | |
| 165 | + /** | |
| 166 | + * Returns {@code true} if the test class or the test method alters the CCM cluster, | |
| 167 | + * e.g. by adding or removing nodes, | |
| 168 | + * in which case, it should not be reused after the test is finished. | |
| 169 | + * <p/> | |
| 170 | + * If {@code true}, CCM cluster will be destroyed after the test method if test mode is | |
| 171 | + * {@link CreateCCM.TestMode#PER_METHOD}, or after the test class, if test mode | |
| 172 | + * is {@link CreateCCM.TestMode#PER_CLASS}. | |
| 173 | + * | |
| 174 | + * @return {@code true} if the test class or the test method alters the CCM cluster used, | |
| 175 | + * {@code false} otherwise. | |
| 176 | + */ | |
| 177 | + boolean[] dirtiesContext() default {}; | |
| 178 | + | |
| 179 | + /** | |
| 180 | + * Returns the name of the method that should be invoked to obtain | |
| 181 | + * a {@link com.datastax.driver.core.Cluster.Builder} instance. | |
| 182 | + * <p/> | |
| 183 | + * This method should be declared in {@link #clusterProviderClass()}, | |
| 184 | + * or if that property is not set, | |
| 185 | + * it will be looked up on the test class itself. | |
| 186 | + * <p/> | |
| 187 | + * The method should not have parameters. It can be static or not, | |
| 188 | + * and have any visibility. | |
| 189 | + * <p/> | |
| 190 | + * By default, the test will look for a method named after {@code createClusterBuilder}. | |
| 191 | + * | |
| 192 | + * @return The name of the method that should be invoked to obtain a | |
| 193 | + * {@link com.datastax.driver.core.Cluster.Builder} instance. | |
| 194 | + */ | |
| 195 | + String clusterProvider() default ""; | |
| 196 | + | |
| 197 | + /** | |
| 198 | + * Returns the name of the class that should be invoked to obtain | |
| 199 | + * a {@link com.datastax.driver.core.Cluster.Builder} instance. | |
| 200 | + * <p/> | |
| 201 | + * This class should contain a method named after {@link #clusterProvider()}; | |
| 202 | + * if this property is not set, | |
| 203 | + * it will default to the test class itself. | |
| 204 | + * | |
| 205 | + * @return The name of the class that should be invoked to obtain a | |
| 206 | + * {@link com.datastax.driver.core.Cluster.Builder} instance. | |
| 207 | + */ | |
| 208 | + Class<?> clusterProviderClass() default Undefined.class; | |
| 209 | + | |
| 210 | + /** | |
| 211 | + * Returns the name of the method that should be invoked to obtain | |
| 212 | + * the test fixtures to use. | |
| 213 | + * <p/> | |
| 214 | + * This method should return {@code Collection<String>}. | |
| 215 | + * <p/> | |
| 216 | + * This method should be declared in {@link #fixturesProviderClass()}, | |
| 217 | + * or if that property is not set, | |
| 218 | + * it will be looked up on the test class itself. | |
| 219 | + * <p/> | |
| 220 | + * The method should not have parameters. It can be static or not, | |
| 221 | + * and have any visibility. | |
| 222 | + * | |
| 223 | + * @return The name of the method that should be invoked to obtain the test fixtures to use. | |
| 224 | + */ | |
| 225 | + String fixturesProvider() default ""; | |
| 226 | + | |
| 227 | + /** | |
| 228 | + * Returns the name of the class that should be invoked to obtain | |
| 229 | + * the test fixtures to use. | |
| 230 | + * <p/> | |
| 231 | + * This class should contain a method named after {@link #fixturesProvider()}; | |
| 232 | + * if this property is not set, | |
| 233 | + * it will default to the test class itself. | |
| 234 | + * | |
| 235 | + * @return The name of the class that should be invoked to obtain a | |
| 236 | + * {@link com.datastax.driver.core.Cluster.Builder} instance. | |
| 237 | + */ | |
| 238 | + Class<?> fixturesProviderClass() default Undefined.class; | |
| 239 | + | |
| 240 | +} |
added driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +749 −0
| @@ -0,0 +1,749 @@ | ||
| 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 com.datastax.driver.core.CreateCCM.TestMode; | |
| 19 | +import com.datastax.driver.core.policies.AddressTranslater; | |
| 20 | +import com.google.common.base.Throwables; | |
| 21 | +import com.google.common.cache.*; | |
| 22 | +import com.google.common.collect.Lists; | |
| 23 | +import com.google.common.io.Closer; | |
| 24 | +import org.slf4j.Logger; | |
| 25 | +import org.slf4j.LoggerFactory; | |
| 26 | +import org.testng.ITestResult; | |
| 27 | +import org.testng.annotations.*; | |
| 28 | + | |
| 29 | +import java.io.Closeable; | |
| 30 | +import java.io.IOException; | |
| 31 | +import java.lang.annotation.Annotation; | |
| 32 | +import java.lang.reflect.Constructor; | |
| 33 | +import java.lang.reflect.Method; | |
| 34 | +import java.lang.reflect.Modifier; | |
| 35 | +import java.lang.reflect.ParameterizedType; | |
| 36 | +import java.net.InetSocketAddress; | |
| 37 | +import java.util.*; | |
| 38 | +import java.util.concurrent.Callable; | |
| 39 | +import java.util.concurrent.ExecutionException; | |
| 40 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 41 | + | |
| 42 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_CLASS; | |
| 43 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 44 | +import static com.datastax.driver.core.TestUtils.*; | |
| 45 | + | |
| 46 | +@SuppressWarnings("unused") | |
| 47 | +public class CCMTestsSupport { | |
| 48 | + | |
| 49 | + private static final Logger LOGGER = LoggerFactory.getLogger(CCMTestsSupport.class); | |
| 50 | + | |
| 51 | + private static final AtomicInteger CCM_COUNTER = new AtomicInteger(1); | |
| 52 | + | |
| 53 | + private static final List<String> TEST_GROUPS = Lists.newArrayList("isolated", "short", "long", "stress", "duration"); | |
| 54 | + | |
| 55 | + private static class CCMTestConfig { | |
| 56 | + | |
| 57 | + private final List<CCMConfig> annotations; | |
| 58 | + | |
| 59 | + private CCMBridge.Builder ccmBuilder; | |
| 60 | + | |
| 61 | + public CCMTestConfig(List<CCMConfig> annotations) { | |
| 62 | + this.annotations = annotations; | |
| 63 | + } | |
| 64 | + | |
| 65 | + private int[] numberOfNodes() { | |
| 66 | + for (CCMConfig ann : annotations) { | |
| 67 | + if (ann != null && ann.numberOfNodes().length > 0) | |
| 68 | + return ann.numberOfNodes(); | |
| 69 | + } | |
| 70 | + return new int[]{1}; | |
| 71 | + } | |
| 72 | + | |
| 73 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 74 | + private String version() { | |
| 75 | + for (CCMConfig ann : annotations) { | |
| 76 | + if (ann != null && !ann.version().isEmpty()) | |
| 77 | + return ann.version(); | |
| 78 | + } | |
| 79 | + return null; | |
| 80 | + } | |
| 81 | + | |
| 82 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 83 | + private boolean dse() { | |
| 84 | + for (CCMConfig ann : annotations) { | |
| 85 | + if (ann != null && ann.dse().length > 0) | |
| 86 | + return ann.dse()[0]; | |
| 87 | + } | |
| 88 | + return false; | |
| 89 | + } | |
| 90 | + | |
| 91 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 92 | + private boolean ssl() { | |
| 93 | + for (CCMConfig ann : annotations) { | |
| 94 | + if (ann != null && ann.ssl().length > 0) | |
| 95 | + return ann.ssl()[0]; | |
| 96 | + } | |
| 97 | + return false; | |
| 98 | + } | |
| 99 | + | |
| 100 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 101 | + private boolean auth() { | |
| 102 | + for (CCMConfig ann : annotations) { | |
| 103 | + if (ann != null && ann.auth().length > 0) | |
| 104 | + return ann.auth()[0]; | |
| 105 | + } | |
| 106 | + return false; | |
| 107 | + } | |
| 108 | + | |
| 109 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 110 | + private Map<String, Object> config() { | |
| 111 | + Map<String, Object> config = new HashMap<String, Object>(); | |
| 112 | + for (int i = annotations.size() - 1; i == 0; i--) { | |
| 113 | + CCMConfig ann = annotations.get(i); | |
| 114 | + addConfigOptions(ann.config(), config); | |
| 115 | + } | |
| 116 | + return config; | |
| 117 | + } | |
| 118 | + | |
| 119 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 120 | + private Map<String, Object> dseConfig() { | |
| 121 | + Map<String, Object> config = new HashMap<String, Object>(); | |
| 122 | + for (int i = annotations.size() - 1; i >= 0; i--) { | |
| 123 | + CCMConfig ann = annotations.get(i); | |
| 124 | + addConfigOptions(ann.dseConfig(), config); | |
| 125 | + } | |
| 126 | + return config; | |
| 127 | + } | |
| 128 | + | |
| 129 | + private void addConfigOptions(String[] conf, Map<String, Object> config) { | |
| 130 | + for (String aConf : conf) { | |
| 131 | + String[] tokens = aConf.split(":"); | |
| 132 | + String key = tokens[0]; | |
| 133 | + String value = tokens[1]; | |
| 134 | + config.put(key, value); | |
| 135 | + } | |
| 136 | + } | |
| 137 | + | |
| 138 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 139 | + private Set<String> jvmArgs() { | |
| 140 | + Set<String> args = new LinkedHashSet<String>(); | |
| 141 | + for (int i = annotations.size() - 1; i >= 0; i--) { | |
| 142 | + CCMConfig ann = annotations.get(i); | |
| 143 | + Collections.addAll(args, ann.jvmArgs()); | |
| 144 | + } | |
| 145 | + return args; | |
| 146 | + } | |
| 147 | + | |
| 148 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 149 | + private Set<String> startOptions() { | |
| 150 | + Set<String> args = new LinkedHashSet<String>(); | |
| 151 | + for (int i = annotations.size() - 1; i >= 0; i--) { | |
| 152 | + CCMConfig ann = annotations.get(i); | |
| 153 | + Collections.addAll(args, ann.options()); | |
| 154 | + } | |
| 155 | + return args; | |
| 156 | + } | |
| 157 | + | |
| 158 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 159 | + private boolean createCcm() { | |
| 160 | + for (CCMConfig ann : annotations) { | |
| 161 | + if (ann != null && ann.createCcm().length > 0) | |
| 162 | + return ann.createCcm()[0]; | |
| 163 | + } | |
| 164 | + return true; | |
| 165 | + } | |
| 166 | + | |
| 167 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 168 | + private boolean createCluster() { | |
| 169 | + for (CCMConfig ann : annotations) { | |
| 170 | + if (ann != null && ann.createCluster().length > 0) | |
| 171 | + return ann.createCluster()[0]; | |
| 172 | + } | |
| 173 | + return true; | |
| 174 | + } | |
| 175 | + | |
| 176 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 177 | + private boolean createSession() { | |
| 178 | + for (CCMConfig ann : annotations) { | |
| 179 | + if (ann != null && ann.createSession().length > 0) | |
| 180 | + return ann.createSession()[0]; | |
| 181 | + } | |
| 182 | + return true; | |
| 183 | + } | |
| 184 | + | |
| 185 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 186 | + private boolean createKeyspace() { | |
| 187 | + for (CCMConfig ann : annotations) { | |
| 188 | + if (ann != null && ann.createKeyspace().length > 0) | |
| 189 | + return ann.createKeyspace()[0]; | |
| 190 | + } | |
| 191 | + return true; | |
| 192 | + } | |
| 193 | + | |
| 194 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 195 | + private boolean dirtiesContext() { | |
| 196 | + for (CCMConfig ann : annotations) { | |
| 197 | + if (ann != null && ann.dirtiesContext().length > 0) | |
| 198 | + return ann.dirtiesContext()[0]; | |
| 199 | + } | |
| 200 | + return false; | |
| 201 | + } | |
| 202 | + | |
| 203 | + private CCMBridge.Builder ccmBuilder() { | |
| 204 | + if (ccmBuilder == null) { | |
| 205 | + ccmBuilder = CCMBridge.builder() | |
| 206 | + .withNodes(numberOfNodes()); | |
| 207 | + if (version() != null) | |
| 208 | + ccmBuilder.withVersion(version()); | |
| 209 | + if (dse()) | |
| 210 | + ccmBuilder.withDSE(); | |
| 211 | + if (ssl()) | |
| 212 | + ccmBuilder.withSSL(); | |
| 213 | + if (auth()) | |
| 214 | + ccmBuilder.withAuth(); | |
| 215 | + for (Map.Entry<String, Object> entry : config().entrySet()) { | |
| 216 | + ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue()); | |
| 217 | + } | |
| 218 | + for (Map.Entry<String, Object> entry : dseConfig().entrySet()) { | |
| 219 | + ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue()); | |
| 220 | + } | |
| 221 | + for (String option : startOptions()) { | |
| 222 | + ccmBuilder.withCreateOptions(option); | |
| 223 | + } | |
| 224 | + for (String arg : jvmArgs()) { | |
| 225 | + ccmBuilder.withJvmArgs(arg); | |
| 226 | + } | |
| 227 | + } | |
| 228 | + return ccmBuilder; | |
| 229 | + } | |
| 230 | + | |
| 231 | + private Cluster.Builder clusterBuilder(Object testInstance) throws Exception { | |
| 232 | + String methodName = null; | |
| 233 | + Class<?> clazz = null; | |
| 234 | + for (int i = annotations.size() - 1; i >= 0; i--) { | |
| 235 | + CCMConfig ann = annotations.get(i); | |
| 236 | + if (!ann.clusterProvider().isEmpty()) { | |
| 237 | + methodName = ann.clusterProvider(); | |
| 238 | + } | |
| 239 | + if (!ann.clusterProviderClass().equals(CCMConfig.Undefined.class)) { | |
| 240 | + clazz = ann.clusterProviderClass(); | |
| 241 | + } | |
| 242 | + } | |
| 243 | + if (methodName == null) | |
| 244 | + methodName = "createClusterBuilder"; | |
| 245 | + if (clazz == null) | |
| 246 | + clazz = testInstance.getClass(); | |
| 247 | + Method method = locateMethod(methodName, clazz); | |
| 248 | + assert Cluster.Builder.class.isAssignableFrom(method.getReturnType()); | |
| 249 | + if (Modifier.isStatic(method.getModifiers())) { | |
| 250 | + return (Cluster.Builder) method.invoke(null); | |
| 251 | + } else { | |
| 252 | + Object receiver = testInstance.getClass().equals(clazz) ? testInstance : instantiate(clazz); | |
| 253 | + return (Cluster.Builder) method.invoke(receiver); | |
| 254 | + } | |
| 255 | + } | |
| 256 | + | |
| 257 | + @SuppressWarnings("unchecked") | |
| 258 | + private Collection<String> fixtures(Object testInstance) throws Exception { | |
| 259 | + String methodName = null; | |
| 260 | + Class<?> clazz = null; | |
| 261 | + for (int i = annotations.size() - 1; i >= 0; i--) { | |
| 262 | + CCMConfig ann = annotations.get(i); | |
| 263 | + if (!ann.fixturesProvider().isEmpty()) { | |
| 264 | + methodName = ann.fixturesProvider(); | |
| 265 | + } | |
| 266 | + if (!ann.fixturesProviderClass().equals(CCMConfig.Undefined.class)) { | |
| 267 | + clazz = ann.fixturesProviderClass(); | |
| 268 | + } | |
| 269 | + } | |
| 270 | + if (methodName == null) | |
| 271 | + methodName = "createTestFixtures"; | |
| 272 | + if (clazz == null) | |
| 273 | + clazz = testInstance.getClass(); | |
| 274 | + Method method = locateMethod(methodName, clazz); | |
| 275 | + assert Collection.class.isAssignableFrom(method.getReturnType()); | |
| 276 | + assert method.getGenericReturnType() instanceof ParameterizedType; | |
| 277 | + assert String.class.equals(((ParameterizedType) method.getGenericReturnType()).getActualTypeArguments()[0]); | |
| 278 | + if (Modifier.isStatic(method.getModifiers())) { | |
| 279 | + return (Collection<String>) method.invoke(null); | |
| 280 | + } else { | |
| 281 | + Object receiver = testInstance.getClass().equals(clazz) ? testInstance : instantiate(clazz); | |
| 282 | + return (Collection<String>) method.invoke(receiver); | |
| 283 | + } | |
| 284 | + } | |
| 285 | + | |
| 286 | + } | |
| 287 | + | |
| 288 | + private static class CCMTestContextLoader extends CacheLoader<CCMBridge.Builder, CCMBridge> { | |
| 289 | + | |
| 290 | + @Override | |
| 291 | + public CCMBridge load(CCMBridge.Builder builder) { | |
| 292 | + return builder.build(); | |
| 293 | + } | |
| 294 | + | |
| 295 | + } | |
| 296 | + | |
| 297 | + private static class CCMTestContextWeigher implements Weigher<CCMBridge.Builder, CCMBridge> { | |
| 298 | + @Override | |
| 299 | + public int weigh(CCMBridge.Builder key, CCMBridge value) { | |
| 300 | + return value.getInitialNumberOfNodes(); | |
| 301 | + } | |
| 302 | + } | |
| 303 | + | |
| 304 | + private static class CCMTestContextRemovalListener implements RemovalListener<CCMBridge.Builder, CCMBridge> { | |
| 305 | + | |
| 306 | + @Override | |
| 307 | + public void onRemoval(RemovalNotification<CCMBridge.Builder, CCMBridge> notification) { | |
| 308 | + if (notification.getValue() != null) { | |
| 309 | + LOGGER.debug("Evicting: " + notification.getValue()); | |
| 310 | + notification.getValue().close(); | |
| 311 | + } | |
| 312 | + } | |
| 313 | + | |
| 314 | + } | |
| 315 | + | |
| 316 | + /** | |
| 317 | + * A LoadingCache that stores running CCM clusters. | |
| 318 | + */ | |
| 319 | + private static final LoadingCache<CCMBridge.Builder, CCMBridge> CACHE; | |
| 320 | + | |
| 321 | + static { | |
| 322 | + long maximumWeight; | |
| 323 | + String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes"); | |
| 324 | + if (numberOfNodes == null) { | |
| 325 | + long freeMemoryMB = TestUtils.getFreeMemoryMB(); | |
| 326 | + if (freeMemoryMB < 1000) | |
| 327 | + LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB); | |
| 328 | + // CCM nodes are started with -Xms500M -Xmx500M | |
| 329 | + // leave at least 500 MB out, with a minimum of 1 node and a maximum of 10 nodes | |
| 330 | + maximumWeight = Math.min(10, Math.max(1, (freeMemoryMB / 500) - 1)); | |
| 331 | + } else { | |
| 332 | + maximumWeight = Integer.parseInt(numberOfNodes); | |
| 333 | + } | |
| 334 | + LOGGER.info("Maximum number of running CCM nodes: {}", maximumWeight); | |
| 335 | + CACHE = CacheBuilder.newBuilder() | |
| 336 | + .initialCapacity(1) | |
| 337 | + .maximumWeight(maximumWeight) | |
| 338 | + .weigher(new CCMTestContextWeigher()) | |
| 339 | + .removalListener(new CCMTestContextRemovalListener()) | |
| 340 | + .build(new CCMTestContextLoader()); | |
| 341 | + } | |
| 342 | + private TestMode testMode; | |
| 343 | + | |
| 344 | + private CCMTestConfig ccmTestConfig; | |
| 345 | + | |
| 346 | + protected CCMBridge ccm; | |
| 347 | + | |
| 348 | + protected Cluster cluster; | |
| 349 | + | |
| 350 | + protected Session session; | |
| 351 | + | |
| 352 | + protected String keyspace; | |
| 353 | + | |
| 354 | + private boolean erroredOut = false; | |
| 355 | + | |
| 356 | + private Closer closer; | |
| 357 | + | |
| 358 | + /** | |
| 359 | + * Hook invoked at the beginning of a test class to initialize CCM test context. | |
| 360 | + * | |
| 361 | + * @throws Exception | |
| 362 | + */ | |
| 363 | + @BeforeClass(groups = {"isolated", "short", "long", "stress", "duration"}) | |
| 364 | + public void beforeTestClass() throws Exception { | |
| 365 | + beforeTestClass(this); | |
| 366 | + } | |
| 367 | + | |
| 368 | + /** | |
| 369 | + * Hook invoked at the beginning of a test class to initialize CCM test context. | |
| 370 | + * <p/> | |
| 371 | + * Useful when this class is not a superclass of the test being run. | |
| 372 | + * | |
| 373 | + * @throws Exception | |
| 374 | + */ | |
| 375 | + public void beforeTestClass(Object testInstance) throws Exception { | |
| 376 | + testMode = determineTestMode(testInstance.getClass()); | |
| 377 | + if (testMode == PER_CLASS) { | |
| 378 | + closer = Closer.create(); | |
| 379 | + initTestContext(testInstance, null); | |
| 380 | + initTestCluster(testInstance); | |
| 381 | + initTestSession(); | |
| 382 | + initTestKeyspace(); | |
| 383 | + initTestFixtures(testInstance); | |
| 384 | + } | |
| 385 | + } | |
| 386 | + | |
| 387 | + /** | |
| 388 | + * Hook executed before each test method. | |
| 389 | + * | |
| 390 | + * @throws Exception | |
| 391 | + */ | |
| 392 | + @BeforeMethod(groups = {"isolated", "short", "long", "stress", "duration"}) | |
| 393 | + public void beforeTestMethod(Method testMethod) throws Exception { | |
| 394 | + beforeTestMethod(this, testMethod); | |
| 395 | + } | |
| 396 | + | |
| 397 | + /** | |
| 398 | + * Hook executed before each test method. | |
| 399 | + * <p/> | |
| 400 | + * Useful when this class is not a superclass of the test being run. | |
| 401 | + * | |
| 402 | + * @throws Exception | |
| 403 | + */ | |
| 404 | + public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception { | |
| 405 | + if (isCcmEnabled(testMethod)) { | |
| 406 | + if (closer == null) | |
| 407 | + closer = Closer.create(); | |
| 408 | + if (testMode == PER_METHOD || erroredOut) { | |
| 409 | + initTestContext(testInstance, testMethod); | |
| 410 | + initTestCluster(testInstance); | |
| 411 | + initTestSession(); | |
| 412 | + initTestKeyspace(); | |
| 413 | + initTestFixtures(testInstance); | |
| 414 | + } | |
| 415 | + assert ccmTestConfig != null; | |
| 416 | + assert !ccmTestConfig.createCcm() || ccm != null; | |
| 417 | + } | |
| 418 | + } | |
| 419 | + | |
| 420 | + /** | |
| 421 | + * Hook executed after each test method. | |
| 422 | + */ | |
| 423 | + @AfterMethod(groups = {"isolated", "short", "long", "stress", "duration"}, alwaysRun = true) | |
| 424 | + public void afterTestMethod(ITestResult tr) { | |
| 425 | + if (isCcmEnabled(tr.getMethod().getConstructorOrMethod().getMethod())) { | |
| 426 | + if (tr.getStatus() == ITestResult.FAILURE) { | |
| 427 | + errorOut(); | |
| 428 | + } | |
| 429 | + if (erroredOut || testMode == PER_METHOD) { | |
| 430 | + closeCloseables(); | |
| 431 | + closeTestCluster(); | |
| 432 | + } | |
| 433 | + if (testMode == PER_METHOD) | |
| 434 | + closeTestContext(); | |
| 435 | + } | |
| 436 | + } | |
| 437 | + /** | |
| 438 | + * Hook executed after each test class. | |
| 439 | + */ | |
| 440 | + @AfterClass(groups = {"isolated", "short", "long", "stress", "duration"}, alwaysRun = true) | |
| 441 | + public void afterTestClass() { | |
| 442 | + if (testMode == PER_CLASS) { | |
| 443 | + closeCloseables(); | |
| 444 | + closeTestCluster(); | |
| 445 | + closeTestContext(); | |
| 446 | + } | |
| 447 | + } | |
| 448 | + | |
| 449 | + /** | |
| 450 | + * Returns the cluster builder to use for this test. | |
| 451 | + * <p/> | |
| 452 | + * The default implementation returns a vanilla builder. | |
| 453 | + * <p/> | |
| 454 | + * It's not required to call {@link com.datastax.driver.core.Cluster.Builder#addContactPointsWithPorts}, | |
| 455 | + * it will be done automatically. | |
| 456 | + * | |
| 457 | + * @return The cluster builder to use for the tests. | |
| 458 | + */ | |
| 459 | + public Cluster.Builder createClusterBuilder() { | |
| 460 | + return Cluster.builder(); | |
| 461 | + } | |
| 462 | + | |
| 463 | + /** | |
| 464 | + * Returns an alternate cluster builder to use for this test, | |
| 465 | + * with no event debouncing. | |
| 466 | + * <p/> | |
| 467 | + * It's not required to call {@link com.datastax.driver.core.Cluster.Builder#addContactPointsWithPorts}, | |
| 468 | + * it will be done automatically. | |
| 469 | + * | |
| 470 | + * @return The cluster builder to use for the tests. | |
| 471 | + */ | |
| 472 | + public Cluster.Builder createClusterBuilderNoDebouncing() { | |
| 473 | + return Cluster.builder().withQueryOptions(TestUtils.nonDebouncingQueryOptions()); | |
| 474 | + } | |
| 475 | + | |
| 476 | + /** | |
| 477 | + * The CQL statements to execute before the tests in this class. | |
| 478 | + * Useful to create tables or other objects inside the test keyspace, | |
| 479 | + * or to insert test data. | |
| 480 | + * <p/> | |
| 481 | + * Statements do not need to be qualified with keyspace name. | |
| 482 | + * <p/> | |
| 483 | + * The default implementation returns an empty list (no fixtures required). | |
| 484 | + * | |
| 485 | + * @return The DDL statements to execute before the tests. | |
| 486 | + */ | |
| 487 | + public Collection<String> createTestFixtures() { | |
| 488 | + return Collections.emptyList(); | |
| 489 | + } | |
| 490 | + | |
| 491 | + /** | |
| 492 | + * Signals that the test has encountered an unexpected error. | |
| 493 | + * <p/> | |
| 494 | + * This method is automatically called when a test finishes with an unexpected exception | |
| 495 | + * being thrown, but it is also possible to manually invoke it. | |
| 496 | + * <p/> | |
| 497 | + * Calling this method will close the current cluster and session. | |
| 498 | + * The CCM data directory will be kept after the test session is finished, | |
| 499 | + * for debugging purposes | |
| 500 | + * <p/> | |
| 501 | + * This method should not be called before the test has started, nor after the test is finished. | |
| 502 | + */ | |
| 503 | + public void errorOut() { | |
| 504 | + erroredOut = true; | |
| 505 | + if (ccm != null) | |
| 506 | + ccm.setKeepLogs(true); | |
| 507 | + } | |
| 508 | + | |
| 509 | + /** | |
| 510 | + * Returns the contact points to use to contact the CCM cluster. | |
| 511 | + * <p/> | |
| 512 | + * This method returns as many contact points as the number of nodes initially present in the CCM cluster, | |
| 513 | + * according to {@link CCMConfig} annotations. | |
| 514 | + * <p/> | |
| 515 | + * On a multi-DC setup, this will include nodes in all data centers. | |
| 516 | + * <p/> | |
| 517 | + * This method should not be called before the test has started, nor after the test is finished. | |
| 518 | + * | |
| 519 | + * @return the contact points to use to contact the CCM cluster. | |
| 520 | + */ | |
| 521 | + public List<InetSocketAddress> getInitialContactPoints() { | |
| 522 | + assert ccmTestConfig != null; | |
| 523 | + List<InetSocketAddress> contactPoints = new ArrayList<InetSocketAddress>(); | |
| 524 | + int n = 1; | |
| 525 | + int[] numberOfNodes = ccmTestConfig.numberOfNodes(); | |
| 526 | + for (int dc = 1; dc <= numberOfNodes.length; dc++) { | |
| 527 | + int nodesInDc = numberOfNodes[dc - 1]; | |
| 528 | + for (int i = 0; i < nodesInDc; i++) { | |
| 529 | + contactPoints.add(new InetSocketAddress(ipOfNode(n), ccm.getBinaryPort())); | |
| 530 | + n++; | |
| 531 | + } | |
| 532 | + } | |
| 533 | + return contactPoints; | |
| 534 | + } | |
| 535 | + | |
| 536 | + /** | |
| 537 | + * Returns the address of the {@code nth} host in the CCM cluster (counting from 1, i.e., | |
| 538 | + * {@code getHostAddress(1)} returns the address of the first node. | |
| 539 | + * <p/> | |
| 540 | + * In multi-DC setups, nodes are numbered in ascending order of their datacenter number. | |
| 541 | + * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4. | |
| 542 | + * <p/> | |
| 543 | + * This method should not be called before the test has started, nor after the test is finished. | |
| 544 | + * | |
| 545 | + * @return the address of the {@code nth} host in the cluster. | |
| 546 | + */ | |
| 547 | + public InetSocketAddress getHostAddress(int n) { | |
| 548 | + return ccm.addressOfNode(n); | |
| 549 | + } | |
| 550 | + | |
| 551 | + /** | |
| 552 | + * Returns an {@link AddressTranslater} to use when tests must manually create | |
| 553 | + * {@link Cluster} instances. | |
| 554 | + * <p/> | |
| 555 | + * This translator is necessary because hosts create with this class do not use standard ports. | |
| 556 | + * <p/> | |
| 557 | + * This method should not be called before the test has started, nor after the test is finished. | |
| 558 | + * | |
| 559 | + * @return an {@link AddressTranslater} to use when tests must manually create | |
| 560 | + * {@link Cluster} instances. | |
| 561 | + */ | |
| 562 | + public AddressTranslater getAddressTranslator() { | |
| 563 | + return ccm.addressTranslator(); | |
| 564 | + } | |
| 565 | + | |
| 566 | + /** | |
| 567 | + * Registers the given {@link Closeable} to be closed at the end of the current test method. | |
| 568 | + * <p/> | |
| 569 | + * This method should not be called before the test has started, nor after the test is finished. | |
| 570 | + * | |
| 571 | + * @param closeable The closeable to close | |
| 572 | + * @return The closeable to close | |
| 573 | + */ | |
| 574 | + public <T extends Closeable> T register(T closeable) { | |
| 575 | + closer.register(closeable); | |
| 576 | + return closeable; | |
| 577 | + } | |
| 578 | + | |
| 579 | + private void initTestContext(Object testInstance, Method testMethod) throws Exception { | |
| 580 | + erroredOut = false; | |
| 581 | + ccmTestConfig = createCCMTestConfig(testInstance, testMethod); | |
| 582 | + assert ccmTestConfig != null; | |
| 583 | + if (ccmTestConfig.createCcm()) { | |
| 584 | + if (ccmTestConfig.dirtiesContext()) { | |
| 585 | + ccm = ccmTestConfig.ccmBuilder().build(); | |
| 586 | + LOGGER.debug("Using dedicated {}", ccm); | |
| 587 | + } else { | |
| 588 | + CCMBridge.Builder key = ccmTestConfig.ccmBuilder(); | |
| 589 | + ccm = CACHE.getIfPresent(key); | |
| 590 | + if (ccm != null) { | |
| 591 | + LOGGER.debug("Reusing {}", ccm); | |
| 592 | + } else { | |
| 593 | + try { | |
| 594 | + ccm = CACHE.get(ccmTestConfig.ccmBuilder()); | |
| 595 | + LOGGER.debug("Using newly-created {}", ccm); | |
| 596 | + } catch (ExecutionException e) { | |
| 597 | + Throwables.propagate(e); | |
| 598 | + } | |
| 599 | + } | |
| 600 | + } | |
| 601 | + assert ccm != null; | |
| 602 | + } | |
| 603 | + } | |
| 604 | + | |
| 605 | + private void initTestCluster(Object testInstance) throws Exception { | |
| 606 | + if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster()) { | |
| 607 | + Cluster.Builder builder = ccmTestConfig.clusterBuilder(testInstance); | |
| 608 | + // add contact points only if the provided builder didn't do so | |
| 609 | + if (builder.getContactPoints().isEmpty()) | |
| 610 | + builder.addContactPointsWithPorts(getInitialContactPoints()); | |
| 611 | + builder.withAddressTranslater(ccm.addressTranslator()); | |
| 612 | + cluster = register(builder.build()); | |
| 613 | + cluster.init(); | |
| 614 | + } | |
| 615 | + } | |
| 616 | + | |
| 617 | + private void initTestSession() throws Exception { | |
| 618 | + if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession()) | |
| 619 | + session = register(cluster.connect()); | |
| 620 | + } | |
| 621 | + | |
| 622 | + private void initTestKeyspace() { | |
| 623 | + if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession() && ccmTestConfig.createKeyspace()) { | |
| 624 | + try { | |
| 625 | + keyspace = TestUtils.getAvailableKeyspaceName(); | |
| 626 | + LOGGER.debug("Using keyspace " + keyspace); | |
| 627 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); | |
| 628 | + session.execute("USE " + keyspace); | |
| 629 | + } catch (Exception e) { | |
| 630 | + errorOut(); | |
| 631 | + LOGGER.error("Could not create test keyspace", e); | |
| 632 | + Throwables.propagate(e); | |
| 633 | + } | |
| 634 | + } | |
| 635 | + } | |
| 636 | + | |
| 637 | + private void initTestFixtures(Object testInstance) throws Exception { | |
| 638 | + if (ccmTestConfig.createCcm() && ccmTestConfig.createCluster() && ccmTestConfig.createSession()) { | |
| 639 | + for (String stmt : ccmTestConfig.fixtures(testInstance)) { | |
| 640 | + try { | |
| 641 | + session.execute(stmt); | |
| 642 | + } catch (Exception e) { | |
| 643 | + errorOut(); | |
| 644 | + LOGGER.error("Could not execute statement: " + stmt, e); | |
| 645 | + Throwables.propagate(e); | |
| 646 | + } | |
| 647 | + } | |
| 648 | + } | |
| 649 | + } | |
| 650 | + | |
| 651 | + private void closeTestContext() { | |
| 652 | + if (ccmTestConfig != null && ccm != null && ccmTestConfig.dirtiesContext()) { | |
| 653 | + ccm.close(); | |
| 654 | + } | |
| 655 | + ccmTestConfig = null; | |
| 656 | + ccm = null; | |
| 657 | + } | |
| 658 | + | |
| 659 | + private void closeTestCluster() { | |
| 660 | + if (cluster != null && !cluster.isClosed()) | |
| 661 | + executeNoFail(new Runnable() { | |
| 662 | + @Override | |
| 663 | + public void run() { | |
| 664 | + cluster.close(); | |
| 665 | + } | |
| 666 | + }, false); | |
| 667 | + cluster = null; | |
| 668 | + session = null; | |
| 669 | + keyspace = null; | |
| 670 | + } | |
| 671 | + | |
| 672 | + private void closeCloseables() { | |
| 673 | + if (closer != null) | |
| 674 | + executeNoFail(new Callable<Void>() { | |
| 675 | + @Override | |
| 676 | + public Void call() throws IOException { | |
| 677 | + closer.close(); | |
| 678 | + return null; | |
| 679 | + } | |
| 680 | + }, false); | |
| 681 | + } | |
| 682 | + | |
| 683 | + private static boolean isCcmEnabled(Method testMethod) { | |
| 684 | + Test ann = locateAnnotation(testMethod, Test.class); | |
| 685 | + return !Collections.disjoint(Arrays.asList(ann.groups()), TEST_GROUPS); | |
| 686 | + } | |
| 687 | + | |
| 688 | + private static CCMTestConfig createCCMTestConfig(Object testInstance, Method testMethod) throws Exception { | |
| 689 | + ArrayList<CCMConfig> annotations = new ArrayList<CCMConfig>(); | |
| 690 | + CCMConfig ann = locateAnnotation(testMethod, CCMConfig.class); | |
| 691 | + if (ann != null) | |
| 692 | + annotations.add(ann); | |
| 693 | + locateClassAnnotations(testInstance.getClass(), CCMConfig.class, annotations); | |
| 694 | + return new CCMTestConfig(annotations); | |
| 695 | + } | |
| 696 | + | |
| 697 | + private static TestMode determineTestMode(Class<?> testClass) { | |
| 698 | + List<CreateCCM> annotations = locateClassAnnotations(testClass, CreateCCM.class, new ArrayList<CreateCCM>()); | |
| 699 | + if (!annotations.isEmpty()) | |
| 700 | + return annotations.get(0).value(); | |
| 701 | + return PER_CLASS; | |
| 702 | + } | |
| 703 | + | |
| 704 | + private static <A extends Annotation> A locateAnnotation(Method testMethod, Class<? extends A> clazz) { | |
| 705 | + if (testMethod == null) | |
| 706 | + return null; | |
| 707 | + testMethod.setAccessible(true); | |
| 708 | + return testMethod.getAnnotation(clazz); | |
| 709 | + } | |
| 710 | + | |
| 711 | + private static <A extends Annotation> List<A> locateClassAnnotations(Class<?> clazz, Class<? extends A> annotationClass, List<A> annotations) { | |
| 712 | + A ann = clazz.getAnnotation(annotationClass); | |
| 713 | + if (ann != null) | |
| 714 | + annotations.add(ann); | |
| 715 | + clazz = clazz.getSuperclass(); | |
| 716 | + if (clazz == null) | |
| 717 | + return annotations; | |
| 718 | + return locateClassAnnotations(clazz, annotationClass, annotations); | |
| 719 | + } | |
| 720 | + | |
| 721 | + private static Method locateMethod(String methodName, Class<?> clazz) throws NoSuchMethodException { | |
| 722 | + try { | |
| 723 | + Method method = clazz.getDeclaredMethod(methodName); | |
| 724 | + method.setAccessible(true); | |
| 725 | + return method; | |
| 726 | + } catch (NoSuchMethodException e) { | |
| 727 | + clazz = clazz.getSuperclass(); | |
| 728 | + if (clazz == null) | |
| 729 | + throw e; | |
| 730 | + return locateMethod(methodName, clazz); | |
| 731 | + } | |
| 732 | + } | |
| 733 | + | |
| 734 | + @SuppressWarnings("unchecked") | |
| 735 | + private static <T> T instantiate(Class<? extends T> clazz) throws NoSuchMethodException, InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException { | |
| 736 | + if (clazz.getEnclosingClass() == null || Modifier.isStatic(clazz.getModifiers())) { | |
| 737 | + Constructor<?> constructor = clazz.getDeclaredConstructor(); | |
| 738 | + constructor.setAccessible(true); | |
| 739 | + return (T) constructor.newInstance(); | |
| 740 | + } else { | |
| 741 | + Class<?> enclosingClass = clazz.getEnclosingClass(); | |
| 742 | + Object enclosingInstance = enclosingClass.newInstance(); | |
| 743 | + Constructor<?> constructor = clazz.getDeclaredConstructor(enclosingClass); | |
| 744 | + constructor.setAccessible(true); | |
| 745 | + return (T) constructor.newInstance(enclosingInstance); | |
| 746 | + } | |
| 747 | + } | |
| 748 | + | |
| 749 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +24 −55
| @@ -20,69 +20,38 @@ | ||
| 20 | 20 | import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; |
| 21 | 21 | import static org.testng.Assert.*; |
| 22 | 22 | |
| 23 | -public class CaseSensitivityTest { | |
| 24 | - | |
| 25 | - private void assertExists(CCMBridge.CCMCluster c, String fetchName, String realName) { | |
| 26 | - KeyspaceMetadata km = c.cluster.getMetadata().getKeyspace(fetchName); | |
| 27 | - assertNotNull(km); | |
| 28 | - assertEquals(realName, km.getName()); | |
| 29 | - } | |
| 30 | - | |
| 31 | - private void assertNotExists(CCMBridge.CCMCluster c, String name) { | |
| 32 | - assertNull(c.cluster.getMetadata().getKeyspace(name)); | |
| 33 | - } | |
| 23 | +@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing") | |
| 24 | +public class CaseSensitivityTest extends CCMTestsSupport { | |
| 34 | 25 | |
| 35 | 26 | @Test(groups = "short") |
| 36 | 27 | public void testCaseInsensitiveKeyspace() throws Throwable { |
| 37 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder() | |
| 38 | - .withQueryOptions(new QueryOptions() | |
| 39 | - .setRefreshNodeIntervalMillis(0) | |
| 40 | - .setRefreshNodeListIntervalMillis(0) | |
| 41 | - .setRefreshSchemaIntervalMillis(0) | |
| 42 | - ) | |
| 43 | - ); | |
| 44 | - Session s = c.session; | |
| 45 | - try { | |
| 46 | - String ksName = "MyKeyspace"; | |
| 47 | - s.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1)); | |
| 48 | - | |
| 49 | - assertExists(c, ksName, "mykeyspace"); | |
| 50 | - assertExists(c, "mykeyspace", "mykeyspace"); | |
| 51 | - assertExists(c, "MYKEYSPACE", "mykeyspace"); | |
| 52 | - | |
| 53 | - } catch (Throwable e) { | |
| 54 | - c.errorOut(); | |
| 55 | - throw e; | |
| 56 | - } finally { | |
| 57 | - c.discard(); | |
| 58 | - } | |
| 28 | + String ksName = "MyKeyspace1"; | |
| 29 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1)); | |
| 30 | + assertExists(ksName, "mykeyspace1"); | |
| 31 | + assertExists("mykeyspace1", "mykeyspace1"); | |
| 32 | + assertExists("MYKEYSPACE1", "mykeyspace1"); | |
| 59 | 33 | } |
| 60 | 34 | |
| 61 | 35 | @Test(groups = "short") |
| 62 | 36 | public void testCaseSensitiveKeyspace() throws Throwable { |
| 63 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder() | |
| 64 | - .withQueryOptions(new QueryOptions() | |
| 65 | - .setRefreshNodeIntervalMillis(0) | |
| 66 | - .setRefreshNodeListIntervalMillis(0) | |
| 67 | - .setRefreshSchemaIntervalMillis(0) | |
| 68 | - ) | |
| 69 | - ); | |
| 70 | - Session s = c.session; | |
| 71 | - try { | |
| 72 | - String ksName = "\"MyKeyspace\""; | |
| 73 | - s.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1)); | |
| 37 | + String ksName = "\"MyKeyspace2\""; | |
| 38 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ksName, 1)); | |
| 39 | + assertExists(ksName, "MyKeyspace2"); | |
| 40 | + assertExists(Metadata.quote("MyKeyspace2"), "MyKeyspace2"); | |
| 41 | + assertNotExists("mykeyspace2"); | |
| 42 | + assertNotExists("MyKeyspace2"); | |
| 43 | + assertNotExists("MYKEYSPACE2"); | |
| 44 | + } | |
| 74 | 45 | |
| 75 | - assertExists(c, ksName, "MyKeyspace"); | |
| 76 | - assertExists(c, Metadata.quote("MyKeyspace"), "MyKeyspace"); | |
| 77 | - assertNotExists(c, "mykeyspace"); | |
| 78 | - assertNotExists(c, "MyKeyspace"); | |
| 79 | - assertNotExists(c, "MYKEYSPACE"); | |
| 46 | + private void assertExists(String fetchName, String realName) { | |
| 47 | + KeyspaceMetadata km = cluster.getMetadata().getKeyspace(fetchName); | |
| 48 | + assertNotNull(km); | |
| 49 | + assertEquals(realName, km.getName()); | |
| 50 | + } | |
| 80 | 51 | |
| 81 | - } catch (Throwable e) { | |
| 82 | - c.errorOut(); | |
| 83 | - throw e; | |
| 84 | - } finally { | |
| 85 | - c.discard(); | |
| 86 | - } | |
| 52 | + private void assertNotExists(String name) { | |
| 53 | + assertNull(cluster.getMetadata().getKeyspace(name)); | |
| 87 | 54 | } |
| 55 | + | |
| 56 | + | |
| 88 | 57 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +6 −1
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import com.google.common.collect.Iterators; |
| 19 | 19 | import org.assertj.core.api.AbstractAssert; |
| 20 | 20 | |
| 21 | +import java.net.InetAddress; | |
| 21 | 22 | import java.util.Iterator; |
| 22 | 23 | import java.util.Set; |
| 23 | 24 | import java.util.TreeSet; |
| @@ -31,7 +32,7 @@ | ||
| 31 | 32 | } |
| 32 | 33 | |
| 33 | 34 | public ClusterAssert usesControlHost(int node) { |
| 34 | - String expectedAddress = CCMBridge.ipOfNode(node); | |
| 35 | + String expectedAddress = TestUtils.ipOfNode(node); | |
| 35 | 36 | Host controlHost = actual.manager.controlConnection.connectedHost(); |
| 36 | 37 | assertThat(controlHost.getAddress().getHostAddress()).isEqualTo(expectedAddress); |
| 37 | 38 | return this; |
| @@ -66,6 +67,10 @@ | ||
| 66 | 67 | return new HostAssert(host, actual); |
| 67 | 68 | } |
| 68 | 69 | |
| 70 | + public HostAssert host(InetAddress hostAddress) { | |
| 71 | + return host(hostAddress.getHostAddress()); | |
| 72 | + } | |
| 73 | + | |
| 69 | 74 | /** |
| 70 | 75 | * Asserts that {@link Cluster}'s {@link Host}s have valid {@link TokenRange}s with the given keyspace. |
| 71 | 76 | * <p/> |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterDelegateTest.java +1 −8
| @@ -15,18 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.google.common.collect.Lists; | |
| 19 | 18 | import org.testng.annotations.Test; |
| 20 | 19 | |
| 21 | -import java.util.Collection; | |
| 22 | - | |
| 23 | 20 | import static org.assertj.core.api.Assertions.assertThat; |
| 24 | 21 | |
| 25 | -public class ClusterDelegateTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 26 | - @Override | |
| 27 | - protected Collection<String> getTableDefinitions() { | |
| 28 | - return Lists.newArrayList(); | |
| 29 | - } | |
| 22 | +public class ClusterDelegateTest extends CCMTestsSupport { | |
| 30 | 23 | |
| 31 | 24 | @Test(groups = "short") |
| 32 | 25 | public void should_allow_subclass_to_delegate_to_other_instance() { |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +23 −20
| @@ -42,8 +42,7 @@ | ||
| 42 | 42 | import static com.datastax.driver.core.Assertions.fail; |
| 43 | 43 | import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS; |
| 44 | 44 | import static com.datastax.driver.core.HostDistance.LOCAL; |
| 45 | -import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 46 | -import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; | |
| 45 | +import static com.datastax.driver.core.TestUtils.*; | |
| 47 | 46 | import static org.mockito.Mockito.*; |
| 48 | 47 | |
| 49 | 48 | public class ClusterInitTest { |
| @@ -67,19 +66,18 @@ | ||
| 67 | 66 | // - 1 is an actual Scassandra instance that will accept connections: |
| 68 | 67 | scassandra = TestUtils.createScassandraServer(); |
| 69 | 68 | scassandra.start(); |
| 70 | - String realHostAddress = "127.0.0.1"; | |
| 71 | 69 | int port = scassandra.getBinaryPort(); |
| 72 | 70 | |
| 73 | 71 | // - the remaining 4 are fake servers that will throw connect timeouts: |
| 74 | 72 | for (int i = 2; i <= 5; i++) { |
| 75 | - FakeHost failingHost = new FakeHost(CCMBridge.ipOfNode(i), port, THROWING_CONNECT_TIMEOUTS); | |
| 73 | + FakeHost failingHost = new FakeHost(TestUtils.ipOfNode(i), port, THROWING_CONNECT_TIMEOUTS); | |
| 76 | 74 | failingHosts.add(failingHost); |
| 77 | 75 | failingHost.start(); |
| 78 | 76 | } |
| 79 | 77 | |
| 80 | 78 | // - we also have a "missing" contact point, i.e. there's no server listening at this address, |
| 81 | 79 | // and the address is not listed in the live host's system.peers |
| 82 | - String missingHostAddress = CCMBridge.ipOfNode(6); | |
| 80 | + String missingHostAddress = TestUtils.ipOfNode(6); | |
| 83 | 81 | |
| 84 | 82 | primePeerRows(scassandra, failingHosts); |
| 85 | 83 | |
| @@ -100,7 +98,7 @@ | ||
| 100 | 98 | cluster = Cluster.builder() |
| 101 | 99 | .withPort(scassandra.getBinaryPort()) |
| 102 | 100 | .addContactPoints( |
| 103 | - realHostAddress, | |
| 101 | + ipOfNode(1), | |
| 104 | 102 | failingHosts.get(0).address, failingHosts.get(1).address, |
| 105 | 103 | failingHosts.get(2).address, failingHosts.get(3).address, |
| 106 | 104 | missingHostAddress |
| @@ -126,7 +124,7 @@ | ||
| 126 | 124 | verify(socketOptions, atLeast(6)).getKeepAlive(); |
| 127 | 125 | verify(socketOptions, atMost(7)).getKeepAlive(); |
| 128 | 126 | |
| 129 | - assertThat(cluster).host(realHostAddress).isNotNull().isUp(); | |
| 127 | + assertThat(cluster).host(1).isNotNull().isUp(); | |
| 130 | 128 | // It is likely but not guaranteed that a host is marked down at this point. |
| 131 | 129 | // It should eventually be marked down as Cluster.Manager.triggerOnDown should be |
| 132 | 130 | // called and submit a task that marks the host down. |
| @@ -166,8 +164,8 @@ | ||
| 166 | 164 | public void should_not_schedule_reconnections_before_init_complete() { |
| 167 | 165 | // Both contact points time out so we're sure we'll try both of them and init will never complete. |
| 168 | 166 | List<FakeHost> hosts = Lists.newArrayList( |
| 169 | - new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS), | |
| 170 | - new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS)); | |
| 167 | + new FakeHost(TestUtils.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS), | |
| 168 | + new FakeHost(TestUtils.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS)); | |
| 171 | 169 | // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a reconnection was scheduled, |
| 172 | 170 | // we would see a call to the reconnection policy. |
| 173 | 171 | CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100)); |
| @@ -184,6 +182,7 @@ | ||
| 184 | 182 | for (FakeHost fakeHost : hosts) { |
| 185 | 183 | fakeHost.stop(); |
| 186 | 184 | } |
| 185 | + cluster.close(); | |
| 187 | 186 | } |
| 188 | 187 | // We don't test that reconnections are scheduled if init succeeds, but that's covered in |
| 189 | 188 | // should_handle_failing_or_missing_contact_points |
| @@ -206,12 +205,13 @@ | ||
| 206 | 205 | cluster.connect(); |
| 207 | 206 | fail("Should not have been able to connect."); |
| 208 | 207 | } catch (NoHostAvailableException e) { |
| 209 | - } // Expected. | |
| 210 | - CloseFuture closeFuture = cluster.closeAsync(); | |
| 211 | - try { | |
| 212 | - closeFuture.get(1, TimeUnit.SECONDS); | |
| 213 | - } catch (TimeoutException e) { | |
| 214 | - fail("Close Future did not complete quickly."); | |
| 208 | + // Expected. | |
| 209 | + CloseFuture closeFuture = cluster.closeAsync(); | |
| 210 | + try { | |
| 211 | + closeFuture.get(1, TimeUnit.SECONDS); | |
| 212 | + } catch (TimeoutException e1) { | |
| 213 | + fail("Close Future did not complete quickly."); | |
| 214 | + } | |
| 215 | 215 | } |
| 216 | 216 | } |
| 217 | 217 | |
| @@ -225,13 +225,14 @@ | ||
| 225 | 225 | @Test(groups = "short") |
| 226 | 226 | public void should_not_abort_init_if_host_does_not_support_protocol_version() { |
| 227 | 227 | ScassandraCluster scassandraCluster = ScassandraCluster.builder() |
| 228 | - .withIpPrefix(CCMBridge.IP_PREFIX) | |
| 228 | + .withIpPrefix(TestUtils.IP_PREFIX) | |
| 229 | 229 | .withNodes(5) |
| 230 | 230 | // For node 2, report an older version which uses protocol v1. |
| 231 | 231 | .forcePeerInfo(1, 2, "release_version", "1.2.19") |
| 232 | 232 | .build(); |
| 233 | 233 | Cluster cluster = Cluster.builder() |
| 234 | - .addContactPoints(scassandraCluster.address(1)) | |
| 234 | + .addContactPointsWithPorts(scassandraCluster.address(1)) | |
| 235 | + .withAddressTranslater(scassandraCluster.addressTranslator()) | |
| 235 | 236 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 236 | 237 | .build(); |
| 237 | 238 | |
| @@ -239,7 +240,7 @@ | ||
| 239 | 240 | scassandraCluster.init(); |
| 240 | 241 | cluster.init(); |
| 241 | 242 | for (int i = 1; i <= 5; i++) { |
| 242 | - String hostAddress = scassandraCluster.address(i); | |
| 243 | + InetAddress hostAddress = scassandraCluster.address(i).getAddress(); | |
| 243 | 244 | if (i == 2) { |
| 244 | 245 | // As this host is at an older protocol version, it should be ignored and not marked up. |
| 245 | 246 | assertThat(cluster).host(hostAddress).hasState(Host.State.ADDED); |
| @@ -256,8 +257,10 @@ | ||
| 256 | 257 | } |
| 257 | 258 | |
| 258 | 259 | private void primePeerRows(Scassandra scassandra, List<FakeHost> otherHosts) throws UnknownHostException { |
| 259 | - PrimingClient primingClient = PrimingClient.builder() | |
| 260 | - .withHost("localhost").withPort(scassandra.getAdminPort()) | |
| 260 | + PrimingClient primingClient = | |
| 261 | + PrimingClient.builder() | |
| 262 | + .withHost(ipOfNode(1)) | |
| 263 | + .withPort(scassandra.getAdminPort()) | |
| 261 | 264 | .build(); |
| 262 | 265 | |
| 263 | 266 | List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(5); |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +38 −25
| @@ -17,20 +17,21 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.utils.SocketChannelMonitor; |
| 19 | 19 | import com.google.common.collect.Lists; |
| 20 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 20 | 21 | import org.slf4j.Logger; |
| 21 | 22 | import org.slf4j.LoggerFactory; |
| 23 | +import org.testng.annotations.AfterMethod; | |
| 22 | 24 | import org.testng.annotations.Test; |
| 23 | 25 | |
| 24 | -import java.net.InetSocketAddress; | |
| 25 | 26 | import java.util.ArrayList; |
| 26 | -import java.util.Collection; | |
| 27 | -import java.util.Collections; | |
| 28 | 27 | import java.util.List; |
| 29 | 28 | import java.util.concurrent.*; |
| 30 | 29 | |
| 31 | 30 | import static org.testng.Assert.assertEquals; |
| 31 | +import static org.testng.Assert.fail; | |
| 32 | + | |
| 33 | +public class ClusterStressTest extends CCMTestsSupport { | |
| 32 | 34 | |
| 33 | -public class ClusterStressTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 34 | 35 | private static final Logger logger = LoggerFactory.getLogger(ClusterStressTest.class); |
| 35 | 36 | |
| 36 | 37 | private ExecutorService executorService; |
| @@ -40,22 +41,35 @@ | ||
| 40 | 41 | executorService = Executors.newFixedThreadPool(8); |
| 41 | 42 | } |
| 42 | 43 | |
| 43 | - @Override | |
| 44 | - protected Collection<String> getTableDefinitions() { | |
| 45 | - return new ArrayList<String>(0); | |
| 46 | - } | |
| 47 | - | |
| 48 | 44 | @Test(groups = "long") |
| 49 | 45 | public void clusters_should_not_leak_connections() { |
| 50 | 46 | int numberOfClusters = 10; |
| 51 | 47 | int numberOfIterations = 500; |
| 52 | - for (int i = 1; i < numberOfIterations; i++) { | |
| 53 | - logger.info("On iteration {}/{}.", i, numberOfIterations); | |
| 54 | - logger.info("Creating {} clusters", numberOfClusters); | |
| 55 | - List<CreateClusterAndCheckConnections> actions = | |
| 56 | - waitForCreates(createClustersConcurrently(numberOfClusters)); | |
| 57 | - waitForCloses(closeClustersConcurrently(actions)); | |
| 58 | - logger.debug("# {} threads currently running", Thread.getAllStackTraces().keySet().size()); | |
| 48 | + try { | |
| 49 | + for (int i = 1; i < numberOfIterations; i++) { | |
| 50 | + logger.info("On iteration {}/{}.", i, numberOfIterations); | |
| 51 | + logger.info("Creating {} clusters", numberOfClusters); | |
| 52 | + List<CreateClusterAndCheckConnections> actions = | |
| 53 | + waitForCreates(createClustersConcurrently(numberOfClusters)); | |
| 54 | + waitForCloses(closeClustersConcurrently(actions)); | |
| 55 | + if (logger.isDebugEnabled()) | |
| 56 | + logger.debug("# {} threads currently running", Thread.getAllStackTraces().keySet().size()); | |
| 57 | + } | |
| 58 | + } finally { | |
| 59 | + logger.info("Sleeping 60 seconds to free TCP resources"); | |
| 60 | + Uninterruptibles.sleepUninterruptibly(60, TimeUnit.SECONDS); | |
| 61 | + } | |
| 62 | + } | |
| 63 | + | |
| 64 | + @AfterMethod(groups = "long", alwaysRun = true) | |
| 65 | + public void shutdown() throws Exception { | |
| 66 | + executorService.shutdown(); | |
| 67 | + try { | |
| 68 | + boolean shutdown = executorService.awaitTermination(30, TimeUnit.SECONDS); | |
| 69 | + if (!shutdown) | |
| 70 | + fail("executor ran for longer than expected"); | |
| 71 | + } catch (InterruptedException e) { | |
| 72 | + fail("Interrupted while waiting for executor to shutdown"); | |
| 59 | 73 | } |
| 60 | 74 | } |
| 61 | 75 | |
| @@ -148,15 +162,14 @@ | ||
| 148 | 162 | return result; |
| 149 | 163 | } |
| 150 | 164 | |
| 151 | - private static class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> { | |
| 165 | + private class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> { | |
| 152 | 166 | private final CountDownLatch startSignal; |
| 153 | 167 | private final Cluster cluster; |
| 154 | 168 | private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor(); |
| 155 | - private final List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress); | |
| 156 | 169 | |
| 157 | 170 | CreateClusterAndCheckConnections(CountDownLatch startSignal) { |
| 158 | 171 | this.startSignal = startSignal; |
| 159 | - this.cluster = Cluster.builder().addContactPointsWithPorts(contactPoints) | |
| 172 | + this.cluster = Cluster.builder().addContactPointsWithPorts(getInitialContactPoints()) | |
| 160 | 173 | .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)) |
| 161 | 174 | .withNettyOptions(channelMonitor.nettyOptions()).build(); |
| 162 | 175 | } |
| @@ -170,19 +183,19 @@ | ||
| 170 | 183 | cluster.init(); |
| 171 | 184 | assertEquals(cluster.manager.sessions.size(), 0); |
| 172 | 185 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 173 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 186 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1); | |
| 174 | 187 | |
| 175 | 188 | // The first session initializes the cluster and its control connection |
| 176 | 189 | Session session = cluster.connect(); |
| 177 | 190 | assertEquals(cluster.manager.sessions.size(), 1); |
| 178 | 191 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster)); |
| 179 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster)); | |
| 192 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster)); | |
| 180 | 193 | |
| 181 | 194 | // Closing the session keeps the control connection opened |
| 182 | 195 | session.close(); |
| 183 | 196 | assertEquals(cluster.manager.sessions.size(), 0); |
| 184 | 197 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 185 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 198 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1); | |
| 186 | 199 | |
| 187 | 200 | return this; |
| 188 | 201 | } catch (AssertionError e) { |
| @@ -196,7 +209,7 @@ | ||
| 196 | 209 | } |
| 197 | 210 | } |
| 198 | 211 | |
| 199 | - private static class CloseCluster implements Callable<Void> { | |
| 212 | + private class CloseCluster implements Callable<Void> { | |
| 200 | 213 | private final Cluster cluster; |
| 201 | 214 | private final SocketChannelMonitor channelMonitor; |
| 202 | 215 | private final CountDownLatch startSignal; |
| @@ -213,7 +226,7 @@ | ||
| 213 | 226 | |
| 214 | 227 | cluster.close(); |
| 215 | 228 | assertEquals(cluster.manager.sessions.size(), 0); |
| 216 | - assertEquals(channelMonitor.openChannels(Collections.singletonList(hostAddress)).size(), 0); | |
| 229 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0); | |
| 217 | 230 | channelMonitor.stop(); |
| 218 | 231 | |
| 219 | 232 | return null; |
| @@ -225,4 +238,4 @@ | ||
| 225 | 238 | error.initCause(cause); |
| 226 | 239 | return error; |
| 227 | 240 | } |
| 228 | -} | |
| No newline at the end of the file | ||
| 241 | +} |
added driver-core/src/test/java/com/datastax/driver/core/ConditionChecker.java +158 −0
| @@ -0,0 +1,158 @@ | ||
| 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 com.google.common.base.Predicate; | |
| 19 | +import com.google.common.base.Predicates; | |
| 20 | +import org.slf4j.Logger; | |
| 21 | +import org.slf4j.LoggerFactory; | |
| 22 | + | |
| 23 | +import java.util.Timer; | |
| 24 | +import java.util.TimerTask; | |
| 25 | +import java.util.concurrent.Callable; | |
| 26 | +import java.util.concurrent.locks.Condition; | |
| 27 | +import java.util.concurrent.locks.Lock; | |
| 28 | +import java.util.concurrent.locks.ReentrantLock; | |
| 29 | + | |
| 30 | +import static com.google.common.base.Preconditions.checkState; | |
| 31 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; | |
| 32 | +import static org.assertj.core.api.Fail.fail; | |
| 33 | + | |
| 34 | +public class ConditionChecker { | |
| 35 | + | |
| 36 | + private static final Logger logger = LoggerFactory.getLogger(ConditionChecker.class); | |
| 37 | + | |
| 38 | + private static final int DEFAULT_PERIOD_MILLIS = 500; | |
| 39 | + | |
| 40 | + public static <T> void awaitUntil(T input, Predicate<? super T> predicate, long timeoutMillis) { | |
| 41 | + new ConditionChecker(input, predicate).await(timeoutMillis); | |
| 42 | + } | |
| 43 | + | |
| 44 | + public static void awaitUntil(final Callable<Boolean> condition, long timeoutMillis) { | |
| 45 | + new ConditionChecker(condition).await(timeoutMillis); | |
| 46 | + } | |
| 47 | + | |
| 48 | + public static <T> void awaitWhile(T input, Predicate<? super T> predicate, long timeoutMillis) { | |
| 49 | + new ConditionChecker(input, Predicates.not(predicate)).await(timeoutMillis); | |
| 50 | + } | |
| 51 | + | |
| 52 | + public static void awaitWhile(final Callable<Boolean> condition, long timeoutMillis) { | |
| 53 | + new ConditionChecker(new Callable<Boolean>() { | |
| 54 | + @Override | |
| 55 | + public Boolean call() throws Exception { | |
| 56 | + return !condition.call(); | |
| 57 | + } | |
| 58 | + }).await(timeoutMillis); | |
| 59 | + } | |
| 60 | + | |
| 61 | + private final Object input; | |
| 62 | + | |
| 63 | + private final Predicate<Object> predicate; | |
| 64 | + | |
| 65 | + private final Lock lock; | |
| 66 | + | |
| 67 | + private final Condition condition; | |
| 68 | + | |
| 69 | + private final Timer timer; | |
| 70 | + | |
| 71 | + /** | |
| 72 | + * When using this constructor, one must override {@link #evalCondition()}. | |
| 73 | + */ | |
| 74 | + public ConditionChecker() { | |
| 75 | + this(null, null); | |
| 76 | + checkState(!this.getClass().equals(ConditionChecker.class), "This constructor requires subclassing ConditionChecker"); | |
| 77 | + } | |
| 78 | + | |
| 79 | + public ConditionChecker(Callable<Boolean> condition) { | |
| 80 | + this(condition, DEFAULT_PERIOD_MILLIS); | |
| 81 | + } | |
| 82 | + | |
| 83 | + public ConditionChecker(final Callable<Boolean> condition, int periodMillis) { | |
| 84 | + this(null, new Predicate<Void>() { | |
| 85 | + @Override | |
| 86 | + public boolean apply(Void input) { | |
| 87 | + try { | |
| 88 | + return condition.call(); | |
| 89 | + } catch (Exception e) { | |
| 90 | + logger.error("Evaluation of condition threw exception", e); | |
| 91 | + return false; | |
| 92 | + } | |
| 93 | + } | |
| 94 | + }, periodMillis); | |
| 95 | + } | |
| 96 | + | |
| 97 | + public <T> ConditionChecker(T input, Predicate<? super T> predicate) { | |
| 98 | + this(input, predicate, DEFAULT_PERIOD_MILLIS); | |
| 99 | + } | |
| 100 | + | |
| 101 | + @SuppressWarnings("unchecked") | |
| 102 | + public <T> ConditionChecker(T input, Predicate<? super T> predicate, int periodMillis) { | |
| 103 | + this.input = input; | |
| 104 | + this.predicate = (Predicate<Object>) predicate; | |
| 105 | + lock = new ReentrantLock(); | |
| 106 | + condition = lock.newCondition(); | |
| 107 | + timer = new Timer("condition-checker", true); | |
| 108 | + timer.schedule(new TimerTask() { | |
| 109 | + @Override | |
| 110 | + public void run() { | |
| 111 | + checkCondition(); | |
| 112 | + } | |
| 113 | + }, 0, periodMillis); | |
| 114 | + } | |
| 115 | + | |
| 116 | + /** | |
| 117 | + * Waits until the predicate becomes true, | |
| 118 | + * or a timeout occurs, whichever happens first. | |
| 119 | + * | |
| 120 | + * @param timeoutMillis timeout in milliseconds | |
| 121 | + */ | |
| 122 | + public void await(long timeoutMillis) { | |
| 123 | + boolean interrupted = false; | |
| 124 | + long nanos = MILLISECONDS.toNanos(timeoutMillis); | |
| 125 | + lock.lock(); | |
| 126 | + try { | |
| 127 | + while (!evalCondition()) { | |
| 128 | + if (nanos <= 0L) | |
| 129 | + fail(String.format("Timeout after %s milliseconds while waiting for condition", timeoutMillis)); | |
| 130 | + try { | |
| 131 | + nanos = condition.awaitNanos(nanos); | |
| 132 | + } catch (InterruptedException e) { | |
| 133 | + interrupted = true; | |
| 134 | + } | |
| 135 | + } | |
| 136 | + } finally { | |
| 137 | + timer.cancel(); | |
| 138 | + if (interrupted) | |
| 139 | + Thread.currentThread().interrupt(); | |
| 140 | + } | |
| 141 | + } | |
| 142 | + | |
| 143 | + private void checkCondition() { | |
| 144 | + lock.lock(); | |
| 145 | + try { | |
| 146 | + if (evalCondition()) { | |
| 147 | + condition.signal(); | |
| 148 | + } | |
| 149 | + } finally { | |
| 150 | + lock.unlock(); | |
| 151 | + } | |
| 152 | + } | |
| 153 | + | |
| 154 | + protected boolean evalCondition() { | |
| 155 | + return predicate.apply(input); | |
| 156 | + } | |
| 157 | + | |
| 158 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +2 −2
| @@ -28,10 +28,10 @@ | ||
| 28 | 28 | * Test {@link ResultSet#wasApplied()} for conditional updates. |
| 29 | 29 | */ |
| 30 | 30 | @CassandraVersion(major = 2.0, description = "Conditional Updates requires 2.0+.") |
| 31 | -public class ConditionalUpdateTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 31 | +public class ConditionalUpdateTest extends CCMTestsSupport { | |
| 32 | 32 | |
| 33 | 33 | @Override |
| 34 | - protected Collection<String> getTableDefinitions() { | |
| 34 | + public Collection<String> createTestFixtures() { | |
| 35 | 35 | return Collections.singletonList("CREATE TABLE test(k1 int, k2 int, v int, PRIMARY KEY (k1, k2))"); |
| 36 | 36 | } |
| 37 | 37 |
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +590 −604
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy; |
| 24 | 24 | import com.datastax.driver.core.policies.RoundRobinPolicy; |
| 25 | 25 | import com.datastax.driver.core.policies.TokenAwarePolicy; |
| 26 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 26 | 27 | import org.slf4j.Logger; |
| 27 | 28 | import org.slf4j.LoggerFactory; |
| 28 | 29 | import org.testng.annotations.Test; |
| @@ -31,713 +32,698 @@ | ||
| 31 | 32 | import java.util.EnumSet; |
| 32 | 33 | import java.util.List; |
| 33 | 34 | import java.util.Set; |
| 34 | - | |
| 35 | -import static com.datastax.driver.core.TestUtils.stopAndWait; | |
| 35 | +import java.util.concurrent.TimeUnit; | |
| 36 | + | |
| 37 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 38 | +import static com.datastax.driver.core.TestUtils.IP_PREFIX; | |
| 39 | +import static com.datastax.driver.core.TestUtils.ipOfNode; | |
| 40 | +import static java.util.Collections.emptyList; | |
| 41 | +import static java.util.Collections.singletonList; | |
| 36 | 42 | import static org.testng.Assert.assertTrue; |
| 37 | 43 | import static org.testng.Assert.fail; |
| 38 | 44 | |
| 45 | +@SuppressWarnings("unused") | |
| 46 | +@CreateCCM(PER_METHOD) | |
| 47 | +@CCMConfig( | |
| 48 | + dirtiesContext = true, | |
| 49 | + createKeyspace = false, | |
| 50 | + config = { | |
| 51 | + "hinted_handoff_enabled:true", | |
| 52 | + "phi_convict_threshold:1", | |
| 53 | + "read_request_timeout_in_ms:100000", | |
| 54 | + "write_request_timeout_in_ms:100000"} | |
| 55 | +) | |
| 39 | 56 | public class ConsistencyTest extends AbstractPoliciesTest { |
| 40 | 57 | |
| 41 | - private static final Logger logger = LoggerFactory.getLogger(CCMBridge.class); | |
| 58 | + private static final Logger logger = LoggerFactory.getLogger(ConsistencyTest.class); | |
| 59 | + | |
| 60 | + private Cluster.Builder tokenAwareRoundRobin() { | |
| 61 | + return Cluster.builder() | |
| 62 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 63 | + .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); | |
| 64 | + } | |
| 65 | + | |
| 66 | + private Cluster.Builder tokenAwareRoundRobinNoShuffle() { | |
| 67 | + return Cluster.builder() | |
| 68 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 69 | + .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)); | |
| 70 | + } | |
| 71 | + | |
| 72 | + private Cluster.Builder tokenAwareRoundRobinDowngrading() { | |
| 73 | + return Cluster.builder() | |
| 74 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 75 | + .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) | |
| 76 | + .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 77 | + } | |
| 78 | + | |
| 79 | + private Cluster.Builder tokenAwareRoundRobinNoShuffleDowngrading() { | |
| 80 | + return Cluster.builder() | |
| 81 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 82 | + .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)) | |
| 83 | + .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 84 | + } | |
| 85 | + | |
| 86 | + private Cluster.Builder roundRobinDowngrading() { | |
| 87 | + return Cluster.builder() | |
| 88 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 89 | + .withLoadBalancingPolicy(new RoundRobinPolicy()) | |
| 90 | + .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 91 | + } | |
| 92 | + | |
| 93 | + private Cluster.Builder tokenAwareDCAwareRoundRobinNoShuffleDowngrading() { | |
| 94 | + return Cluster.builder() | |
| 95 | + .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 96 | + .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), false)) | |
| 97 | + .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 98 | + } | |
| 42 | 99 | |
| 43 | 100 | @Test(groups = "long") |
| 101 | + @CCMConfig( | |
| 102 | + numberOfNodes = 3, | |
| 103 | + clusterProvider = "tokenAwareRoundRobin") | |
| 44 | 104 | public void testRFOneTokenAware() throws Throwable { |
| 45 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); | |
| 46 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 47 | - try { | |
| 48 | 105 | |
| 49 | - createSchema(c.session, 1); | |
| 50 | - init(c, 12, ConsistencyLevel.ONE); | |
| 51 | - query(c, 12, ConsistencyLevel.ONE); | |
| 52 | - | |
| 53 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 54 | - assertQueried(CCMBridge.IP_PREFIX + '2', 12); | |
| 55 | - assertQueried(CCMBridge.IP_PREFIX + '3', 0); | |
| 56 | - | |
| 57 | - resetCoordinators(); | |
| 58 | - stopAndWait(c, 2); | |
| 59 | - | |
| 60 | - List<ConsistencyLevel> acceptedList = Arrays.asList(ConsistencyLevel.ANY); | |
| 61 | - | |
| 62 | - List<ConsistencyLevel> failList = Arrays.asList( | |
| 63 | - ConsistencyLevel.ONE, | |
| 64 | - ConsistencyLevel.TWO, | |
| 65 | - ConsistencyLevel.THREE, | |
| 66 | - ConsistencyLevel.QUORUM, | |
| 67 | - ConsistencyLevel.ALL, | |
| 68 | - ConsistencyLevel.LOCAL_QUORUM, | |
| 69 | - ConsistencyLevel.EACH_QUORUM); | |
| 70 | - | |
| 71 | - // Test successful writes | |
| 72 | - for (ConsistencyLevel cl : acceptedList) { | |
| 73 | - try { | |
| 74 | - init(c, 12, cl); | |
| 75 | - } catch (Exception e) { | |
| 76 | - fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 77 | - } | |
| 78 | - } | |
| 106 | + createSchema(1); | |
| 107 | + init(12, ConsistencyLevel.ONE); | |
| 108 | + query(12, ConsistencyLevel.ONE); | |
| 109 | + | |
| 110 | + assertQueried(IP_PREFIX + '1', 0); | |
| 111 | + assertQueried(IP_PREFIX + '2', 12); | |
| 112 | + assertQueried(IP_PREFIX + '3', 0); | |
| 113 | + | |
| 114 | + resetCoordinators(); | |
| 115 | + stopAndWait(2); | |
| 116 | + | |
| 117 | + List<ConsistencyLevel> acceptedList = singletonList(ConsistencyLevel.ANY); | |
| 118 | + | |
| 119 | + List<ConsistencyLevel> failList = Arrays.asList( | |
| 120 | + ConsistencyLevel.ONE, | |
| 121 | + ConsistencyLevel.TWO, | |
| 122 | + ConsistencyLevel.THREE, | |
| 123 | + ConsistencyLevel.QUORUM, | |
| 124 | + ConsistencyLevel.ALL, | |
| 125 | + ConsistencyLevel.LOCAL_QUORUM, | |
| 126 | + ConsistencyLevel.EACH_QUORUM); | |
| 79 | 127 | |
| 80 | - // Test successful reads | |
| 81 | - for (ConsistencyLevel cl : acceptedList) { | |
| 82 | - try { | |
| 83 | - query(c, 12, cl); | |
| 84 | - } catch (InvalidQueryException e) { | |
| 85 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 86 | - "ANY ConsistencyLevel is only supported for writes"); | |
| 87 | - assertTrue(acceptableErrorMessages.contains(e.getMessage())); | |
| 88 | - } | |
| 128 | + // Test successful writes | |
| 129 | + for (ConsistencyLevel cl : acceptedList) { | |
| 130 | + try { | |
| 131 | + init(12, cl); | |
| 132 | + } catch (Exception e) { | |
| 133 | + fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 89 | 134 | } |
| 135 | + } | |
| 90 | 136 | |
| 91 | - // Test writes which should fail | |
| 92 | - for (ConsistencyLevel cl : failList) { | |
| 93 | - try { | |
| 94 | - init(c, 12, cl); | |
| 95 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 96 | - } catch (InvalidQueryException e) { | |
| 97 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 98 | - "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", | |
| 99 | - "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)"); | |
| 100 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 101 | - } catch (UnavailableException e) { | |
| 102 | - // expected to fail when the client has already marked the | |
| 103 | - // node as DOWN | |
| 104 | - } catch (WriteTimeoutException e) { | |
| 105 | - // expected to fail when the client hasn't marked the | |
| 106 | - // node as DOWN yet | |
| 107 | - } | |
| 137 | + // Test successful reads | |
| 138 | + for (ConsistencyLevel cl : acceptedList) { | |
| 139 | + try { | |
| 140 | + query(12, cl); | |
| 141 | + } catch (InvalidQueryException e) { | |
| 142 | + List<String> acceptableErrorMessages = singletonList( | |
| 143 | + "ANY ConsistencyLevel is only supported for writes"); | |
| 144 | + assertTrue(acceptableErrorMessages.contains(e.getMessage())); | |
| 108 | 145 | } |
| 146 | + } | |
| 109 | 147 | |
| 110 | - // Test reads which should fail | |
| 111 | - for (ConsistencyLevel cl : failList) { | |
| 112 | - try { | |
| 113 | - query(c, 12, cl); | |
| 114 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 115 | - } catch (InvalidQueryException e) { | |
| 116 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 117 | - "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", | |
| 118 | - "EACH_QUORUM ConsistencyLevel is only supported for writes"); | |
| 119 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 120 | - } catch (ReadTimeoutException e) { | |
| 121 | - // expected to fail when the client hasn't marked the | |
| 122 | - // node as DOWN yet | |
| 123 | - } catch (UnavailableException e) { | |
| 124 | - // expected to fail when the client has already marked the | |
| 125 | - // node as DOWN | |
| 126 | - } | |
| 148 | + // Test writes which should fail | |
| 149 | + for (ConsistencyLevel cl : failList) { | |
| 150 | + try { | |
| 151 | + init(12, cl); | |
| 152 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 153 | + } catch (InvalidQueryException e) { | |
| 154 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 155 | + "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", | |
| 156 | + "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)"); | |
| 157 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 158 | + } catch (UnavailableException e) { | |
| 159 | + // expected to fail when the client has already marked the | |
| 160 | + // node as DOWN | |
| 161 | + } catch (WriteTimeoutException e) { | |
| 162 | + // expected to fail when the client hasn't marked the | |
| 163 | + // node as DOWN yet | |
| 127 | 164 | } |
| 165 | + } | |
| 128 | 166 | |
| 129 | - } catch (Throwable e) { | |
| 130 | - c.errorOut(); | |
| 131 | - throw e; | |
| 132 | - } finally { | |
| 133 | - resetCoordinators(); | |
| 134 | - c.discard(); | |
| 167 | + // Test reads which should fail | |
| 168 | + for (ConsistencyLevel cl : failList) { | |
| 169 | + try { | |
| 170 | + query(12, cl); | |
| 171 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 172 | + } catch (InvalidQueryException e) { | |
| 173 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 174 | + "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", | |
| 175 | + "EACH_QUORUM ConsistencyLevel is only supported for writes"); | |
| 176 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 177 | + } catch (ReadTimeoutException e) { | |
| 178 | + // expected to fail when the client hasn't marked the | |
| 179 | + // node as DOWN yet | |
| 180 | + } catch (UnavailableException e) { | |
| 181 | + // expected to fail when the client has already marked the | |
| 182 | + // node as DOWN | |
| 183 | + } | |
| 135 | 184 | } |
| 136 | 185 | } |
| 137 | 186 | |
| 138 | 187 | @Test(groups = "long") |
| 188 | + @CCMConfig(numberOfNodes = 3, | |
| 189 | + clusterProvider = "tokenAwareRoundRobinNoShuffle") | |
| 139 | 190 | public void testRFTwoTokenAware() throws Throwable { |
| 140 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)); | |
| 141 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 142 | - try { | |
| 143 | - | |
| 144 | - createSchema(c.session, 2); | |
| 145 | - init(c, 12, ConsistencyLevel.TWO); | |
| 146 | - query(c, 12, ConsistencyLevel.TWO); | |
| 147 | - | |
| 148 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 149 | - assertQueried(CCMBridge.IP_PREFIX + '2', 12); | |
| 150 | - assertQueried(CCMBridge.IP_PREFIX + '3', 0); | |
| 151 | - | |
| 152 | - resetCoordinators(); | |
| 153 | - stopAndWait(c, 2); | |
| 154 | - | |
| 155 | - List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 156 | - ConsistencyLevel.ANY, | |
| 157 | - ConsistencyLevel.ONE | |
| 158 | - ); | |
| 159 | - | |
| 160 | - List<ConsistencyLevel> failList = Arrays.asList( | |
| 161 | - ConsistencyLevel.TWO, | |
| 162 | - ConsistencyLevel.QUORUM, | |
| 163 | - ConsistencyLevel.THREE, | |
| 164 | - ConsistencyLevel.ALL, | |
| 165 | - ConsistencyLevel.LOCAL_QUORUM, | |
| 166 | - ConsistencyLevel.EACH_QUORUM); | |
| 167 | - | |
| 168 | - // Test successful writes | |
| 169 | - for (ConsistencyLevel cl : acceptedList) { | |
| 170 | - try { | |
| 171 | - init(c, 12, cl); | |
| 172 | - } catch (Exception e) { | |
| 173 | - fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 174 | - } | |
| 191 | + createSchema(2); | |
| 192 | + init(12, ConsistencyLevel.TWO); | |
| 193 | + query(12, ConsistencyLevel.TWO); | |
| 194 | + | |
| 195 | + assertQueried(IP_PREFIX + '1', 0); | |
| 196 | + assertQueried(IP_PREFIX + '2', 12); | |
| 197 | + assertQueried(IP_PREFIX + '3', 0); | |
| 198 | + | |
| 199 | + resetCoordinators(); | |
| 200 | + stopAndWait(2); | |
| 201 | + | |
| 202 | + List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 203 | + ConsistencyLevel.ANY, | |
| 204 | + ConsistencyLevel.ONE | |
| 205 | + ); | |
| 206 | + | |
| 207 | + List<ConsistencyLevel> failList = Arrays.asList( | |
| 208 | + ConsistencyLevel.TWO, | |
| 209 | + ConsistencyLevel.QUORUM, | |
| 210 | + ConsistencyLevel.THREE, | |
| 211 | + ConsistencyLevel.ALL, | |
| 212 | + ConsistencyLevel.LOCAL_QUORUM, | |
| 213 | + ConsistencyLevel.EACH_QUORUM); | |
| 214 | + | |
| 215 | + // Test successful writes | |
| 216 | + for (ConsistencyLevel cl : acceptedList) { | |
| 217 | + try { | |
| 218 | + init(12, cl); | |
| 219 | + } catch (Exception e) { | |
| 220 | + fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 175 | 221 | } |
| 222 | + } | |
| 176 | 223 | |
| 177 | - // Test successful reads | |
| 178 | - for (ConsistencyLevel cl : acceptedList) { | |
| 179 | - try { | |
| 180 | - query(c, 12, cl); | |
| 181 | - } catch (InvalidQueryException e) { | |
| 182 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 183 | - "ANY ConsistencyLevel is only supported for writes"); | |
| 184 | - assertTrue(acceptableErrorMessages.contains(e.getMessage())); | |
| 185 | - } | |
| 224 | + // Test successful reads | |
| 225 | + for (ConsistencyLevel cl : acceptedList) { | |
| 226 | + try { | |
| 227 | + query(12, cl); | |
| 228 | + } catch (InvalidQueryException e) { | |
| 229 | + List<String> acceptableErrorMessages = singletonList( | |
| 230 | + "ANY ConsistencyLevel is only supported for writes"); | |
| 231 | + assertTrue(acceptableErrorMessages.contains(e.getMessage())); | |
| 186 | 232 | } |
| 233 | + } | |
| 187 | 234 | |
| 188 | - // Test writes which should fail | |
| 189 | - for (ConsistencyLevel cl : failList) { | |
| 190 | - try { | |
| 191 | - init(c, 12, cl); | |
| 192 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 193 | - } catch (InvalidQueryException e) { | |
| 194 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 195 | - "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", | |
| 196 | - "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)"); | |
| 197 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 198 | - } catch (UnavailableException e) { | |
| 199 | - // expected to fail when the client has already marked the | |
| 200 | - // node as DOWN | |
| 201 | - } catch (WriteTimeoutException e) { | |
| 202 | - // expected to fail when the client hasn't marked the | |
| 203 | - // node as DOWN yet | |
| 204 | - } | |
| 235 | + // Test writes which should fail | |
| 236 | + for (ConsistencyLevel cl : failList) { | |
| 237 | + try { | |
| 238 | + init(12, cl); | |
| 239 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 240 | + } catch (InvalidQueryException e) { | |
| 241 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 242 | + "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", | |
| 243 | + "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)"); | |
| 244 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 245 | + } catch (UnavailableException e) { | |
| 246 | + // expected to fail when the client has already marked the | |
| 247 | + // node as DOWN | |
| 248 | + } catch (WriteTimeoutException e) { | |
| 249 | + // expected to fail when the client hasn't marked the | |
| 250 | + // node as DOWN yet | |
| 205 | 251 | } |
| 252 | + } | |
| 206 | 253 | |
| 207 | - // Test reads which should fail | |
| 208 | - for (ConsistencyLevel cl : failList) { | |
| 209 | - try { | |
| 210 | - query(c, 12, cl); | |
| 211 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 212 | - } catch (InvalidQueryException e) { | |
| 213 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 214 | - "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", | |
| 215 | - "EACH_QUORUM ConsistencyLevel is only supported for writes"); | |
| 216 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 217 | - } catch (ReadTimeoutException e) { | |
| 218 | - // expected to fail when the client hasn't marked the | |
| 219 | - // node as DOWN yet | |
| 220 | - } catch (UnavailableException e) { | |
| 221 | - // expected to fail when the client has already marked the | |
| 222 | - // node as DOWN | |
| 223 | - } | |
| 254 | + // Test reads which should fail | |
| 255 | + for (ConsistencyLevel cl : failList) { | |
| 256 | + try { | |
| 257 | + query(12, cl); | |
| 258 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 259 | + } catch (InvalidQueryException e) { | |
| 260 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 261 | + "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", | |
| 262 | + "EACH_QUORUM ConsistencyLevel is only supported for writes"); | |
| 263 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 264 | + } catch (ReadTimeoutException e) { | |
| 265 | + // expected to fail when the client hasn't marked the | |
| 266 | + // node as DOWN yet | |
| 267 | + } catch (UnavailableException e) { | |
| 268 | + // expected to fail when the client has already marked the | |
| 269 | + // node as DOWN | |
| 224 | 270 | } |
| 225 | - | |
| 226 | - } catch (Throwable e) { | |
| 227 | - c.errorOut(); | |
| 228 | - throw e; | |
| 229 | - } finally { | |
| 230 | - resetCoordinators(); | |
| 231 | - c.discard(); | |
| 232 | 271 | } |
| 233 | 272 | } |
| 234 | 273 | |
| 235 | 274 | @Test(groups = "long") |
| 275 | + @CCMConfig(numberOfNodes = 3, | |
| 276 | + clusterProvider = "tokenAwareRoundRobinNoShuffle") | |
| 236 | 277 | public void testRFThreeTokenAware() throws Throwable { |
| 237 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)); | |
| 238 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 239 | - try { | |
| 240 | - | |
| 241 | - createSchema(c.session, 3); | |
| 242 | - init(c, 12, ConsistencyLevel.TWO); | |
| 243 | - query(c, 12, ConsistencyLevel.TWO); | |
| 244 | - | |
| 245 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 246 | - assertQueried(CCMBridge.IP_PREFIX + '2', 12); | |
| 247 | - assertQueried(CCMBridge.IP_PREFIX + '3', 0); | |
| 248 | - | |
| 249 | - resetCoordinators(); | |
| 250 | - stopAndWait(c, 2); | |
| 251 | - | |
| 252 | - Set<ConsistencyLevel> cls = EnumSet.allOf(ConsistencyLevel.class); | |
| 253 | - // Remove serial consistencies as they require conditional read/writes | |
| 254 | - cls.remove(ConsistencyLevel.SERIAL); | |
| 255 | - cls.remove(ConsistencyLevel.LOCAL_SERIAL); | |
| 256 | - | |
| 257 | - List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 258 | - ConsistencyLevel.ANY, | |
| 259 | - ConsistencyLevel.ONE, | |
| 260 | - ConsistencyLevel.TWO, | |
| 261 | - ConsistencyLevel.QUORUM, | |
| 262 | - ConsistencyLevel.LOCAL_QUORUM, | |
| 263 | - ConsistencyLevel.EACH_QUORUM | |
| 264 | - ); | |
| 265 | - | |
| 266 | - List<ConsistencyLevel> failList = Arrays.asList( | |
| 267 | - ConsistencyLevel.THREE, | |
| 268 | - ConsistencyLevel.ALL | |
| 269 | - ); | |
| 270 | - | |
| 271 | - | |
| 272 | - // Test successful writes | |
| 273 | - for (ConsistencyLevel cl : acceptedList) { | |
| 274 | - try { | |
| 275 | - init(c, 12, cl); | |
| 276 | - } catch (Exception e) { | |
| 277 | - fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 278 | - } | |
| 278 | + createSchema(3); | |
| 279 | + init(12, ConsistencyLevel.TWO); | |
| 280 | + query(12, ConsistencyLevel.TWO); | |
| 281 | + | |
| 282 | + assertQueried(IP_PREFIX + '1', 0); | |
| 283 | + assertQueried(IP_PREFIX + '2', 12); | |
| 284 | + assertQueried(IP_PREFIX + '3', 0); | |
| 285 | + | |
| 286 | + resetCoordinators(); | |
| 287 | + stopAndWait(2); | |
| 288 | + | |
| 289 | + Set<ConsistencyLevel> cls = EnumSet.allOf(ConsistencyLevel.class); | |
| 290 | + // Remove serial consistencies as they require conditional read/writes | |
| 291 | + cls.remove(ConsistencyLevel.SERIAL); | |
| 292 | + cls.remove(ConsistencyLevel.LOCAL_SERIAL); | |
| 293 | + | |
| 294 | + List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 295 | + ConsistencyLevel.ANY, | |
| 296 | + ConsistencyLevel.ONE, | |
| 297 | + ConsistencyLevel.TWO, | |
| 298 | + ConsistencyLevel.QUORUM, | |
| 299 | + ConsistencyLevel.LOCAL_QUORUM, | |
| 300 | + ConsistencyLevel.EACH_QUORUM | |
| 301 | + ); | |
| 302 | + | |
| 303 | + List<ConsistencyLevel> failList = Arrays.asList( | |
| 304 | + ConsistencyLevel.THREE, | |
| 305 | + ConsistencyLevel.ALL | |
| 306 | + ); | |
| 307 | + | |
| 308 | + | |
| 309 | + // Test successful writes | |
| 310 | + for (ConsistencyLevel cl : acceptedList) { | |
| 311 | + try { | |
| 312 | + init(12, cl); | |
| 313 | + } catch (Exception e) { | |
| 314 | + fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 279 | 315 | } |
| 316 | + } | |
| 280 | 317 | |
| 281 | - // Test successful reads | |
| 282 | - for (ConsistencyLevel cl : acceptedList) { | |
| 283 | - try { | |
| 284 | - query(c, 12, cl); | |
| 285 | - } catch (InvalidQueryException e) { | |
| 286 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 287 | - "ANY ConsistencyLevel is only supported for writes", | |
| 288 | - "EACH_QUORUM ConsistencyLevel is only supported for writes" | |
| 289 | - ); | |
| 290 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage()); | |
| 291 | - } | |
| 318 | + // Test successful reads | |
| 319 | + for (ConsistencyLevel cl : acceptedList) { | |
| 320 | + try { | |
| 321 | + query(12, cl); | |
| 322 | + } catch (InvalidQueryException e) { | |
| 323 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 324 | + "ANY ConsistencyLevel is only supported for writes", | |
| 325 | + "EACH_QUORUM ConsistencyLevel is only supported for writes" | |
| 326 | + ); | |
| 327 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage()); | |
| 292 | 328 | } |
| 329 | + } | |
| 293 | 330 | |
| 294 | - // Test writes which should fail | |
| 295 | - for (ConsistencyLevel cl : failList) { | |
| 296 | - try { | |
| 297 | - init(c, 12, cl); | |
| 298 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 299 | - } catch (UnavailableException e) { | |
| 300 | - // expected to fail when the client has already marked the | |
| 301 | - // node as DOWN | |
| 302 | - } catch (WriteTimeoutException e) { | |
| 303 | - // expected to fail when the client hasn't marked the | |
| 304 | - // node as DOWN yet | |
| 305 | - } | |
| 331 | + // Test writes which should fail | |
| 332 | + for (ConsistencyLevel cl : failList) { | |
| 333 | + try { | |
| 334 | + init(12, cl); | |
| 335 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 336 | + } catch (UnavailableException e) { | |
| 337 | + // expected to fail when the client has already marked the | |
| 338 | + // node as DOWN | |
| 339 | + } catch (WriteTimeoutException e) { | |
| 340 | + // expected to fail when the client hasn't marked the | |
| 341 | + // node as DOWN yet | |
| 306 | 342 | } |
| 343 | + } | |
| 307 | 344 | |
| 308 | - // Test reads which should fail | |
| 309 | - for (ConsistencyLevel cl : failList) { | |
| 310 | - try { | |
| 311 | - query(c, 12, cl); | |
| 312 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 313 | - } catch (ReadTimeoutException e) { | |
| 314 | - // expected to fail when the client hasn't marked the | |
| 315 | - // node as DOWN yet | |
| 316 | - } catch (UnavailableException e) { | |
| 317 | - // expected to fail when the client has already marked the | |
| 318 | - // node as DOWN | |
| 319 | - } | |
| 345 | + // Test reads which should fail | |
| 346 | + for (ConsistencyLevel cl : failList) { | |
| 347 | + try { | |
| 348 | + query(12, cl); | |
| 349 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 350 | + } catch (ReadTimeoutException e) { | |
| 351 | + // expected to fail when the client hasn't marked the | |
| 352 | + // node as DOWN yet | |
| 353 | + } catch (UnavailableException e) { | |
| 354 | + // expected to fail when the client has already marked the | |
| 355 | + // node as DOWN | |
| 320 | 356 | } |
| 321 | - | |
| 322 | - } catch (Throwable e) { | |
| 323 | - c.errorOut(); | |
| 324 | - throw e; | |
| 325 | - } finally { | |
| 326 | - resetCoordinators(); | |
| 327 | - c.discard(); | |
| 328 | 357 | } |
| 329 | 358 | } |
| 330 | 359 | |
| 331 | 360 | |
| 332 | 361 | @Test(groups = "long") |
| 362 | + @CCMConfig(numberOfNodes = 3, | |
| 363 | + clusterProvider = "tokenAwareRoundRobinDowngrading") | |
| 333 | 364 | public void testRFOneDowngradingCL() throws Throwable { |
| 334 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 335 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 336 | - try { | |
| 337 | - | |
| 338 | - createSchema(c.session, 1); | |
| 339 | - init(c, 12, ConsistencyLevel.ONE); | |
| 340 | - query(c, 12, ConsistencyLevel.ONE); | |
| 341 | - | |
| 342 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 343 | - assertQueried(CCMBridge.IP_PREFIX + '2', 12); | |
| 344 | - assertQueried(CCMBridge.IP_PREFIX + '3', 0); | |
| 345 | - | |
| 346 | - resetCoordinators(); | |
| 347 | - stopAndWait(c, 2); | |
| 348 | - | |
| 349 | - List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 350 | - ConsistencyLevel.ANY | |
| 351 | - ); | |
| 352 | - | |
| 353 | - List<ConsistencyLevel> failList = Arrays.asList( | |
| 354 | - ConsistencyLevel.ONE, | |
| 355 | - ConsistencyLevel.TWO, | |
| 356 | - ConsistencyLevel.THREE, | |
| 357 | - ConsistencyLevel.QUORUM, | |
| 358 | - ConsistencyLevel.ALL, | |
| 359 | - ConsistencyLevel.LOCAL_QUORUM, | |
| 360 | - ConsistencyLevel.EACH_QUORUM); | |
| 361 | - | |
| 362 | - // Test successful writes | |
| 363 | - for (ConsistencyLevel cl : acceptedList) { | |
| 364 | - try { | |
| 365 | - init(c, 12, cl); | |
| 366 | - } catch (Exception e) { | |
| 367 | - fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 368 | - } | |
| 365 | + createSchema(1); | |
| 366 | + init(12, ConsistencyLevel.ONE); | |
| 367 | + query(12, ConsistencyLevel.ONE); | |
| 368 | + | |
| 369 | + assertQueried(IP_PREFIX + '1', 0); | |
| 370 | + assertQueried(IP_PREFIX + '2', 12); | |
| 371 | + assertQueried(IP_PREFIX + '3', 0); | |
| 372 | + | |
| 373 | + resetCoordinators(); | |
| 374 | + stopAndWait(2); | |
| 375 | + | |
| 376 | + List<ConsistencyLevel> acceptedList = singletonList( | |
| 377 | + ConsistencyLevel.ANY | |
| 378 | + ); | |
| 379 | + | |
| 380 | + List<ConsistencyLevel> failList = Arrays.asList( | |
| 381 | + ConsistencyLevel.ONE, | |
| 382 | + ConsistencyLevel.TWO, | |
| 383 | + ConsistencyLevel.THREE, | |
| 384 | + ConsistencyLevel.QUORUM, | |
| 385 | + ConsistencyLevel.ALL, | |
| 386 | + ConsistencyLevel.LOCAL_QUORUM, | |
| 387 | + ConsistencyLevel.EACH_QUORUM); | |
| 388 | + | |
| 389 | + // Test successful writes | |
| 390 | + for (ConsistencyLevel cl : acceptedList) { | |
| 391 | + try { | |
| 392 | + init(12, cl); | |
| 393 | + } catch (Exception e) { | |
| 394 | + fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 369 | 395 | } |
| 396 | + } | |
| 370 | 397 | |
| 371 | - // Test successful reads | |
| 372 | - for (ConsistencyLevel cl : acceptedList) { | |
| 373 | - try { | |
| 374 | - query(c, 12, cl); | |
| 375 | - } catch (InvalidQueryException e) { | |
| 376 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 377 | - "ANY ConsistencyLevel is only supported for writes"); | |
| 378 | - assertTrue(acceptableErrorMessages.contains(e.getMessage())); | |
| 379 | - } | |
| 398 | + // Test successful reads | |
| 399 | + for (ConsistencyLevel cl : acceptedList) { | |
| 400 | + try { | |
| 401 | + query(12, cl); | |
| 402 | + } catch (InvalidQueryException e) { | |
| 403 | + List<String> acceptableErrorMessages = singletonList( | |
| 404 | + "ANY ConsistencyLevel is only supported for writes"); | |
| 405 | + assertTrue(acceptableErrorMessages.contains(e.getMessage())); | |
| 380 | 406 | } |
| 407 | + } | |
| 381 | 408 | |
| 382 | - // Test writes which should fail | |
| 383 | - for (ConsistencyLevel cl : failList) { | |
| 384 | - try { | |
| 385 | - init(c, 12, cl); | |
| 386 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 387 | - } catch (UnavailableException e) { | |
| 388 | - // expected to fail when the client has already marked the | |
| 389 | - // node as DOWN | |
| 390 | - } catch (WriteTimeoutException e) { | |
| 391 | - // expected to fail when the client hasn't marked the | |
| 392 | - // node as DOWN yet | |
| 393 | - } | |
| 409 | + // Test writes which should fail | |
| 410 | + for (ConsistencyLevel cl : failList) { | |
| 411 | + try { | |
| 412 | + init(12, cl); | |
| 413 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 414 | + } catch (UnavailableException e) { | |
| 415 | + // expected to fail when the client has already marked the | |
| 416 | + // node as DOWN | |
| 417 | + } catch (WriteTimeoutException e) { | |
| 418 | + // expected to fail when the client hasn't marked the | |
| 419 | + // node as DOWN yet | |
| 394 | 420 | } |
| 421 | + } | |
| 395 | 422 | |
| 396 | - // Test reads which should fail | |
| 397 | - for (ConsistencyLevel cl : failList) { | |
| 398 | - try { | |
| 399 | - query(c, 12, cl); | |
| 400 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 401 | - } catch (InvalidQueryException e) { | |
| 402 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 403 | - "EACH_QUORUM ConsistencyLevel is only supported for writes" | |
| 404 | - ); | |
| 405 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage()); | |
| 406 | - } catch (ReadTimeoutException e) { | |
| 407 | - // expected to fail when the client hasn't marked the | |
| 408 | - // node as DOWN yet | |
| 409 | - } catch (UnavailableException e) { | |
| 410 | - // expected to fail when the client has already marked the | |
| 411 | - // node as DOWN | |
| 412 | - } | |
| 423 | + // Test reads which should fail | |
| 424 | + for (ConsistencyLevel cl : failList) { | |
| 425 | + try { | |
| 426 | + query(12, cl); | |
| 427 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 428 | + } catch (InvalidQueryException e) { | |
| 429 | + List<String> acceptableErrorMessages = singletonList( | |
| 430 | + "EACH_QUORUM ConsistencyLevel is only supported for writes" | |
| 431 | + ); | |
| 432 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage()); | |
| 433 | + } catch (ReadTimeoutException e) { | |
| 434 | + // expected to fail when the client hasn't marked the | |
| 435 | + // node as DOWN yet | |
| 436 | + } catch (UnavailableException e) { | |
| 437 | + // expected to fail when the client has already marked the | |
| 438 | + // node as DOWN | |
| 413 | 439 | } |
| 414 | - | |
| 415 | - } catch (Throwable e) { | |
| 416 | - c.errorOut(); | |
| 417 | - throw e; | |
| 418 | - } finally { | |
| 419 | - resetCoordinators(); | |
| 420 | - c.discard(); | |
| 421 | 440 | } |
| 422 | 441 | } |
| 423 | 442 | |
| 424 | 443 | @Test(groups = "long") |
| 444 | + @CCMConfig(numberOfNodes = 3, | |
| 445 | + clusterProvider = "tokenAwareRoundRobinNoShuffleDowngrading") | |
| 425 | 446 | public void testRFTwoDowngradingCL() throws Throwable { |
| 426 | - Cluster.Builder builder = Cluster.builder() | |
| 427 | - .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)) | |
| 428 | - .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 429 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 430 | - try { | |
| 431 | - | |
| 432 | - createSchema(c.session, 2); | |
| 433 | - init(c, 12, ConsistencyLevel.TWO); | |
| 434 | - query(c, 12, ConsistencyLevel.TWO); | |
| 435 | - | |
| 436 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 437 | - assertQueried(CCMBridge.IP_PREFIX + '2', 12); | |
| 438 | - assertQueried(CCMBridge.IP_PREFIX + '3', 0); | |
| 439 | - | |
| 440 | - resetCoordinators(); | |
| 441 | - stopAndWait(c, 2); | |
| 442 | - | |
| 443 | - Set<ConsistencyLevel> acceptedList = EnumSet.allOf(ConsistencyLevel.class); | |
| 444 | - // Remove serial consistencies as they require conditional read/writes | |
| 445 | - acceptedList.remove(ConsistencyLevel.SERIAL); | |
| 446 | - acceptedList.remove(ConsistencyLevel.LOCAL_SERIAL); | |
| 447 | - | |
| 448 | - // Test successful writes | |
| 449 | - for (ConsistencyLevel cl : acceptedList) { | |
| 450 | - try { | |
| 451 | - init(c, 12, cl); | |
| 452 | - } catch (Exception e) { | |
| 453 | - fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 454 | - } | |
| 447 | + createSchema(2); | |
| 448 | + init(12, ConsistencyLevel.TWO); | |
| 449 | + query(12, ConsistencyLevel.TWO); | |
| 450 | + | |
| 451 | + assertQueried(IP_PREFIX + '1', 0); | |
| 452 | + assertQueried(IP_PREFIX + '2', 12); | |
| 453 | + assertQueried(IP_PREFIX + '3', 0); | |
| 454 | + | |
| 455 | + resetCoordinators(); | |
| 456 | + stopAndWait(2); | |
| 457 | + | |
| 458 | + Set<ConsistencyLevel> acceptedList = EnumSet.allOf(ConsistencyLevel.class); | |
| 459 | + // Remove serial consistencies as they require conditional read/writes | |
| 460 | + acceptedList.remove(ConsistencyLevel.SERIAL); | |
| 461 | + acceptedList.remove(ConsistencyLevel.LOCAL_SERIAL); | |
| 462 | + | |
| 463 | + // Test successful writes | |
| 464 | + for (ConsistencyLevel cl : acceptedList) { | |
| 465 | + try { | |
| 466 | + init(12, cl); | |
| 467 | + } catch (Exception e) { | |
| 468 | + fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 455 | 469 | } |
| 470 | + } | |
| 456 | 471 | |
| 457 | - // Test successful reads | |
| 458 | - for (ConsistencyLevel cl : acceptedList) { | |
| 459 | - try { | |
| 460 | - query(c, 12, cl); | |
| 461 | - } catch (InvalidQueryException e) { | |
| 462 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 463 | - "ANY ConsistencyLevel is only supported for writes", | |
| 464 | - "EACH_QUORUM ConsistencyLevel is only supported for writes" | |
| 465 | - ); | |
| 466 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage()); | |
| 467 | - } | |
| 472 | + // Test successful reads | |
| 473 | + for (ConsistencyLevel cl : acceptedList) { | |
| 474 | + try { | |
| 475 | + query(12, cl); | |
| 476 | + } catch (InvalidQueryException e) { | |
| 477 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 478 | + "ANY ConsistencyLevel is only supported for writes", | |
| 479 | + "EACH_QUORUM ConsistencyLevel is only supported for writes" | |
| 480 | + ); | |
| 481 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage()); | |
| 468 | 482 | } |
| 469 | - | |
| 470 | - } catch (Throwable e) { | |
| 471 | - c.errorOut(); | |
| 472 | - throw e; | |
| 473 | - } finally { | |
| 474 | - resetCoordinators(); | |
| 475 | - c.discard(); | |
| 476 | 483 | } |
| 477 | 484 | } |
| 478 | 485 | |
| 479 | 486 | @Test(groups = "long") |
| 487 | + @CCMConfig(numberOfNodes = 3, | |
| 488 | + clusterProvider = "roundRobinDowngrading") | |
| 480 | 489 | public void testRFThreeRoundRobinDowngradingCL() throws Throwable { |
| 481 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()).withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 482 | - testRFThreeDowngradingCL(builder); | |
| 490 | + testRFThreeDowngradingCL(); | |
| 483 | 491 | } |
| 484 | 492 | |
| 485 | 493 | @Test(groups = "long") |
| 494 | + @CCMConfig(numberOfNodes = 3, | |
| 495 | + clusterProvider = "tokenAwareRoundRobinNoShuffleDowngrading") | |
| 486 | 496 | public void testRFThreeTokenAwareDowngradingCL() throws Throwable { |
| 487 | - Cluster.Builder builder = Cluster.builder() | |
| 488 | - .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)) | |
| 489 | - .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 490 | - testRFThreeDowngradingCL(builder); | |
| 497 | + testRFThreeDowngradingCL(); | |
| 491 | 498 | } |
| 492 | 499 | |
| 493 | - public void testRFThreeDowngradingCL(Cluster.Builder builder) throws Throwable { | |
| 494 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 500 | + private void testRFThreeDowngradingCL() throws Throwable { | |
| 501 | + | |
| 502 | + createSchema(3); | |
| 503 | + init(12, ConsistencyLevel.ALL); | |
| 504 | + query(12, ConsistencyLevel.ALL); | |
| 505 | + | |
| 495 | 506 | try { |
| 507 | + // This test catches TokenAwarePolicy | |
| 508 | + // However, full tests in LoadBalancingPolicyTest.java | |
| 509 | + assertQueried(IP_PREFIX + '1', 0); | |
| 510 | + assertQueried(IP_PREFIX + '2', 12); | |
| 511 | + assertQueried(IP_PREFIX + '3', 0); | |
| 512 | + } catch (AssertionError e) { | |
| 513 | + // This test catches RoundRobinPolicy | |
| 514 | + assertQueried(IP_PREFIX + '1', 4); | |
| 515 | + assertQueried(IP_PREFIX + '2', 4); | |
| 516 | + assertQueried(IP_PREFIX + '3', 4); | |
| 517 | + } | |
| 496 | 518 | |
| 497 | - createSchema(c.session, 3); | |
| 498 | - init(c, 12, ConsistencyLevel.ALL); | |
| 499 | - query(c, 12, ConsistencyLevel.ALL); | |
| 519 | + resetCoordinators(); | |
| 520 | + stopAndWait(2); | |
| 500 | 521 | |
| 501 | - try { | |
| 502 | - // This test catches TokenAwarePolicy | |
| 503 | - // However, full tests in LoadBalancingPolicyTest.java | |
| 504 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 505 | - assertQueried(CCMBridge.IP_PREFIX + '2', 12); | |
| 506 | - assertQueried(CCMBridge.IP_PREFIX + '3', 0); | |
| 507 | - } catch (AssertionError e) { | |
| 508 | - // This test catches RoundRobinPolicy | |
| 509 | - assertQueried(CCMBridge.IP_PREFIX + '1', 4); | |
| 510 | - assertQueried(CCMBridge.IP_PREFIX + '2', 4); | |
| 511 | - assertQueried(CCMBridge.IP_PREFIX + '3', 4); | |
| 512 | - } | |
| 522 | + Set<ConsistencyLevel> acceptedList = EnumSet.allOf(ConsistencyLevel.class); | |
| 523 | + // Remove serial consistencies as they require conditional read/writes | |
| 524 | + acceptedList.remove(ConsistencyLevel.SERIAL); | |
| 525 | + acceptedList.remove(ConsistencyLevel.LOCAL_SERIAL); | |
| 513 | 526 | |
| 514 | - resetCoordinators(); | |
| 515 | - stopAndWait(c, 2); | |
| 516 | - | |
| 517 | - Set<ConsistencyLevel> acceptedList = EnumSet.allOf(ConsistencyLevel.class); | |
| 518 | - // Remove serial consistencies as they require conditional read/writes | |
| 519 | - acceptedList.remove(ConsistencyLevel.SERIAL); | |
| 520 | - acceptedList.remove(ConsistencyLevel.LOCAL_SERIAL); | |
| 521 | - | |
| 522 | - // Test successful writes | |
| 523 | - for (ConsistencyLevel cl : acceptedList) { | |
| 524 | - try { | |
| 525 | - init(c, 12, cl); | |
| 526 | - } catch (Exception e) { | |
| 527 | - fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 528 | - } | |
| 527 | + // Test successful writes | |
| 528 | + for (ConsistencyLevel cl : acceptedList) { | |
| 529 | + try { | |
| 530 | + init(12, cl); | |
| 531 | + } catch (Exception e) { | |
| 532 | + fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 529 | 533 | } |
| 534 | + } | |
| 530 | 535 | |
| 531 | - // Test successful reads | |
| 532 | - for (ConsistencyLevel cl : acceptedList) { | |
| 533 | - try { | |
| 534 | - query(c, 12, cl); | |
| 535 | - } catch (InvalidQueryException e) { | |
| 536 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 537 | - "ANY ConsistencyLevel is only supported for writes", | |
| 538 | - "EACH_QUORUM ConsistencyLevel is only supported for writes" | |
| 539 | - ); | |
| 540 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage()); | |
| 541 | - } | |
| 536 | + // Test successful reads | |
| 537 | + for (ConsistencyLevel cl : acceptedList) { | |
| 538 | + try { | |
| 539 | + query(12, cl); | |
| 540 | + } catch (InvalidQueryException e) { | |
| 541 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 542 | + "ANY ConsistencyLevel is only supported for writes", | |
| 543 | + "EACH_QUORUM ConsistencyLevel is only supported for writes" | |
| 544 | + ); | |
| 545 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), "Got unexpected message " + e.getMessage()); | |
| 542 | 546 | } |
| 543 | - | |
| 544 | - } catch (Throwable e) { | |
| 545 | - c.errorOut(); | |
| 546 | - throw e; | |
| 547 | - } finally { | |
| 548 | - resetCoordinators(); | |
| 549 | - c.discard(); | |
| 550 | 547 | } |
| 551 | 548 | } |
| 552 | 549 | |
| 553 | 550 | @Test(groups = "long") |
| 551 | + @CCMConfig( | |
| 552 | + numberOfNodes = {3, 3}, | |
| 553 | + clusterProvider = "tokenAwareRoundRobinNoShuffleDowngrading" | |
| 554 | + ) | |
| 554 | 555 | public void testRFThreeDowngradingCLTwoDCs() throws Throwable { |
| 555 | - Cluster.Builder builder = Cluster.builder() | |
| 556 | - .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)) | |
| 557 | - .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 558 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder); | |
| 559 | - try { | |
| 560 | - | |
| 561 | - createMultiDCSchema(c.session, 3, 3); | |
| 562 | - init(c, 12, ConsistencyLevel.TWO); | |
| 563 | - query(c, 12, ConsistencyLevel.TWO); | |
| 564 | - | |
| 565 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 566 | - assertQueried(CCMBridge.IP_PREFIX + '2', 12); | |
| 567 | - assertQueried(CCMBridge.IP_PREFIX + '3', 0); | |
| 568 | - assertQueried(CCMBridge.IP_PREFIX + '4', 0); | |
| 569 | - assertQueried(CCMBridge.IP_PREFIX + '5', 0); | |
| 570 | - assertQueried(CCMBridge.IP_PREFIX + '6', 0); | |
| 571 | - | |
| 572 | - resetCoordinators(); | |
| 573 | - logger.info("Stopping node 3..."); | |
| 574 | - stopAndWait(c, 3); | |
| 575 | - logger.info("Node 3 stopped."); | |
| 576 | - | |
| 577 | - List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 578 | - ConsistencyLevel.ANY, | |
| 579 | - ConsistencyLevel.ONE, | |
| 580 | - ConsistencyLevel.TWO, | |
| 581 | - ConsistencyLevel.QUORUM, | |
| 582 | - ConsistencyLevel.THREE, | |
| 583 | - ConsistencyLevel.ALL, | |
| 584 | - ConsistencyLevel.LOCAL_QUORUM, | |
| 585 | - ConsistencyLevel.EACH_QUORUM | |
| 586 | - ); | |
| 587 | - | |
| 588 | - List<ConsistencyLevel> failList = Arrays.asList(); | |
| 589 | - | |
| 590 | - // Test successful writes | |
| 591 | - for (ConsistencyLevel cl : acceptedList) { | |
| 592 | - logger.info("Test successful init(): " + cl); | |
| 593 | - try { | |
| 594 | - init(c, 12, cl); | |
| 595 | - } catch (Exception e) { | |
| 596 | - fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 597 | - } | |
| 556 | + createMultiDCSchema(3, 3); | |
| 557 | + init(12, ConsistencyLevel.TWO); | |
| 558 | + query(12, ConsistencyLevel.TWO); | |
| 559 | + | |
| 560 | + assertQueried(IP_PREFIX + '1', 0); | |
| 561 | + assertQueried(IP_PREFIX + '2', 12); | |
| 562 | + assertQueried(IP_PREFIX + '3', 0); | |
| 563 | + assertQueried(IP_PREFIX + '4', 0); | |
| 564 | + assertQueried(IP_PREFIX + '5', 0); | |
| 565 | + assertQueried(IP_PREFIX + '6', 0); | |
| 566 | + | |
| 567 | + resetCoordinators(); | |
| 568 | + stopAndWait(3); | |
| 569 | + | |
| 570 | + List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 571 | + ConsistencyLevel.ANY, | |
| 572 | + ConsistencyLevel.ONE, | |
| 573 | + ConsistencyLevel.TWO, | |
| 574 | + ConsistencyLevel.QUORUM, | |
| 575 | + ConsistencyLevel.THREE, | |
| 576 | + ConsistencyLevel.ALL, | |
| 577 | + ConsistencyLevel.LOCAL_QUORUM, | |
| 578 | + ConsistencyLevel.EACH_QUORUM | |
| 579 | + ); | |
| 580 | + | |
| 581 | + List<ConsistencyLevel> failList = emptyList(); | |
| 582 | + | |
| 583 | + // Test successful writes | |
| 584 | + for (ConsistencyLevel cl : acceptedList) { | |
| 585 | + logger.debug("Test successful init(): " + cl); | |
| 586 | + try { | |
| 587 | + init(12, cl); | |
| 588 | + } catch (Exception e) { | |
| 589 | + fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 598 | 590 | } |
| 591 | + } | |
| 599 | 592 | |
| 600 | - // Test successful reads | |
| 601 | - for (ConsistencyLevel cl : acceptedList) { | |
| 602 | - logger.info("Test successful query(): " + cl); | |
| 603 | - try { | |
| 604 | - query(c, 12, cl); | |
| 605 | - } catch (InvalidQueryException e) { | |
| 606 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 607 | - "EACH_QUORUM ConsistencyLevel is only supported for writes", | |
| 608 | - "ANY ConsistencyLevel is only supported for writes"); | |
| 609 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 610 | - } | |
| 593 | + // Test successful reads | |
| 594 | + for (ConsistencyLevel cl : acceptedList) { | |
| 595 | + logger.debug("Test successful query(): " + cl); | |
| 596 | + try { | |
| 597 | + query(12, cl); | |
| 598 | + } catch (InvalidQueryException e) { | |
| 599 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 600 | + "EACH_QUORUM ConsistencyLevel is only supported for writes", | |
| 601 | + "ANY ConsistencyLevel is only supported for writes"); | |
| 602 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 611 | 603 | } |
| 604 | + } | |
| 612 | 605 | |
| 613 | - // Test writes which should fail | |
| 614 | - for (ConsistencyLevel cl : failList) { | |
| 615 | - logger.info("Test failure init(): " + cl); | |
| 616 | - try { | |
| 617 | - init(c, 12, cl); | |
| 618 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 619 | - } catch (UnavailableException e) { | |
| 620 | - // expected to fail when the client has already marked the | |
| 621 | - // node as DOWN | |
| 622 | - } catch (WriteTimeoutException e) { | |
| 623 | - // expected to fail when the client hasn't marked the | |
| 624 | - // node as DOWN yet | |
| 625 | - } | |
| 606 | + // Test writes which should fail | |
| 607 | + for (ConsistencyLevel cl : failList) { | |
| 608 | + logger.debug("Test failure init(): " + cl); | |
| 609 | + try { | |
| 610 | + init(12, cl); | |
| 611 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 612 | + } catch (UnavailableException e) { | |
| 613 | + // expected to fail when the client has already marked the | |
| 614 | + // node as DOWN | |
| 615 | + } catch (WriteTimeoutException e) { | |
| 616 | + // expected to fail when the client hasn't marked the | |
| 617 | + // node as DOWN yet | |
| 626 | 618 | } |
| 619 | + } | |
| 627 | 620 | |
| 628 | - // Test reads which should fail | |
| 629 | - for (ConsistencyLevel cl : failList) { | |
| 630 | - logger.info("Test failure query(): " + cl); | |
| 631 | - try { | |
| 632 | - query(c, 12, cl); | |
| 633 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 634 | - } catch (ReadTimeoutException e) { | |
| 635 | - // expected to fail when the client hasn't marked the | |
| 636 | - // node as DOWN yet | |
| 637 | - } catch (UnavailableException e) { | |
| 638 | - // expected to fail when the client has already marked the | |
| 639 | - // node as DOWN | |
| 640 | - } | |
| 621 | + // Test reads which should fail | |
| 622 | + for (ConsistencyLevel cl : failList) { | |
| 623 | + logger.debug("Test failure query(): " + cl); | |
| 624 | + try { | |
| 625 | + query(12, cl); | |
| 626 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 627 | + } catch (ReadTimeoutException e) { | |
| 628 | + // expected to fail when the client hasn't marked the | |
| 629 | + // node as DOWN yet | |
| 630 | + } catch (UnavailableException e) { | |
| 631 | + // expected to fail when the client has already marked the | |
| 632 | + // node as DOWN | |
| 641 | 633 | } |
| 642 | - | |
| 643 | - } catch (Throwable e) { | |
| 644 | - c.errorOut(); | |
| 645 | - throw e; | |
| 646 | - } finally { | |
| 647 | - resetCoordinators(); | |
| 648 | - c.discard(); | |
| 649 | 634 | } |
| 650 | 635 | } |
| 651 | 636 | |
| 652 | 637 | @Test(groups = "long") |
| 638 | + @CCMConfig( | |
| 639 | + numberOfNodes = {3, 3}, | |
| 640 | + clusterProvider = "tokenAwareDCAwareRoundRobinNoShuffleDowngrading" | |
| 641 | + ) | |
| 653 | 642 | public void testRFThreeDowngradingCLTwoDCsDCAware() throws Throwable { |
| 654 | - Cluster.Builder builder = Cluster.builder() | |
| 655 | - .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc2"), false)) | |
| 656 | - .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 657 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder); | |
| 658 | - try { | |
| 659 | - | |
| 660 | - createMultiDCSchema(c.session, 3, 3); | |
| 661 | - init(c, 12, ConsistencyLevel.TWO); | |
| 662 | - query(c, 12, ConsistencyLevel.TWO); | |
| 663 | - | |
| 664 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 665 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 666 | - assertQueried(CCMBridge.IP_PREFIX + '3', 0); | |
| 667 | - assertQueried(CCMBridge.IP_PREFIX + '4', 0); | |
| 668 | - assertQueried(CCMBridge.IP_PREFIX + '5', 12); | |
| 669 | - assertQueried(CCMBridge.IP_PREFIX + '6', 0); | |
| 670 | - | |
| 671 | - resetCoordinators(); | |
| 672 | - c.cassandraCluster.stop(2); | |
| 673 | - | |
| 674 | - List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 675 | - ConsistencyLevel.ANY, | |
| 676 | - ConsistencyLevel.ONE, | |
| 677 | - ConsistencyLevel.TWO, | |
| 678 | - ConsistencyLevel.QUORUM, | |
| 679 | - ConsistencyLevel.THREE, | |
| 680 | - ConsistencyLevel.ALL, | |
| 681 | - ConsistencyLevel.LOCAL_QUORUM, | |
| 682 | - ConsistencyLevel.EACH_QUORUM | |
| 683 | - ); | |
| 684 | - | |
| 685 | - List<ConsistencyLevel> failList = Arrays.asList(); | |
| 686 | - | |
| 687 | - // Test successful writes | |
| 688 | - for (ConsistencyLevel cl : acceptedList) { | |
| 689 | - try { | |
| 690 | - init(c, 12, cl); | |
| 691 | - } catch (Exception e) { | |
| 692 | - fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 693 | - } | |
| 643 | + createMultiDCSchema(3, 3); | |
| 644 | + init(12, ConsistencyLevel.TWO); | |
| 645 | + query(12, ConsistencyLevel.TWO); | |
| 646 | + | |
| 647 | + assertQueried(IP_PREFIX + '1', 0); | |
| 648 | + assertQueried(IP_PREFIX + '2', 0); | |
| 649 | + assertQueried(IP_PREFIX + '3', 0); | |
| 650 | + assertQueried(IP_PREFIX + '4', 0); | |
| 651 | + assertQueried(IP_PREFIX + '5', 12); | |
| 652 | + assertQueried(IP_PREFIX + '6', 0); | |
| 653 | + | |
| 654 | + resetCoordinators(); | |
| 655 | + stopAndWait(2); | |
| 656 | + | |
| 657 | + List<ConsistencyLevel> acceptedList = Arrays.asList( | |
| 658 | + ConsistencyLevel.ANY, | |
| 659 | + ConsistencyLevel.ONE, | |
| 660 | + ConsistencyLevel.TWO, | |
| 661 | + ConsistencyLevel.QUORUM, | |
| 662 | + ConsistencyLevel.THREE, | |
| 663 | + ConsistencyLevel.ALL, | |
| 664 | + ConsistencyLevel.LOCAL_QUORUM, | |
| 665 | + ConsistencyLevel.EACH_QUORUM | |
| 666 | + ); | |
| 667 | + | |
| 668 | + List<ConsistencyLevel> failList = emptyList(); | |
| 669 | + | |
| 670 | + // Test successful writes | |
| 671 | + for (ConsistencyLevel cl : acceptedList) { | |
| 672 | + try { | |
| 673 | + init(12, cl); | |
| 674 | + } catch (Exception e) { | |
| 675 | + fail(String.format("Test failed at CL.%s with message: %s", cl, e.getMessage())); | |
| 694 | 676 | } |
| 677 | + } | |
| 695 | 678 | |
| 696 | - // Test successful reads | |
| 697 | - for (ConsistencyLevel cl : acceptedList) { | |
| 698 | - try { | |
| 699 | - query(c, 12, cl); | |
| 700 | - } catch (InvalidQueryException e) { | |
| 701 | - List<String> acceptableErrorMessages = Arrays.asList( | |
| 702 | - "EACH_QUORUM ConsistencyLevel is only supported for writes", | |
| 703 | - "ANY ConsistencyLevel is only supported for writes"); | |
| 704 | - assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 705 | - } | |
| 679 | + // Test successful reads | |
| 680 | + for (ConsistencyLevel cl : acceptedList) { | |
| 681 | + try { | |
| 682 | + query(12, cl); | |
| 683 | + } catch (InvalidQueryException e) { | |
| 684 | + List<String> acceptableErrorMessages = Arrays.asList( | |
| 685 | + "EACH_QUORUM ConsistencyLevel is only supported for writes", | |
| 686 | + "ANY ConsistencyLevel is only supported for writes"); | |
| 687 | + assertTrue(acceptableErrorMessages.contains(e.getMessage()), String.format("Received: %s", e.getMessage())); | |
| 706 | 688 | } |
| 689 | + } | |
| 707 | 690 | |
| 708 | - // Test writes which should fail | |
| 709 | - for (ConsistencyLevel cl : failList) { | |
| 710 | - try { | |
| 711 | - init(c, 12, cl); | |
| 712 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 713 | - } catch (UnavailableException e) { | |
| 714 | - // expected to fail when the client has already marked the | |
| 715 | - // node as DOWN | |
| 716 | - } catch (WriteTimeoutException e) { | |
| 717 | - // expected to fail when the client hasn't marked the | |
| 718 | - // node as DOWN yet | |
| 719 | - } | |
| 691 | + // Test writes which should fail | |
| 692 | + for (ConsistencyLevel cl : failList) { | |
| 693 | + try { | |
| 694 | + init(12, cl); | |
| 695 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 696 | + } catch (UnavailableException e) { | |
| 697 | + // expected to fail when the client has already marked the | |
| 698 | + // node as DOWN | |
| 699 | + } catch (WriteTimeoutException e) { | |
| 700 | + // expected to fail when the client hasn't marked the | |
| 701 | + // node as DOWN yet | |
| 720 | 702 | } |
| 703 | + } | |
| 721 | 704 | |
| 722 | - // Test reads which should fail | |
| 723 | - for (ConsistencyLevel cl : failList) { | |
| 724 | - try { | |
| 725 | - query(c, 12, cl); | |
| 726 | - fail(String.format("Test passed at CL.%s.", cl)); | |
| 727 | - } catch (ReadTimeoutException e) { | |
| 728 | - // expected to fail when the client hasn't marked the | |
| 729 | - // node as DOWN yet | |
| 730 | - } catch (UnavailableException e) { | |
| 731 | - // expected to fail when the client has already marked the | |
| 732 | - // node as DOWN | |
| 733 | - } | |
| 705 | + // Test reads which should fail | |
| 706 | + for (ConsistencyLevel cl : failList) { | |
| 707 | + try { | |
| 708 | + query(12, cl); | |
| 709 | + fail(String.format("Test passed at CL.%s.", cl)); | |
| 710 | + } catch (ReadTimeoutException e) { | |
| 711 | + // expected to fail when the client hasn't marked the | |
| 712 | + // node as DOWN yet | |
| 713 | + } catch (UnavailableException e) { | |
| 714 | + // expected to fail when the client has already marked the | |
| 715 | + // node as DOWN | |
| 734 | 716 | } |
| 735 | - } catch (Throwable e) { | |
| 736 | - c.errorOut(); | |
| 737 | - throw e; | |
| 738 | - } finally { | |
| 739 | - resetCoordinators(); | |
| 740 | - c.discard(); | |
| 741 | 717 | } |
| 742 | 718 | } |
| 719 | + | |
| 720 | + private void stopAndWait(int node) { | |
| 721 | + logger.debug("Stopping node " + node); | |
| 722 | + ccm.stop(node); | |
| 723 | + ccm.waitForDown(node);// this uses port ping | |
| 724 | + TestUtils.waitForDown(ipOfNode(node), cluster, 10); // this uses UP/DOWN events | |
| 725 | + logger.debug("Node " + node + " stopped, sleeping one extra minute to allow nodes to gossip"); | |
| 726 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES); | |
| 727 | + } | |
| 728 | + | |
| 743 | 729 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +65 −83
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | import org.testng.annotations.Test; |
| 29 | 29 | |
| 30 | 30 | import java.net.InetAddress; |
| 31 | +import java.net.InetSocketAddress; | |
| 31 | 32 | import java.util.Collection; |
| 32 | 33 | import java.util.Iterator; |
| 33 | 34 | import java.util.Map; |
| @@ -35,18 +36,21 @@ | ||
| 35 | 36 | import java.util.concurrent.atomic.AtomicInteger; |
| 36 | 37 | |
| 37 | 38 | import static com.datastax.driver.core.Assertions.assertThat; |
| 39 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 38 | 40 | import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; |
| 39 | 41 | import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; |
| 40 | 42 | import static com.google.common.collect.Lists.newArrayList; |
| 41 | 43 | |
| 42 | -public class ControlConnectionTest { | |
| 44 | +@CreateCCM(PER_METHOD) | |
| 45 | +@CCMConfig(dirtiesContext = true, createCluster = false) | |
| 46 | +public class ControlConnectionTest extends CCMTestsSupport { | |
| 43 | 47 | |
| 44 | 48 | static final Logger logger = LoggerFactory.getLogger(ControlConnectionTest.class); |
| 45 | 49 | |
| 46 | 50 | @Test(groups = "short") |
| 51 | + @CCMConfig(numberOfNodes = 2) | |
| 47 | 52 | public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException { |
| 48 | - CCMBridge ccm = null; | |
| 49 | - Cluster cluster = null; | |
| 53 | + Cluster cluster; | |
| 50 | 54 | |
| 51 | 55 | // Custom load balancing policy that counts the number of calls to newQueryPlan(). |
| 52 | 56 | // Since we don't open any session from our Cluster, only the control connection reattempts are calling this |
| @@ -68,31 +72,23 @@ | ||
| 68 | 72 | } |
| 69 | 73 | }; |
| 70 | 74 | |
| 71 | - try { | |
| 72 | - ccm = CCMBridge.builder("test").withNodes(2).build(); | |
| 73 | - // We pass only the first host as contact point, so we know the control connection will be on this host | |
| 74 | - cluster = Cluster.builder() | |
| 75 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 76 | - .withReconnectionPolicy(reconnectionPolicy) | |
| 77 | - .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 78 | - .build(); | |
| 79 | - cluster.init(); | |
| 80 | - | |
| 81 | - // Kill the control connection host, there should be exactly one reconnection attempt | |
| 82 | - ccm.stop(1); | |
| 83 | - TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing | |
| 84 | - assertThat(reconnectionAttempts.get()).isEqualTo(1); | |
| 85 | - | |
| 86 | - ccm.stop(2); | |
| 87 | - TimeUnit.SECONDS.sleep(1); | |
| 88 | - assertThat(reconnectionAttempts.get()).isEqualTo(2); | |
| 89 | - | |
| 90 | - } finally { | |
| 91 | - if (cluster != null) | |
| 92 | - cluster.close(); | |
| 93 | - if (ccm != null) | |
| 94 | - ccm.remove(); | |
| 95 | - } | |
| 75 | + // We pass only the first host as contact point, so we know the control connection will be on this host | |
| 76 | + cluster = register(Cluster.builder() | |
| 77 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 78 | + .withAddressTranslater(getAddressTranslator()) | |
| 79 | + .withReconnectionPolicy(reconnectionPolicy) | |
| 80 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 81 | + .build()); | |
| 82 | + cluster.init(); | |
| 83 | + | |
| 84 | + // Kill the control connection host, there should be exactly one reconnection attempt | |
| 85 | + ccm.stop(1); | |
| 86 | + TimeUnit.SECONDS.sleep(1); // Sleep for a while to make sure our final count is not the result of lucky timing | |
| 87 | + assertThat(reconnectionAttempts.get()).isEqualTo(1); | |
| 88 | + | |
| 89 | + ccm.stop(2); | |
| 90 | + TimeUnit.SECONDS.sleep(1); | |
| 91 | + assertThat(reconnectionAttempts.get()).isEqualTo(2); | |
| 96 | 92 | } |
| 97 | 93 | |
| 98 | 94 | /** |
| @@ -104,30 +100,23 @@ | ||
| 104 | 100 | @Test(groups = "short") |
| 105 | 101 | @CassandraVersion(major = 2.1) |
| 106 | 102 | public void should_parse_UDT_definitions_when_using_default_protocol_version() { |
| 107 | - CCMBridge ccm = null; | |
| 108 | - Cluster cluster = null; | |
| 109 | - | |
| 110 | - try { | |
| 111 | - ccm = CCMBridge.builder("test").build(); | |
| 112 | - | |
| 113 | - // First driver instance: create UDT | |
| 114 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 115 | - Session session = cluster.connect(); | |
| 116 | - session.execute("create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 117 | - session.execute("create type ks.foo (i int)"); | |
| 118 | - cluster.close(); | |
| 119 | - | |
| 120 | - // Second driver instance: read UDT definition | |
| 121 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 122 | - UserType fooType = cluster.getMetadata().getKeyspace("ks").getUserType("foo"); | |
| 123 | - | |
| 124 | - assertThat(fooType.getFieldNames()).containsExactly("i"); | |
| 125 | - } finally { | |
| 126 | - if (cluster != null) | |
| 127 | - cluster.close(); | |
| 128 | - if (ccm != null) | |
| 129 | - ccm.remove(); | |
| 130 | - } | |
| 103 | + Cluster cluster; | |
| 104 | + InetSocketAddress firstHost = getHostAddress(1); | |
| 105 | + // First driver instance: create UDT | |
| 106 | + cluster = register(Cluster.builder() | |
| 107 | + .addContactPointsWithPorts(firstHost) | |
| 108 | + .withAddressTranslater(getAddressTranslator()) | |
| 109 | + .build()); | |
| 110 | + Session session = cluster.connect(); | |
| 111 | + session.execute("create keyspace ks WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 112 | + session.execute("create type ks.foo (i int)"); | |
| 113 | + cluster.close(); | |
| 114 | + | |
| 115 | + // Second driver instance: read UDT definition | |
| 116 | + cluster = register(Cluster.builder().addContactPointsWithPorts(firstHost).build()); | |
| 117 | + UserType fooType = cluster.getMetadata().getKeyspace("ks").getUserType("foo"); | |
| 118 | + | |
| 119 | + assertThat(fooType.getFieldNames()).containsExactly("i"); | |
| 131 | 120 | } |
| 132 | 121 | |
| 133 | 122 | /** |
| @@ -140,36 +129,27 @@ | ||
| 140 | 129 | * @since 2.0.9 |
| 141 | 130 | */ |
| 142 | 131 | @Test(groups = "long") |
| 132 | + @CCMConfig(numberOfNodes = 3) | |
| 143 | 133 | public void should_reestablish_if_control_node_decommissioned() throws InterruptedException { |
| 144 | - CCMBridge ccm = null; | |
| 145 | - Cluster cluster = null; | |
| 146 | - | |
| 147 | - try { | |
| 148 | - ccm = CCMBridge.builder("test").withNodes(3).build(); | |
| 149 | - | |
| 150 | - cluster = Cluster.builder() | |
| 151 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 152 | - .withQueryOptions(nonDebouncingQueryOptions()) | |
| 153 | - .build(); | |
| 154 | - cluster.init(); | |
| 155 | - | |
| 156 | - // Ensure the control connection host is that of the first node. | |
| 157 | - String controlHost = cluster.manager.controlConnection.connectedHost().getAddress().getHostAddress(); | |
| 158 | - assertThat(controlHost).isEqualTo(CCMBridge.ipOfNode(1)); | |
| 159 | - | |
| 160 | - // Decommission the node. | |
| 161 | - ccm.decommissionNode(1); | |
| 162 | - | |
| 163 | - // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node. | |
| 164 | - Host newHost = cluster.manager.controlConnection.connectedHost(); | |
| 165 | - assertThat(newHost).isNotNull(); | |
| 166 | - assertThat(newHost.getAddress().getHostAddress()).isNotEqualTo(controlHost); | |
| 167 | - } finally { | |
| 168 | - if (cluster != null) | |
| 169 | - cluster.close(); | |
| 170 | - if (ccm != null) | |
| 171 | - ccm.remove(); | |
| 172 | - } | |
| 134 | + InetSocketAddress firstHost = getHostAddress(1); | |
| 135 | + Cluster cluster = register(Cluster.builder() | |
| 136 | + .addContactPointsWithPorts(firstHost) | |
| 137 | + .withAddressTranslater(getAddressTranslator()) | |
| 138 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 139 | + .build()); | |
| 140 | + cluster.init(); | |
| 141 | + | |
| 142 | + // Ensure the control connection host is that of the first node. | |
| 143 | + InetAddress controlHost = cluster.manager.controlConnection.connectedHost().getAddress(); | |
| 144 | + assertThat(controlHost).isEqualTo(firstHost.getAddress()); | |
| 145 | + | |
| 146 | + // Decommission the node. | |
| 147 | + ccm.decommissionNode(1); | |
| 148 | + | |
| 149 | + // Ensure that the new control connection is not null and it's host is not equal to the decommissioned node. | |
| 150 | + Host newHost = cluster.manager.controlConnection.connectedHost(); | |
| 151 | + assertThat(newHost).isNotNull(); | |
| 152 | + assertThat(newHost.getAddress()).isNotEqualTo(controlHost); | |
| 173 | 153 | } |
| 174 | 154 | |
| 175 | 155 | /** |
| @@ -186,6 +166,7 @@ | ||
| 186 | 166 | * @since 2.0.11, 2.1.8, 2.2.0 |
| 187 | 167 | */ |
| 188 | 168 | @Test(groups = "short") |
| 169 | + @CCMConfig(createCcm = false) | |
| 189 | 170 | public void should_randomize_contact_points_when_determining_control_connection() { |
| 190 | 171 | int hostCount = 5; |
| 191 | 172 | int iterations = 100; |
| @@ -193,14 +174,15 @@ | ||
| 193 | 174 | scassandras.init(); |
| 194 | 175 | |
| 195 | 176 | try { |
| 196 | - Collection<String> contactPoints = newArrayList(); | |
| 177 | + Collection<InetSocketAddress> contactPoints = newArrayList(); | |
| 197 | 178 | for (int i = 1; i <= hostCount; i++) { |
| 198 | 179 | contactPoints.add(scassandras.address(i)); |
| 199 | 180 | } |
| 200 | 181 | final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount); |
| 201 | 182 | for (int i = 0; i < iterations; i++) { |
| 202 | 183 | Cluster cluster = Cluster.builder() |
| 203 | - .addContactPoints(contactPoints.toArray(new String[hostCount])) | |
| 184 | + .addContactPointsWithPorts(contactPoints) | |
| 185 | + .withAddressTranslater(scassandras.addressTranslator()) | |
| 204 | 186 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 205 | 187 | .build(); |
| 206 | 188 |
added driver-core/src/test/java/com/datastax/driver/core/CreateCCM.java +64 −0
| @@ -0,0 +1,64 @@ | ||
| 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.lang.annotation.Retention; | |
| 19 | +import java.lang.annotation.Target; | |
| 20 | + | |
| 21 | +import static java.lang.annotation.ElementType.TYPE; | |
| 22 | +import static java.lang.annotation.RetentionPolicy.RUNTIME; | |
| 23 | + | |
| 24 | +@Retention(RUNTIME) | |
| 25 | +@Target(TYPE) | |
| 26 | +public @interface CreateCCM { | |
| 27 | + | |
| 28 | + enum TestMode { | |
| 29 | + | |
| 30 | + /** | |
| 31 | + * When this mode is selected, one single CCM cluster will | |
| 32 | + * be shared for all tests in the test class. | |
| 33 | + * <p/> | |
| 34 | + * When this mode is selected, only class-level {@link CCMConfig} annotations | |
| 35 | + * are processed; method-level annotations are ignored. | |
| 36 | + * <p/> | |
| 37 | + * This mode usually runs faster, but care should be taken | |
| 38 | + * not to alter the CCM cluster in a test in such a way | |
| 39 | + * that subsequent tests could fail. | |
| 40 | + */ | |
| 41 | + PER_CLASS, | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * When this mode is selected, a different CCM cluster | |
| 45 | + * will be used for each test in the test class. | |
| 46 | + * <p/> | |
| 47 | + * When this mode is selected, both class-level and method-level {@link CCMConfig} annotations | |
| 48 | + * are processed; the test configuration results from the merge of | |
| 49 | + * both annotations, if both are present (method-level annotations | |
| 50 | + * override class-level ones). | |
| 51 | + * <p/> | |
| 52 | + * This mode is slower, but is safer to use | |
| 53 | + * if a test method alters the CCM cluster. | |
| 54 | + */ | |
| 55 | + PER_METHOD | |
| 56 | + } | |
| 57 | + | |
| 58 | + /** | |
| 59 | + * The test mode to use for tests in this class. | |
| 60 | + * | |
| 61 | + * @return The test mode to use for tests in this class. | |
| 62 | + */ | |
| 63 | + TestMode value() default TestMode.PER_CLASS; | |
| 64 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/CustomTypeTest.java +2 −3
| @@ -28,10 +28,10 @@ | ||
| 28 | 28 | /** |
| 29 | 29 | * Test we "support" custom types. |
| 30 | 30 | */ |
| 31 | -public class CustomTypeTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 31 | +public class CustomTypeTest extends CCMTestsSupport { | |
| 32 | 32 | |
| 33 | 33 | @Override |
| 34 | - protected Collection<String> getTableDefinitions() { | |
| 34 | + public Collection<String> createTestFixtures() { | |
| 35 | 35 | return Collections.singleton( |
| 36 | 36 | "CREATE TABLE test (" |
| 37 | 37 | + " k int," |
| @@ -43,7 +43,6 @@ | ||
| 43 | 43 | } |
| 44 | 44 | |
| 45 | 45 | private ByteBuffer serializeForDynamicType(Object... params) { |
| 46 | - | |
| 47 | 46 | List<ByteBuffer> l = new ArrayList<ByteBuffer>(); |
| 48 | 47 | int size = 0; |
| 49 | 48 | for (Object p : params) { |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +3 −2
| @@ -35,7 +35,8 @@ | ||
| 35 | 35 | * (protocol > v2 only) and a prepared statement. |
| 36 | 36 | * This is repeated with a large number of datatypes. |
| 37 | 37 | */ |
| 38 | -public class DataTypeIntegrationTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 38 | +@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing") | |
| 39 | +public class DataTypeIntegrationTest extends CCMTestsSupport { | |
| 39 | 40 | private static final Logger logger = LoggerFactory.getLogger(DataTypeIntegrationTest.class); |
| 40 | 41 | |
| 41 | 42 | List<TestTable> tables = allTables(); |
| @@ -44,7 +45,7 @@ | ||
| 44 | 45 | enum StatementType {RAW_STRING, SIMPLE_WITH_PARAM, PREPARED} |
| 45 | 46 | |
| 46 | 47 | @Override |
| 47 | - protected Collection<String> getTableDefinitions() { | |
| 48 | + public Collection<String> createTestFixtures() { | |
| 48 | 49 | Host host = cluster.getMetadata().getAllHosts().iterator().next(); |
| 49 | 50 | cassandraVersion = host.getCassandraVersion().nextStable(); |
| 50 | 51 |
modified driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java +28 −36
| @@ -22,11 +22,13 @@ | ||
| 22 | 22 | import java.util.concurrent.CyclicBarrier; |
| 23 | 23 | import java.util.concurrent.TimeUnit; |
| 24 | 24 | |
| 25 | -import static com.datastax.driver.core.CCMBridge.ipOfNode; | |
| 25 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 26 | +import static com.datastax.driver.core.TestUtils.ipOfNode; | |
| 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; |
| 27 | 28 | import static org.assertj.core.api.Fail.fail; |
| 28 | 29 | |
| 29 | -public class EventDebouncerIntegrationTest { | |
| 30 | +@CreateCCM(PER_METHOD) | |
| 31 | +public class EventDebouncerIntegrationTest extends CCMTestsSupport { | |
| 30 | 32 | |
| 31 | 33 | /** |
| 32 | 34 | * Tests that DOWN, UP, REMOVE or ADD events will not be delivered to |
| @@ -37,43 +39,33 @@ | ||
| 37 | 39 | * @jira_ticket JAVA-784 |
| 38 | 40 | * @since 2.0.11 |
| 39 | 41 | */ |
| 42 | + @CCMConfig(numberOfNodes = 3, createCluster = false, dirtiesContext = true) | |
| 40 | 43 | @Test(groups = "long") |
| 41 | 44 | public void should_wait_until_load_balancing_policy_is_fully_initialized() throws InterruptedException { |
| 42 | 45 | TestLoadBalancingPolicy policy = new TestLoadBalancingPolicy(); |
| 43 | - CCMBridge ccm = CCMBridge.builder("main").withNodes(3).build(); | |
| 44 | - final Cluster cluster = new Cluster.Builder() | |
| 45 | - .addContactPoints(ipOfNode(1)) | |
| 46 | - .withLoadBalancingPolicy(policy) | |
| 47 | - .withQueryOptions(new QueryOptions() | |
| 48 | - .setRefreshNodeIntervalMillis(0) | |
| 49 | - .setRefreshNodeListIntervalMillis(0) | |
| 50 | - .setRefreshSchemaIntervalMillis(0) | |
| 51 | - ).build(); | |
| 52 | - try { | |
| 53 | - new Thread() { | |
| 54 | - @Override | |
| 55 | - public void run() { | |
| 56 | - cluster.init(); | |
| 57 | - } | |
| 58 | - }.start(); | |
| 59 | - // stop cluster initialization in the middle of LBP initialization | |
| 60 | - policy.stop(); | |
| 61 | - // generate a DOWN event - will not be delivered immediately | |
| 62 | - // because the debouncers are not started | |
| 63 | - // note: a graceful stop notify other nodes which send a topology change event to the driver right away | |
| 64 | - // while forceStop kills the node so other nodes take much more time to detect node failure | |
| 65 | - ccm.stop(3); | |
| 66 | - ccm.waitForDown(3); | |
| 67 | - // finish cluster initialization and deliver the DOWN event | |
| 68 | - policy.proceed(); | |
| 69 | - assertThat(policy.onDownCalledBeforeInit).isFalse(); | |
| 70 | - assertThat(policy.onDownCalled()).isTrue(); | |
| 71 | - assertThat(policy.hosts).doesNotContain(TestUtils.findHost(cluster, 3)); | |
| 72 | - } finally { | |
| 73 | - if (cluster != null) | |
| 74 | - cluster.close(); | |
| 75 | - ccm.remove("main"); | |
| 76 | - } | |
| 46 | + final Cluster cluster = register(createClusterBuilderNoDebouncing() | |
| 47 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 48 | + .withAddressTranslater(getAddressTranslator()) | |
| 49 | + .withLoadBalancingPolicy(policy).build()); | |
| 50 | + new Thread() { | |
| 51 | + @Override | |
| 52 | + public void run() { | |
| 53 | + cluster.init(); | |
| 54 | + } | |
| 55 | + }.start(); | |
| 56 | + // stop cluster initialization in the middle of LBP initialization | |
| 57 | + policy.stop(); | |
| 58 | + // generate a DOWN event - will not be delivered immediately | |
| 59 | + // because the debouncers are not started | |
| 60 | + // note: a graceful stop notify other nodes which send a topology change event to the driver right away | |
| 61 | + // while forceStop kills the node so other nodes take much more time to detect node failure | |
| 62 | + ccm.stop(3); | |
| 63 | + ccm.waitForDown(3); | |
| 64 | + // finish cluster initialization and deliver the DOWN event | |
| 65 | + policy.proceed(); | |
| 66 | + assertThat(policy.onDownCalledBeforeInit).isFalse(); | |
| 67 | + assertThat(policy.onDownCalled()).isTrue(); | |
| 68 | + assertThat(policy.hosts).doesNotContain(TestUtils.findHost(cluster, 3)); | |
| 77 | 69 | } |
| 78 | 70 | |
| 79 | 71 | private class TestLoadBalancingPolicy extends SortingLoadBalancingPolicy { |
modified driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java +2 −2
| @@ -190,7 +190,7 @@ | ||
| 190 | 190 | } |
| 191 | 191 | |
| 192 | 192 | void awaitEvents(int expected) throws InterruptedException { |
| 193 | - long nanos = SECONDS.toNanos(10); | |
| 193 | + long nanos = SECONDS.toNanos(60); | |
| 194 | 194 | lock.lock(); |
| 195 | 195 | try { |
| 196 | 196 | while (events.size() < expected) { |
| @@ -204,7 +204,7 @@ | ||
| 204 | 204 | } |
| 205 | 205 | |
| 206 | 206 | void awaitInvocations(int expected) throws InterruptedException { |
| 207 | - long nanos = SECONDS.toNanos(10); | |
| 207 | + long nanos = SECONDS.toNanos(60); | |
| 208 | 208 | lock.lock(); |
| 209 | 209 | try { |
| 210 | 210 | while (invocations.get() < expected) { |
modified driver-core/src/test/java/com/datastax/driver/core/FetchingTest.java +4 −10
| @@ -26,18 +26,16 @@ | ||
| 26 | 26 | /** |
| 27 | 27 | * Test ResultSet paging correct behavior. |
| 28 | 28 | */ |
| 29 | -public class FetchingTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 29 | +public class FetchingTest extends CCMTestsSupport { | |
| 30 | 30 | |
| 31 | 31 | @Override |
| 32 | - protected Collection<String> getTableDefinitions() { | |
| 32 | + public Collection<String> createTestFixtures() { | |
| 33 | 33 | return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))"); |
| 34 | 34 | } |
| 35 | 35 | |
| 36 | 36 | @Test(groups = "short") |
| 37 | - public void simplePagingTest() throws Throwable { | |
| 38 | - | |
| 37 | + public void simplePagingTest() { | |
| 39 | 38 | try { |
| 40 | - | |
| 41 | 39 | // Insert data |
| 42 | 40 | String key = "paging_test"; |
| 43 | 41 | for (int i = 0; i < 100; i++) |
| @@ -61,11 +59,7 @@ | ||
| 61 | 59 | |
| 62 | 60 | } catch (UnsupportedFeatureException e) { |
| 63 | 61 | // This is expected when testing the protocol v1 |
| 64 | - if (cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum() != ProtocolVersion.V1) | |
| 65 | - throw e; | |
| 66 | - } catch (Throwable e) { | |
| 67 | - errorOut(); | |
| 68 | - throw e; | |
| 62 | + assertEquals(cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(), ProtocolVersion.V1); | |
| 69 | 63 | } |
| 70 | 64 | } |
| 71 | 65 | } |
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +64 −77
| @@ -24,21 +24,24 @@ | ||
| 24 | 24 | import static com.datastax.driver.core.Assertions.assertThat; |
| 25 | 25 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 26 | 26 | |
| 27 | -public class HeartbeatTest { | |
| 27 | +@CCMConfig(createCluster = false) | |
| 28 | +public class HeartbeatTest extends CCMTestsSupport { | |
| 28 | 29 | |
| 29 | 30 | Logger connectionLogger = Logger.getLogger(Connection.class); |
| 30 | 31 | MemoryAppender logs; |
| 32 | + Level originalLevel; | |
| 31 | 33 | |
| 32 | 34 | @BeforeMethod(groups = "long") |
| 33 | 35 | public void startCapturingLogs() { |
| 36 | + originalLevel = connectionLogger.getLevel(); | |
| 34 | 37 | connectionLogger.setLevel(Level.DEBUG); |
| 35 | 38 | logs = new MemoryAppender(); |
| 36 | 39 | connectionLogger.addAppender(logs); |
| 37 | 40 | } |
| 38 | 41 | |
| 39 | - @AfterMethod(groups = "long") | |
| 42 | + @AfterMethod(groups = "long", alwaysRun = true) | |
| 40 | 43 | public void stopCapturingLogs() { |
| 41 | - connectionLogger.setLevel(null); | |
| 44 | + connectionLogger.setLevel(originalLevel); | |
| 42 | 45 | connectionLogger.removeAppender(logs); |
| 43 | 46 | } |
| 44 | 47 | |
| @@ -53,55 +56,47 @@ | ||
| 53 | 56 | */ |
| 54 | 57 | @Test(groups = "long") |
| 55 | 58 | public void should_send_heartbeat_when_connection_is_inactive() throws InterruptedException { |
| 56 | - CCMBridge ccm = null; | |
| 57 | - Cluster cluster = null; | |
| 58 | - try { | |
| 59 | - ccm = CCMBridge.builder("test").withNodes(1).build(); | |
| 60 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)) | |
| 61 | - .withPoolingOptions(new PoolingOptions() | |
| 62 | - .setHeartbeatIntervalSeconds(3)) | |
| 63 | - .build(); | |
| 64 | - | |
| 65 | - // Don't create any session, only the control connection will be established | |
| 66 | - cluster.init(); | |
| 67 | - | |
| 68 | - for (int i = 0; i < 5; i++) { | |
| 69 | - triggerRequestOnControlConnection(cluster); | |
| 70 | - SECONDS.sleep(1); | |
| 71 | - } | |
| 72 | - assertThat(logs.getNext()).doesNotContain("sending heartbeat"); | |
| 73 | - | |
| 74 | - // Ensure heartbeat is sent after no activity. | |
| 75 | - SECONDS.sleep(4); | |
| 76 | - assertThat(logs.getNext()) | |
| 77 | - .contains("sending heartbeat") | |
| 78 | - .contains("heartbeat query succeeded"); | |
| 79 | - | |
| 80 | - // Ensure heartbeat is sent after continued inactivity. | |
| 81 | - SECONDS.sleep(4); | |
| 82 | - assertThat(logs.getNext()) | |
| 83 | - .contains("sending heartbeat") | |
| 84 | - .contains("heartbeat query succeeded"); | |
| 85 | - | |
| 86 | - // Ensure heartbeat is not sent after activity. | |
| 87 | - logs.getNext(); | |
| 88 | - for (int i = 0; i < 5; i++) { | |
| 89 | - triggerRequestOnControlConnection(cluster); | |
| 90 | - SECONDS.sleep(1); | |
| 91 | - } | |
| 92 | - assertThat(logs.getNext()).doesNotContain("sending heartbeat"); | |
| 93 | - | |
| 94 | - // Finally, ensure heartbeat is sent after inactivity. | |
| 95 | - SECONDS.sleep(4); | |
| 96 | - assertThat(logs.getNext()) | |
| 97 | - .contains("sending heartbeat") | |
| 98 | - .contains("heartbeat query succeeded"); | |
| 99 | - } finally { | |
| 100 | - if (cluster != null) | |
| 101 | - cluster.close(); | |
| 102 | - if (ccm != null) | |
| 103 | - ccm.remove(); | |
| 59 | + Cluster cluster = register(Cluster.builder() | |
| 60 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 61 | + .withAddressTranslater(getAddressTranslator()) | |
| 62 | + .withPoolingOptions(new PoolingOptions() | |
| 63 | + .setHeartbeatIntervalSeconds(3)) | |
| 64 | + .build()); | |
| 65 | + | |
| 66 | + // Don't create any session, only the control connection will be established | |
| 67 | + cluster.init(); | |
| 68 | + | |
| 69 | + for (int i = 0; i < 5; i++) { | |
| 70 | + triggerRequestOnControlConnection(cluster); | |
| 71 | + SECONDS.sleep(1); | |
| 104 | 72 | } |
| 73 | + assertThat(logs.getNext()).doesNotContain("sending heartbeat"); | |
| 74 | + | |
| 75 | + // Ensure heartbeat is sent after no activity. | |
| 76 | + SECONDS.sleep(4); | |
| 77 | + assertThat(logs.getNext()) | |
| 78 | + .contains("sending heartbeat") | |
| 79 | + .contains("heartbeat query succeeded"); | |
| 80 | + | |
| 81 | + // Ensure heartbeat is sent after continued inactivity. | |
| 82 | + SECONDS.sleep(4); | |
| 83 | + assertThat(logs.getNext()) | |
| 84 | + .contains("sending heartbeat") | |
| 85 | + .contains("heartbeat query succeeded"); | |
| 86 | + | |
| 87 | + // Ensure heartbeat is not sent after activity. | |
| 88 | + logs.getNext(); | |
| 89 | + for (int i = 0; i < 5; i++) { | |
| 90 | + triggerRequestOnControlConnection(cluster); | |
| 91 | + SECONDS.sleep(1); | |
| 92 | + } | |
| 93 | + assertThat(logs.getNext()).doesNotContain("sending heartbeat"); | |
| 94 | + | |
| 95 | + // Finally, ensure heartbeat is sent after inactivity. | |
| 96 | + SECONDS.sleep(4); | |
| 97 | + assertThat(logs.getNext()) | |
| 98 | + .contains("sending heartbeat") | |
| 99 | + .contains("heartbeat query succeeded"); | |
| 105 | 100 | } |
| 106 | 101 | |
| 107 | 102 | /** |
| @@ -117,33 +112,25 @@ | ||
| 117 | 112 | */ |
| 118 | 113 | @Test(groups = "long") |
| 119 | 114 | public void should_not_send_heartbeat_when_disabled() throws InterruptedException { |
| 120 | - CCMBridge ccm = null; | |
| 121 | - Cluster cluster = null; | |
| 122 | - try { | |
| 123 | - ccm = CCMBridge.builder("test").withNodes(1).build(); | |
| 124 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)) | |
| 125 | - .withPoolingOptions(new PoolingOptions() | |
| 126 | - .setHeartbeatIntervalSeconds(0)) | |
| 127 | - .build(); | |
| 128 | - | |
| 129 | - // Don't create any session, only the control connection will be established | |
| 130 | - cluster.init(); | |
| 131 | - | |
| 132 | - for (int i = 0; i < 5; i++) { | |
| 133 | - triggerRequestOnControlConnection(cluster); | |
| 134 | - SECONDS.sleep(1); | |
| 135 | - } | |
| 136 | - assertThat(logs.get()).doesNotContain("sending heartbeat"); | |
| 137 | - | |
| 138 | - // Sleep for a while and ensure no heartbeat is sent. | |
| 139 | - SECONDS.sleep(32); | |
| 140 | - assertThat(logs.get()).doesNotContain("sending heartbeat"); | |
| 141 | - } finally { | |
| 142 | - if (cluster != null) | |
| 143 | - cluster.close(); | |
| 144 | - if (ccm != null) | |
| 145 | - ccm.remove(); | |
| 115 | + Cluster cluster = register(Cluster.builder() | |
| 116 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 117 | + .withAddressTranslater(getAddressTranslator()) | |
| 118 | + .withPoolingOptions(new PoolingOptions() | |
| 119 | + .setHeartbeatIntervalSeconds(0)) | |
| 120 | + .build()); | |
| 121 | + | |
| 122 | + // Don't create any session, only the control connection will be established | |
| 123 | + cluster.init(); | |
| 124 | + | |
| 125 | + for (int i = 0; i < 5; i++) { | |
| 126 | + triggerRequestOnControlConnection(cluster); | |
| 127 | + SECONDS.sleep(1); | |
| 146 | 128 | } |
| 129 | + assertThat(logs.get()).doesNotContain("sending heartbeat"); | |
| 130 | + | |
| 131 | + // Sleep for a while and ensure no heartbeat is sent. | |
| 132 | + SECONDS.sleep(32); | |
| 133 | + assertThat(logs.get()).doesNotContain("sending heartbeat"); | |
| 147 | 134 | } |
| 148 | 135 | |
| 149 | 136 | // Simulates activity on the control connection via the internal API |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java +3 −2
| @@ -41,7 +41,7 @@ | ||
| 41 | 41 | scassandra.init(); |
| 42 | 42 | } |
| 43 | 43 | |
| 44 | - @AfterMethod(groups = {"short", "long"}) | |
| 44 | + @AfterMethod(groups = {"short", "long"}, alwaysRun = true) | |
| 45 | 45 | private void tearDown() { |
| 46 | 46 | if (cluster != null) { |
| 47 | 47 | cluster.close(); |
| @@ -53,7 +53,8 @@ | ||
| 53 | 53 | PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, core, max); |
| 54 | 54 | SocketOptions socketOptions = new SocketOptions().setReadTimeoutMillis(1000); |
| 55 | 55 | cluster = Cluster.builder() |
| 56 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 56 | + .addContactPointsWithPorts(scassandra.address(1)) | |
| 57 | + .withAddressTranslater(scassandra.addressTranslator()) | |
| 57 | 58 | .withQueryOptions(nonDebouncingQueryOptions()) |
| 58 | 59 | .withPoolingOptions(poolingOptions) |
| 59 | 60 | .withSocketOptions(socketOptions) |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +54 −5
| @@ -17,7 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.codahale.metrics.Gauge; |
| 19 | 19 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 20 | -import com.google.common.util.concurrent.Uninterruptibles; | |
| 20 | +import com.google.common.util.concurrent.*; | |
| 21 | 21 | import org.scassandra.cql.PrimitiveType; |
| 22 | 22 | import org.scassandra.http.client.PrimingRequest; |
| 23 | 23 | import org.testng.annotations.BeforeClass; |
| @@ -41,7 +41,6 @@ | ||
| 41 | 41 | |
| 42 | 42 | public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster { |
| 43 | 43 | |
| 44 | - | |
| 45 | 44 | @BeforeClass(groups = {"short", "long"}) |
| 46 | 45 | public void reinitializeCluster() { |
| 47 | 46 | // Don't use the provided cluster, each test will create its own instead. |
| @@ -574,6 +573,9 @@ | ||
| 574 | 573 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 575 | 574 | cluster.manager.connectionFactory = factory; |
| 576 | 575 | |
| 576 | + TestExecutorService blockingExecutor = new TestExecutorService(cluster.manager.blockingExecutor); | |
| 577 | + cluster.manager.blockingExecutor = blockingExecutor; | |
| 578 | + | |
| 577 | 579 | HostConnectionPool pool = createPool(cluster, 3, 3); |
| 578 | 580 | Connection core0 = pool.connections.get(0); |
| 579 | 581 | Connection core1 = pool.connections.get(1); |
| @@ -602,12 +604,14 @@ | ||
| 602 | 604 | Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS); |
| 603 | 605 | |
| 604 | 606 | // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection. |
| 607 | + blockingExecutor.reset(); | |
| 605 | 608 | request = MockRequest.send(pool); |
| 606 | 609 | requests.add(request); |
| 607 | 610 | assertThat(request.connection).isEqualTo(core1); |
| 608 | 611 | |
| 609 | 612 | // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core. |
| 610 | - verify(factory, timeout(reconnectInterval).times(1)).open(any(HostConnectionPool.class)); | |
| 613 | + blockingExecutor.blockUntilNextTaskCompleted(); | |
| 614 | + verify(factory).open(any(HostConnectionPool.class)); | |
| 611 | 615 | reset(factory); |
| 612 | 616 | |
| 613 | 617 | // Sleep for reconnect interval to allow reconnection time to elapse. |
| @@ -619,13 +623,17 @@ | ||
| 619 | 623 | Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS); |
| 620 | 624 | |
| 621 | 625 | // Try to borrow a connection, the pool should grow. |
| 626 | + blockingExecutor.reset(); | |
| 622 | 627 | requests.add(MockRequest.send(pool)); |
| 623 | - verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class)); | |
| 628 | + blockingExecutor.blockUntilNextTaskCompleted(); | |
| 629 | + verify(factory).open(any(HostConnectionPool.class)); | |
| 624 | 630 | reset(factory); |
| 625 | 631 | |
| 626 | 632 | // Another core connection should be opened as result of another request to get us up to core connections. |
| 633 | + blockingExecutor.reset(); | |
| 627 | 634 | requests.add(MockRequest.send(pool)); |
| 628 | - verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class)); | |
| 635 | + blockingExecutor.blockUntilNextTaskCompleted(); | |
| 636 | + verify(factory).open(any(HostConnectionPool.class)); | |
| 629 | 637 | reset(factory); |
| 630 | 638 | |
| 631 | 639 | // Sending another request should not grow the pool any more, since we are now at core connections. |
| @@ -1103,4 +1111,45 @@ | ||
| 1103 | 1111 | return 0; // value not important for this test class |
| 1104 | 1112 | } |
| 1105 | 1113 | } |
| 1114 | + | |
| 1115 | + static class TestExecutorService extends ForwardingListeningExecutorService { | |
| 1116 | + | |
| 1117 | + private final ListeningExecutorService delegate; | |
| 1118 | + | |
| 1119 | + private final Semaphore semaphore = new Semaphore(0); | |
| 1120 | + | |
| 1121 | + TestExecutorService(ListeningExecutorService delegate) { | |
| 1122 | + this.delegate = delegate; | |
| 1123 | + } | |
| 1124 | + | |
| 1125 | + @Override | |
| 1126 | + protected ListeningExecutorService delegate() { | |
| 1127 | + return delegate; | |
| 1128 | + } | |
| 1129 | + | |
| 1130 | + public void reset() { | |
| 1131 | + semaphore.drainPermits(); | |
| 1132 | + } | |
| 1133 | + | |
| 1134 | + public void blockUntilNextTaskCompleted() throws InterruptedException { | |
| 1135 | + semaphore.tryAcquire(1, 1, TimeUnit.MINUTES); | |
| 1136 | + } | |
| 1137 | + | |
| 1138 | + @Override | |
| 1139 | + public ListenableFuture<?> submit(Runnable task) { | |
| 1140 | + ListenableFuture<?> future = super.submit(task); | |
| 1141 | + Futures.addCallback(future, new FutureCallback<Object>() { | |
| 1142 | + @Override | |
| 1143 | + public void onSuccess(Object result) { | |
| 1144 | + semaphore.release(1); | |
| 1145 | + } | |
| 1146 | + | |
| 1147 | + @Override | |
| 1148 | + public void onFailure(Throwable t) { | |
| 1149 | + semaphore.release(1); | |
| 1150 | + } | |
| 1151 | + }); | |
| 1152 | + return future; | |
| 1153 | + } | |
| 1154 | + } | |
| 1106 | 1155 | } |
modified driver-core/src/test/java/com/datastax/driver/core/IndexMetadataTest.java +3 −3
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | |
| 34 | 34 | @CassandraVersion( |
| 35 | 35 | major = 1.2) |
| 36 | -public class IndexMetadataTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 36 | +public class IndexMetadataTest extends CCMTestsSupport { | |
| 37 | 37 | |
| 38 | 38 | /** |
| 39 | 39 | * Column definitions for schema_columns table. |
| @@ -49,7 +49,7 @@ | ||
| 49 | 49 | }); |
| 50 | 50 | |
| 51 | 51 | @Override |
| 52 | - protected Collection<String> getTableDefinitions() { | |
| 52 | + public Collection<String> createTestFixtures() { | |
| 53 | 53 | String createTable = "CREATE TABLE indexing (" |
| 54 | 54 | + "id int primary key," |
| 55 | 55 | + "map_values map<text, int>," |
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | + "text_column text" |
| 59 | 59 | + |
| 60 | 60 | // Frozen collections was introduced only in C* 2.1.3 |
| 61 | - (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0 | |
| 61 | + (ccm.getVersion().compareTo(VersionNumber.parse("2.1.3")) >= 0 | |
| 62 | 62 | ? |
| 63 | 63 | ", map_full frozen<map<text, int>>," |
| 64 | 64 | + "set_full frozen<set<text>>," |
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +65 −130
| @@ -22,6 +22,7 @@ | ||
| 22 | 22 | |
| 23 | 23 | import java.nio.ByteBuffer; |
| 24 | 24 | |
| 25 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 25 | 26 | import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; |
| 26 | 27 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 27 | 28 | import static org.testng.Assert.assertEquals; |
| @@ -30,7 +31,8 @@ | ||
| 30 | 31 | /** |
| 31 | 32 | * Test limitations when using large amounts of data with the driver |
| 32 | 33 | */ |
| 33 | -public class LargeDataTest { | |
| 34 | +@CreateCCM(PER_METHOD) | |
| 35 | +public class LargeDataTest extends CCMTestsSupport { | |
| 34 | 36 | |
| 35 | 37 | /* |
| 36 | 38 | * Test a wide row of size 1,000,000 |
| @@ -38,14 +40,14 @@ | ||
| 38 | 40 | * @param key The key value that will receive the data |
| 39 | 41 | * @throws Throwable |
| 40 | 42 | */ |
| 41 | - private void testWideRows(CCMBridge.CCMCluster c, int key) throws Throwable { | |
| 43 | + private void testWideRows(int key) throws Throwable { | |
| 42 | 44 | // Write data |
| 43 | 45 | for (int i = 0; i < 1000000; ++i) { |
| 44 | - c.session.execute(insertInto("wide_rows").value("k", key).value("i", i).setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 46 | + session.execute(insertInto("wide_rows").value("k", key).value("i", i).setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 45 | 47 | } |
| 46 | 48 | |
| 47 | 49 | // Read data |
| 48 | - ResultSet rs = c.session.execute(select("i").from("wide_rows").where(eq("k", key))); | |
| 50 | + ResultSet rs = session.execute(select("i").from("wide_rows").where(eq("k", key))); | |
| 49 | 51 | |
| 50 | 52 | // Verify data |
| 51 | 53 | int i = 0; |
| @@ -60,16 +62,16 @@ | ||
| 60 | 62 | * @param key The key value that will receive the data |
| 61 | 63 | * @throws Throwable |
| 62 | 64 | */ |
| 63 | - private void testWideBatchRows(CCMBridge.CCMCluster c, int key) throws Throwable { | |
| 65 | + private void testWideBatchRows(int key) throws Throwable { | |
| 64 | 66 | // Write data |
| 65 | 67 | Batch q = batch(); |
| 66 | 68 | for (int i = 0; i < 10000; ++i) { |
| 67 | 69 | q = q.add(insertInto("wide_batch_rows").value("k", key).value("i", i)); |
| 68 | 70 | } |
| 69 | - c.session.execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 71 | + session.execute(q.setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 70 | 72 | |
| 71 | 73 | // Read data |
| 72 | - ResultSet rs = c.session.execute(select("i").from("wide_batch_rows").where(eq("k", key))); | |
| 74 | + ResultSet rs = session.execute(select("i").from("wide_batch_rows").where(eq("k", key))); | |
| 73 | 75 | |
| 74 | 76 | // Verify data |
| 75 | 77 | int i = 0; |
| @@ -84,7 +86,7 @@ | ||
| 84 | 86 | * @param key The key value that will receive the data |
| 85 | 87 | * @throws Throwable |
| 86 | 88 | */ |
| 87 | - private void testByteRows(CCMBridge.CCMCluster c, int key) throws Throwable { | |
| 89 | + private void testByteRows(int key) throws Throwable { | |
| 88 | 90 | // Build small ByteBuffer sample |
| 89 | 91 | ByteBuffer bb = ByteBuffer.allocate(58); |
| 90 | 92 | bb.putShort((short) 0xCAFE); |
| @@ -92,11 +94,11 @@ | ||
| 92 | 94 | |
| 93 | 95 | // Write data |
| 94 | 96 | for (int i = 0; i < 1000000; ++i) { |
| 95 | - c.session.execute(insertInto("wide_byte_rows").value("k", key).value("i", bb).setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 97 | + session.execute(insertInto("wide_byte_rows").value("k", key).value("i", bb).setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 96 | 98 | } |
| 97 | 99 | |
| 98 | 100 | // Read data |
| 99 | - ResultSet rs = c.session.execute(select("i").from("wide_byte_rows").where(eq("k", key))); | |
| 101 | + ResultSet rs = session.execute(select("i").from("wide_byte_rows").where(eq("k", key))); | |
| 100 | 102 | |
| 101 | 103 | // Verify data |
| 102 | 104 | for (Row row : rs) { |
| @@ -110,17 +112,17 @@ | ||
| 110 | 112 | * @param key The key value that will receive the data |
| 111 | 113 | * @throws Throwable |
| 112 | 114 | */ |
| 113 | - private void testLargeText(CCMBridge.CCMCluster c, int key) throws Throwable { | |
| 115 | + private void testLargeText(int key) throws Throwable { | |
| 114 | 116 | // Write data |
| 115 | 117 | StringBuilder b = new StringBuilder(); |
| 116 | 118 | for (int i = 0; i < 1000000; ++i) { |
| 117 | 119 | // Create ultra-long text |
| 118 | 120 | b.append(i); |
| 119 | 121 | } |
| 120 | - c.session.execute(insertInto("large_text").value("k", key).value("txt", b.toString()).setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 122 | + session.execute(insertInto("large_text").value("k", key).value("txt", b.toString()).setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 121 | 123 | |
| 122 | 124 | // Read data |
| 123 | - Row row = c.session.execute(select().all().from("large_text").where(eq("k", key))).one(); | |
| 125 | + Row row = session.execute(select().all().from("large_text").where(eq("k", key))).one(); | |
| 124 | 126 | |
| 125 | 127 | // Verify data |
| 126 | 128 | assertTrue(b.toString().equals(row.getString("txt"))); |
| @@ -158,16 +160,16 @@ | ||
| 158 | 160 | * @param key The key value that will receive the data |
| 159 | 161 | * @throws Throwable |
| 160 | 162 | */ |
| 161 | - private void testWideTable(CCMBridge.CCMCluster c, int key) throws Throwable { | |
| 163 | + private void testWideTable(int key) throws Throwable { | |
| 162 | 164 | // Write data |
| 163 | 165 | Insert insertStatement = insertInto("wide_table").value("k", key); |
| 164 | 166 | for (int i = 0; i < 330; ++i) { |
| 165 | 167 | insertStatement = insertStatement.value(createColumnName(i), i); |
| 166 | 168 | } |
| 167 | - c.session.execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 169 | + session.execute(insertStatement.setConsistencyLevel(ConsistencyLevel.QUORUM)); | |
| 168 | 170 | |
| 169 | 171 | // Read data |
| 170 | - Row row = c.session.execute(select().all().from("wide_table").where(eq("k", key))).one(); | |
| 172 | + Row row = session.execute(select().all().from("wide_table").where(eq("k", key))).one(); | |
| 171 | 173 | |
| 172 | 174 | // Verify data |
| 173 | 175 | for (int i = 0; i < 330; ++i) { |
| @@ -184,21 +186,10 @@ | ||
| 184 | 186 | @Test(groups = "stress") |
| 185 | 187 | @CassandraVersion(major = 2.0, minor = 0, description = "< 2.0 is skipped as 1.2 does not handle reading wide rows well.") |
| 186 | 188 | public void wideRows() throws Throwable { |
| 187 | - Cluster.Builder builder = Cluster.builder(); | |
| 188 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); | |
| 189 | - | |
| 190 | - c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 191 | - c.session.execute("USE large_data"); | |
| 192 | - c.session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_rows")); | |
| 193 | - | |
| 194 | - try { | |
| 195 | - testWideRows(c, 0); | |
| 196 | - } catch (Throwable e) { | |
| 197 | - c.errorOut(); | |
| 198 | - throw e; | |
| 199 | - } finally { | |
| 200 | - c.discard(); | |
| 201 | - } | |
| 189 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 190 | + session.execute("USE large_data"); | |
| 191 | + session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_rows")); | |
| 192 | + testWideRows(0); | |
| 202 | 193 | } |
| 203 | 194 | |
| 204 | 195 | /** |
| @@ -209,21 +200,10 @@ | ||
| 209 | 200 | @Test(groups = "stress") |
| 210 | 201 | @CassandraVersion(major = 2.0, minor = 0, description = "< 2.0 is skipped as 1.2 does not handle large batches well.") |
| 211 | 202 | public void wideBatchRows() throws Throwable { |
| 212 | - Cluster.Builder builder = Cluster.builder(); | |
| 213 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); | |
| 214 | - | |
| 215 | - c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 216 | - c.session.execute("USE large_data"); | |
| 217 | - c.session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_batch_rows")); | |
| 218 | - | |
| 219 | - try { | |
| 220 | - testWideBatchRows(c, 0); | |
| 221 | - } catch (Throwable e) { | |
| 222 | - c.errorOut(); | |
| 223 | - throw e; | |
| 224 | - } finally { | |
| 225 | - c.discard(); | |
| 226 | - } | |
| 203 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 204 | + session.execute("USE large_data"); | |
| 205 | + session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_batch_rows")); | |
| 206 | + testWideBatchRows(0); | |
| 227 | 207 | } |
| 228 | 208 | |
| 229 | 209 | /** |
| @@ -233,21 +213,10 @@ | ||
| 233 | 213 | */ |
| 234 | 214 | @Test(groups = "stress") |
| 235 | 215 | public void wideByteRows() throws Throwable { |
| 236 | - Cluster.Builder builder = Cluster.builder(); | |
| 237 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); | |
| 238 | - | |
| 239 | - c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 240 | - c.session.execute("USE large_data"); | |
| 241 | - c.session.execute(String.format("CREATE TABLE %s (k INT, i BLOB, PRIMARY KEY(k, i))", "wide_byte_rows")); | |
| 242 | - | |
| 243 | - try { | |
| 244 | - testByteRows(c, 0); | |
| 245 | - } catch (Throwable e) { | |
| 246 | - c.errorOut(); | |
| 247 | - throw e; | |
| 248 | - } finally { | |
| 249 | - c.discard(); | |
| 250 | - } | |
| 216 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 217 | + session.execute("USE large_data"); | |
| 218 | + session.execute(String.format("CREATE TABLE %s (k INT, i BLOB, PRIMARY KEY(k, i))", "wide_byte_rows")); | |
| 219 | + testByteRows(0); | |
| 251 | 220 | } |
| 252 | 221 | |
| 253 | 222 | /** |
| @@ -257,21 +226,10 @@ | ||
| 257 | 226 | */ |
| 258 | 227 | @Test(groups = "stress") |
| 259 | 228 | public void largeText() throws Throwable { |
| 260 | - Cluster.Builder builder = Cluster.builder(); | |
| 261 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); | |
| 262 | - | |
| 263 | - c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 264 | - c.session.execute("USE large_data"); | |
| 265 | - c.session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, txt text)", "large_text")); | |
| 266 | - | |
| 267 | - try { | |
| 268 | - testLargeText(c, 0); | |
| 269 | - } catch (Throwable e) { | |
| 270 | - c.errorOut(); | |
| 271 | - throw e; | |
| 272 | - } finally { | |
| 273 | - c.discard(); | |
| 274 | - } | |
| 229 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 230 | + session.execute("USE large_data"); | |
| 231 | + session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, txt text)", "large_text")); | |
| 232 | + testLargeText(0); | |
| 275 | 233 | } |
| 276 | 234 | |
| 277 | 235 | /** |
| @@ -281,12 +239,8 @@ | ||
| 281 | 239 | */ |
| 282 | 240 | @Test(groups = "stress") |
| 283 | 241 | public void wideTable() throws Throwable { |
| 284 | - Cluster.Builder builder = Cluster.builder(); | |
| 285 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); | |
| 286 | - | |
| 287 | - c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 288 | - c.session.execute("USE large_data"); | |
| 289 | - | |
| 242 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 1)); | |
| 243 | + session.execute("USE large_data"); | |
| 290 | 244 | // Create the extra wide table definition |
| 291 | 245 | StringBuilder tableDeclaration = new StringBuilder(); |
| 292 | 246 | tableDeclaration.append("CREATE TABLE wide_table ("); |
| @@ -295,16 +249,8 @@ | ||
| 295 | 249 | tableDeclaration.append(String.format(", %s INT", createColumnName(i))); |
| 296 | 250 | } |
| 297 | 251 | tableDeclaration.append(')'); |
| 298 | - c.session.execute(tableDeclaration.toString()); | |
| 299 | - | |
| 300 | - try { | |
| 301 | - testWideTable(c, 0); | |
| 302 | - } catch (Throwable e) { | |
| 303 | - c.errorOut(); | |
| 304 | - throw e; | |
| 305 | - } finally { | |
| 306 | - c.discard(); | |
| 307 | - } | |
| 252 | + session.execute(tableDeclaration.toString()); | |
| 253 | + testWideTable(0); | |
| 308 | 254 | } |
| 309 | 255 | |
| 310 | 256 | /** |
| @@ -313,17 +259,14 @@ | ||
| 313 | 259 | * @throws Throwable |
| 314 | 260 | */ |
| 315 | 261 | @Test(groups = "duration") |
| 262 | + @CCMConfig(numberOfNodes = 3) | |
| 316 | 263 | public void mixedDurationTest() throws Throwable { |
| 317 | - Cluster.Builder builder = Cluster.builder(); | |
| 318 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 319 | - | |
| 320 | - c.session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 3)); | |
| 321 | - c.session.execute("USE large_data"); | |
| 322 | - c.session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_rows")); | |
| 323 | - c.session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_batch_rows")); | |
| 324 | - c.session.execute(String.format("CREATE TABLE %s (k INT, i BLOB, PRIMARY KEY(k, i))", "wide_byte_rows")); | |
| 325 | - c.session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, txt text)", "large_text")); | |
| 326 | - | |
| 264 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "large_data", 3)); | |
| 265 | + session.execute("USE large_data"); | |
| 266 | + session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_rows")); | |
| 267 | + session.execute(String.format("CREATE TABLE %s (k INT, i INT, PRIMARY KEY(k, i))", "wide_batch_rows")); | |
| 268 | + session.execute(String.format("CREATE TABLE %s (k INT, i BLOB, PRIMARY KEY(k, i))", "wide_byte_rows")); | |
| 269 | + session.execute(String.format("CREATE TABLE %s (k int PRIMARY KEY, txt text)", "large_text")); | |
| 327 | 270 | // Create the extra wide table definition |
| 328 | 271 | StringBuilder tableDeclaration = new StringBuilder(); |
| 329 | 272 | tableDeclaration.append("CREATE TABLE wide_table ("); |
| @@ -332,35 +275,27 @@ | ||
| 332 | 275 | tableDeclaration.append(String.format(", %s INT", createColumnName(i))); |
| 333 | 276 | } |
| 334 | 277 | tableDeclaration.append(')'); |
| 335 | - c.session.execute(tableDeclaration.toString()); | |
| 336 | - | |
| 337 | - try { | |
| 338 | - for (int i = 0; i < 10; ++i) { | |
| 339 | - switch ((int) (Math.random() * 5)) { | |
| 340 | - case 0: | |
| 341 | - testWideRows(c, 0); | |
| 342 | - break; | |
| 343 | - case 1: | |
| 344 | - testWideBatchRows(c, 0); | |
| 345 | - break; | |
| 346 | - case 2: | |
| 347 | - testByteRows(c, 0); | |
| 348 | - break; | |
| 349 | - case 3: | |
| 350 | - testLargeText(c, 0); | |
| 351 | - break; | |
| 352 | - case 4: | |
| 353 | - testWideTable(c, 0); | |
| 354 | - break; | |
| 355 | - default: | |
| 356 | - break; | |
| 357 | - } | |
| 278 | + session.execute(tableDeclaration.toString()); | |
| 279 | + for (int i = 0; i < 10; ++i) { | |
| 280 | + switch ((int) (Math.random() * 5)) { | |
| 281 | + case 0: | |
| 282 | + testWideRows(0); | |
| 283 | + break; | |
| 284 | + case 1: | |
| 285 | + testWideBatchRows(0); | |
| 286 | + break; | |
| 287 | + case 2: | |
| 288 | + testByteRows(0); | |
| 289 | + break; | |
| 290 | + case 3: | |
| 291 | + testLargeText(0); | |
| 292 | + break; | |
| 293 | + case 4: | |
| 294 | + testWideTable(0); | |
| 295 | + break; | |
| 296 | + default: | |
| 297 | + break; | |
| 358 | 298 | } |
| 359 | - } catch (Throwable e) { | |
| 360 | - c.errorOut(); | |
| 361 | - throw e; | |
| 362 | - } finally { | |
| 363 | - c.discard(); | |
| 364 | 299 | } |
| 365 | 300 | } |
| 366 | 301 | } |
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +59 −77
| @@ -31,7 +31,8 @@ | ||
| 31 | 31 | import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.entry; |
| 32 | 32 | import static org.assertj.core.api.Assertions.assertThat; |
| 33 | 33 | |
| 34 | -public class LoadBalancingPolicyBootstrapTest { | |
| 34 | +@CCMConfig(numberOfNodes = 2, dirtiesContext = true, createCluster = false) | |
| 35 | +public class LoadBalancingPolicyBootstrapTest extends CCMTestsSupport { | |
| 35 | 36 | |
| 36 | 37 | private static final Logger logger = LoggerFactory.getLogger(LoadBalancingPolicyBootstrapTest.class); |
| 37 | 38 | |
| @@ -46,27 +47,18 @@ | ||
| 46 | 47 | public void should_init_policy_with_up_contact_points() throws Exception { |
| 47 | 48 | HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy()); |
| 48 | 49 | |
| 49 | - CCMBridge ccm = null; | |
| 50 | - Cluster cluster = null; | |
| 51 | - try { | |
| 52 | - ccm = CCMBridge.builder("test").withNodes(2).build(); | |
| 53 | - cluster = Cluster.builder() | |
| 54 | - .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2)) | |
| 55 | - .withLoadBalancingPolicy(policy) | |
| 56 | - .build(); | |
| 57 | - | |
| 58 | - cluster.init(); | |
| 59 | - | |
| 60 | - assertThat(policy.history).containsOnly( | |
| 61 | - entry(INIT, TestUtils.findHost(cluster, 1)), | |
| 62 | - entry(INIT, TestUtils.findHost(cluster, 2)) | |
| 63 | - ); | |
| 64 | - } finally { | |
| 65 | - if (cluster != null) | |
| 66 | - cluster.close(); | |
| 67 | - if (ccm != null) | |
| 68 | - ccm.remove(); | |
| 69 | - } | |
| 50 | + Cluster cluster = register(Cluster.builder() | |
| 51 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 52 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 53 | + .withLoadBalancingPolicy(policy) | |
| 54 | + .build()); | |
| 55 | + | |
| 56 | + cluster.init(); | |
| 57 | + | |
| 58 | + assertThat(policy.history).containsOnly( | |
| 59 | + entry(INIT, TestUtils.findHost(cluster, 1)), | |
| 60 | + entry(INIT, TestUtils.findHost(cluster, 2)) | |
| 61 | + ); | |
| 70 | 62 | } |
| 71 | 63 | |
| 72 | 64 | /** |
| @@ -79,66 +71,56 @@ | ||
| 79 | 71 | * @jira_ticket JAVA-613 |
| 80 | 72 | * @since 2.0.10, 2.1.5 |
| 81 | 73 | */ |
| 82 | - @Test(groups = "short") | |
| 74 | + @Test(groups = "short", dependsOnMethods = "should_init_policy_with_up_contact_points") | |
| 83 | 75 | public void should_send_down_notifications_after_init_when_contact_points_are_down() throws Exception { |
| 84 | - CCMBridge ccm = null; | |
| 85 | - Cluster cluster = null; | |
| 86 | - try { | |
| 87 | - ccm = CCMBridge.builder("test").withNodes(2).build(); | |
| 88 | - | |
| 89 | - // In order to validate this behavior, we need to stop the first node that would be attempted to be | |
| 90 | - // established as the control connection. | |
| 91 | - // This depends on the internal behavior and will even be made totally random by JAVA-618, therefore | |
| 92 | - // we retry the scenario until we get the desired preconditions. | |
| 93 | - | |
| 94 | - int nodeToStop = 1; | |
| 95 | - int tries = 1, maxTries = 10; | |
| 96 | - for (; tries <= maxTries; tries++) { | |
| 97 | - nodeToStop = (nodeToStop == 1) ? 2 : 1; // switch nodes at each try | |
| 98 | - int activeNode = nodeToStop == 2 ? 1 : 2; | |
| 99 | - | |
| 100 | - ccm.stop(nodeToStop); | |
| 101 | - ccm.waitForDown(nodeToStop); | |
| 102 | - | |
| 103 | - HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy()); | |
| 104 | - cluster = Cluster.builder() | |
| 105 | - .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2)) | |
| 106 | - .withLoadBalancingPolicy(policy) | |
| 107 | - .build(); | |
| 108 | - | |
| 109 | - cluster.init(); | |
| 110 | - | |
| 111 | - if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) { | |
| 112 | - // This is the situation we're testing, the control connection tried the stopped node first. | |
| 113 | - assertThat(policy.history).containsExactly( | |
| 114 | - entry(INIT, TestUtils.findHost(cluster, activeNode)), | |
| 115 | - entry(DOWN, TestUtils.findHost(cluster, nodeToStop)) | |
| 116 | - ); | |
| 117 | - break; | |
| 118 | - } else { | |
| 119 | - assertThat(policy.history).containsOnly( | |
| 120 | - entry(INIT, TestUtils.findHost(cluster, 1)), | |
| 121 | - entry(INIT, TestUtils.findHost(cluster, 2)) | |
| 122 | - ); | |
| 123 | - | |
| 124 | - logger.info("Could not get first contact point to fail, retrying"); | |
| 125 | - | |
| 126 | - cluster.close(); | |
| 127 | - | |
| 128 | - ccm.start(nodeToStop); | |
| 129 | - ccm.waitForUp(nodeToStop); | |
| 130 | - } | |
| 131 | - } | |
| 132 | 76 | |
| 133 | - if (tries == maxTries + 1) | |
| 134 | - logger.warn("Could not get first contact point to fail after {} tries", maxTries); | |
| 77 | + // In order to validate this behavior, we need to stop the first node that would be attempted to be | |
| 78 | + // established as the control connection. | |
| 79 | + // This depends on the internal behavior and will even be made totally random by JAVA-618, therefore | |
| 80 | + // we retry the scenario until we get the desired preconditions. | |
| 81 | + | |
| 82 | + int nodeToStop = 1; | |
| 83 | + int tries = 1, maxTries = 10; | |
| 84 | + for (; tries <= maxTries; tries++) { | |
| 85 | + nodeToStop = (nodeToStop == 1) ? 2 : 1; // switch nodes at each try | |
| 86 | + int activeNode = nodeToStop == 2 ? 1 : 2; | |
| 87 | + | |
| 88 | + ccm.stop(nodeToStop); | |
| 89 | + ccm.waitForDown(nodeToStop); | |
| 90 | + | |
| 91 | + HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy()); | |
| 92 | + Cluster cluster = register(Cluster.builder() | |
| 93 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 94 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 95 | + .withLoadBalancingPolicy(policy) | |
| 96 | + .build()); | |
| 97 | + | |
| 98 | + cluster.init(); | |
| 99 | + | |
| 100 | + if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) { | |
| 101 | + // This is the situation we're testing, the control connection tried the stopped node first. | |
| 102 | + assertThat(policy.history).containsExactly( | |
| 103 | + entry(INIT, TestUtils.findHost(cluster, activeNode)), | |
| 104 | + entry(DOWN, TestUtils.findHost(cluster, nodeToStop)) | |
| 105 | + ); | |
| 106 | + break; | |
| 107 | + } else { | |
| 108 | + assertThat(policy.history).containsOnly( | |
| 109 | + entry(INIT, TestUtils.findHost(cluster, 1)), | |
| 110 | + entry(INIT, TestUtils.findHost(cluster, 2)) | |
| 111 | + ); | |
| 112 | + | |
| 113 | + logger.info("Could not get first contact point to fail, retrying"); | |
| 135 | 114 | |
| 136 | - } finally { | |
| 137 | - if (cluster != null) | |
| 138 | 115 | cluster.close(); |
| 139 | - if (ccm != null) | |
| 140 | - ccm.remove(); | |
| 116 | + | |
| 117 | + ccm.start(nodeToStop); | |
| 118 | + ccm.waitForUp(nodeToStop); | |
| 119 | + } | |
| 141 | 120 | } |
| 121 | + | |
| 122 | + if (tries == maxTries + 1) | |
| 123 | + logger.warn("Could not get first contact point to fail after {} tries", maxTries); | |
| 142 | 124 | } |
| 143 | 125 | |
| 144 | 126 | static class HistoryPolicy extends DelegatingLoadBalancingPolicy { |
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyRefreshTest.java +26 −30
| @@ -23,12 +23,16 @@ | ||
| 23 | 23 | import java.util.Collection; |
| 24 | 24 | import java.util.Iterator; |
| 25 | 25 | |
| 26 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 26 | 27 | import static org.testng.Assert.assertTrue; |
| 27 | 28 | |
| 28 | 29 | // Test that PoolingOpions.refreshConnectedHosts works as expected (JAVA-309) |
| 29 | -public class LoadBalancingPolicyRefreshTest { | |
| 30 | +@CreateCCM(PER_METHOD) | |
| 31 | +public class LoadBalancingPolicyRefreshTest extends CCMTestsSupport { | |
| 30 | 32 | |
| 31 | - private static class UpdatablePolicy implements LoadBalancingPolicy { | |
| 33 | + UpdatablePolicy policy; | |
| 34 | + | |
| 35 | + private class UpdatablePolicy implements LoadBalancingPolicy { | |
| 32 | 36 | |
| 33 | 37 | private Cluster cluster; |
| 34 | 38 | private Host theHost; |
| @@ -42,7 +46,7 @@ | ||
| 42 | 46 | this.cluster = cluster; |
| 43 | 47 | try { |
| 44 | 48 | for (Host h : hosts) |
| 45 | - if (h.getAddress().equals(InetAddress.getByName(CCMBridge.IP_PREFIX + '1'))) | |
| 49 | + if (h.getAddress().equals(InetAddress.getByName(TestUtils.IP_PREFIX + '1'))) | |
| 46 | 50 | this.theHost = h; |
| 47 | 51 | } catch (Exception e) { |
| 48 | 52 | throw new RuntimeException(e); |
| @@ -74,37 +78,29 @@ | ||
| 74 | 78 | } |
| 75 | 79 | |
| 76 | 80 | @Test(groups = "short") |
| 81 | + @CCMConfig(numberOfNodes = 2, clusterProvider = "updatablePolicy") | |
| 77 | 82 | public void refreshTest() throws Throwable { |
| 83 | + // Ugly | |
| 84 | + Host[] hosts = new Host[2]; | |
| 85 | + for (Host h : cluster.getMetadata().getAllHosts()) { | |
| 86 | + if (h.getAddress().equals(InetAddress.getByName(TestUtils.IP_PREFIX + '1'))) | |
| 87 | + hosts[0] = h; | |
| 88 | + else | |
| 89 | + hosts[1] = h; | |
| 90 | + } | |
| 78 | 91 | |
| 79 | - UpdatablePolicy policy = new UpdatablePolicy(); | |
| 80 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(policy); | |
| 81 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder); | |
| 82 | - try { | |
| 83 | - | |
| 84 | - Session s = c.session; | |
| 85 | - | |
| 86 | - // Ugly | |
| 87 | - Host[] hosts = new Host[2]; | |
| 88 | - for (Host h : c.cluster.getMetadata().getAllHosts()) { | |
| 89 | - if (h.getAddress().equals(InetAddress.getByName(CCMBridge.IP_PREFIX + '1'))) | |
| 90 | - hosts[0] = h; | |
| 91 | - else | |
| 92 | - hosts[1] = h; | |
| 93 | - } | |
| 94 | - | |
| 95 | - assertTrue(s.getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + s.getState().getConnectedHosts()); | |
| 96 | - assertTrue(!s.getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + s.getState().getConnectedHosts()); | |
| 92 | + assertTrue(session.getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + session.getState().getConnectedHosts()); | |
| 93 | + assertTrue(!session.getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + session.getState().getConnectedHosts()); | |
| 97 | 94 | |
| 98 | - policy.changeTheHost(hosts[1]); | |
| 95 | + policy.changeTheHost(hosts[1]); | |
| 99 | 96 | |
| 100 | - assertTrue(!s.getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + s.getState().getConnectedHosts()); | |
| 101 | - assertTrue(s.getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + s.getState().getConnectedHosts()); | |
| 97 | + assertTrue(!session.getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + session.getState().getConnectedHosts()); | |
| 98 | + assertTrue(session.getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + session.getState().getConnectedHosts()); | |
| 99 | + } | |
| 102 | 100 | |
| 103 | - } catch (Throwable e) { | |
| 104 | - c.errorOut(); | |
| 105 | - throw e; | |
| 106 | - } finally { | |
| 107 | - c.discard(); | |
| 108 | - } | |
| 101 | + @SuppressWarnings("unused") | |
| 102 | + private Cluster.Builder updatablePolicy() { | |
| 103 | + policy = new UpdatablePolicy(); | |
| 104 | + return Cluster.builder().withLoadBalancingPolicy(policy); | |
| 109 | 105 | } |
| 110 | 106 | } |
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenIntegrationTest.java +2 −1
| @@ -18,8 +18,9 @@ | ||
| 18 | 18 | import com.datastax.driver.core.Token.M3PToken; |
| 19 | 19 | |
| 20 | 20 | public class M3PTokenIntegrationTest extends TokenIntegrationTest { |
| 21 | + | |
| 21 | 22 | public M3PTokenIntegrationTest() { |
| 22 | - super("", DataType.bigint()); | |
| 23 | + super(DataType.bigint(), false); | |
| 23 | 24 | } |
| 24 | 25 | |
| 25 | 26 | @Override |
modified driver-core/src/test/java/com/datastax/driver/core/M3PTokenVnodeIntegrationTest.java +3 −1
| @@ -15,9 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +@CCMConfig(options = "--vnodes") | |
| 18 | 19 | public class M3PTokenVnodeIntegrationTest extends TokenIntegrationTest { |
| 20 | + | |
| 19 | 21 | public M3PTokenVnodeIntegrationTest() { |
| 20 | - super("", DataType.bigint(), true); | |
| 22 | + super(DataType.bigint(), true); | |
| 21 | 23 | } |
| 22 | 24 | |
| 23 | 25 | @Override |
modified driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +56 −63
| @@ -21,10 +21,12 @@ | ||
| 21 | 21 | import java.util.Map; |
| 22 | 22 | |
| 23 | 23 | import static com.datastax.driver.core.Assertions.assertThat; |
| 24 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 24 | 25 | import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; |
| 25 | 26 | import static com.datastax.driver.core.TestUtils.waitFor; |
| 26 | 27 | |
| 27 | -public class MetadataTest { | |
| 28 | +@CreateCCM(PER_METHOD) | |
| 29 | +public class MetadataTest extends CCMTestsSupport { | |
| 28 | 30 | |
| 29 | 31 | /** |
| 30 | 32 | * <p> |
| @@ -50,71 +52,62 @@ | ||
| 50 | 52 | * @since 2.0.10, 2.1.5 |
| 51 | 53 | */ |
| 52 | 54 | @Test(groups = "long") |
| 55 | + @CCMConfig(numberOfNodes = 3, dirtiesContext = true, createCluster = false) | |
| 53 | 56 | public void should_update_metadata_on_topology_change() { |
| 54 | - CCMBridge ccm = null; | |
| 55 | - Cluster cluster = null; | |
| 56 | - | |
| 57 | - try { | |
| 58 | - ccm = CCMBridge.builder("test").withNodes(3).build(); | |
| 59 | - | |
| 60 | - cluster = Cluster.builder() | |
| 61 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 62 | - .withQueryOptions(nonDebouncingQueryOptions()) | |
| 63 | - .build(); | |
| 64 | - Session session = cluster.connect(); | |
| 65 | - | |
| 66 | - String keyspace = "test"; | |
| 67 | - session.execute("CREATE KEYSPACE " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 68 | - Metadata metadata = cluster.getMetadata(); | |
| 69 | - | |
| 70 | - // Capture all Token data. | |
| 71 | - assertThat(metadata.getTokenRanges()).hasSize(3); | |
| 72 | - Map<Host, Token> tokensForHost = getTokenForHosts(metadata); | |
| 73 | - | |
| 74 | - // Capture host3s token and range before we take it down. | |
| 75 | - Host host3 = TestUtils.findHost(cluster, 3); | |
| 76 | - Token host3Token = tokensForHost.get(host3); | |
| 77 | - | |
| 78 | - ccm.decommissionNode(3); | |
| 79 | - ccm.remove(3); | |
| 80 | - | |
| 81 | - // Ensure that the token ranges were updated, there should only be 2 ranges now. | |
| 82 | - assertThat(metadata.getTokenRanges()).hasSize(2); | |
| 83 | - | |
| 84 | - // The token should not be present for any Host. | |
| 85 | - assertThat(getTokenForHosts(metadata)).doesNotContainValue(host3Token); | |
| 86 | - | |
| 87 | - // The ring should be fully accounted for. | |
| 88 | - assertThat(cluster).hasValidTokenRanges("test"); | |
| 89 | - assertThat(cluster).hasValidTokenRanges(); | |
| 90 | - | |
| 91 | - // Add an additional node. | |
| 92 | - ccm.bootstrapNode(4); | |
| 93 | - waitFor(CCMBridge.IP_PREFIX + '4', cluster); | |
| 94 | - | |
| 95 | - // Ensure that the token ranges were updated, there should only be 3 ranges now. | |
| 96 | - assertThat(metadata.getTokenRanges()).hasSize(3); | |
| 97 | - | |
| 98 | - Host host4 = TestUtils.findHost(cluster, 4); | |
| 99 | - TokenRange host4Range = metadata.getTokenRanges(keyspace, host4).iterator().next(); | |
| 100 | - | |
| 101 | - // Ensure no host token range intersects with node 4. | |
| 102 | - for (Host host : metadata.getAllHosts()) { | |
| 103 | - if (!host.equals(host4)) { | |
| 104 | - TokenRange hostRange = metadata.getTokenRanges(keyspace, host).iterator().next(); | |
| 105 | - assertThat(host4Range).doesNotIntersect(hostRange); | |
| 106 | - } | |
| 57 | + Cluster cluster = register(Cluster.builder() | |
| 58 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 59 | + .withAddressTranslater(getAddressTranslator()) | |
| 60 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 61 | + .build()); | |
| 62 | + Session session = cluster.connect(); | |
| 63 | + | |
| 64 | + String keyspace = "test"; | |
| 65 | + session.execute("CREATE KEYSPACE " + keyspace + " WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 66 | + Metadata metadata = cluster.getMetadata(); | |
| 67 | + | |
| 68 | + // Capture all Token data. | |
| 69 | + assertThat(metadata.getTokenRanges()).hasSize(3); | |
| 70 | + Map<Host, Token> tokensForHost = getTokenForHosts(metadata); | |
| 71 | + | |
| 72 | + // Capture host3s token and range before we take it down. | |
| 73 | + Host host3 = TestUtils.findHost(cluster, 3); | |
| 74 | + Token host3Token = tokensForHost.get(host3); | |
| 75 | + | |
| 76 | + ccm.decommissionNode(3); | |
| 77 | + ccm.remove(3); | |
| 78 | + | |
| 79 | + // Ensure that the token ranges were updated, there should only be 2 ranges now. | |
| 80 | + assertThat(metadata.getTokenRanges()).hasSize(2); | |
| 81 | + | |
| 82 | + // The token should not be present for any Host. | |
| 83 | + assertThat(getTokenForHosts(metadata)).doesNotContainValue(host3Token); | |
| 84 | + | |
| 85 | + // The ring should be fully accounted for. | |
| 86 | + assertThat(cluster).hasValidTokenRanges("test"); | |
| 87 | + assertThat(cluster).hasValidTokenRanges(); | |
| 88 | + | |
| 89 | + // Add an additional node. | |
| 90 | + ccm.add(4); | |
| 91 | + ccm.start(4); | |
| 92 | + waitFor(TestUtils.IP_PREFIX + '4', cluster); | |
| 93 | + | |
| 94 | + // Ensure that the token ranges were updated, there should only be 3 ranges now. | |
| 95 | + assertThat(metadata.getTokenRanges()).hasSize(3); | |
| 96 | + | |
| 97 | + Host host4 = TestUtils.findHost(cluster, 4); | |
| 98 | + TokenRange host4Range = metadata.getTokenRanges(keyspace, host4).iterator().next(); | |
| 99 | + | |
| 100 | + // Ensure no host token range intersects with node 4. | |
| 101 | + for (Host host : metadata.getAllHosts()) { | |
| 102 | + if (!host.equals(host4)) { | |
| 103 | + TokenRange hostRange = metadata.getTokenRanges(keyspace, host).iterator().next(); | |
| 104 | + assertThat(host4Range).doesNotIntersect(hostRange); | |
| 107 | 105 | } |
| 108 | - | |
| 109 | - // The ring should be fully accounted for. | |
| 110 | - assertThat(cluster).hasValidTokenRanges("test"); | |
| 111 | - assertThat(cluster).hasValidTokenRanges(); | |
| 112 | - } finally { | |
| 113 | - if (cluster != null) | |
| 114 | - cluster.close(); | |
| 115 | - if (ccm != null) | |
| 116 | - ccm.remove(); | |
| 117 | 106 | } |
| 107 | + | |
| 108 | + // The ring should be fully accounted for. | |
| 109 | + assertThat(cluster).hasValidTokenRanges("test"); | |
| 110 | + assertThat(cluster).hasValidTokenRanges(); | |
| 118 | 111 | } |
| 119 | 112 | |
| 120 | 113 | /** |
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +4 −4
| @@ -25,12 +25,12 @@ | ||
| 25 | 25 | |
| 26 | 26 | import static org.testng.Assert.assertEquals; |
| 27 | 27 | |
| 28 | -public class MetricsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 28 | +public class MetricsTest extends CCMTestsSupport { | |
| 29 | 29 | private volatile RetryDecision retryDecision; |
| 30 | 30 | |
| 31 | 31 | @Override |
| 32 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 33 | - return builder.withRetryPolicy(new RetryPolicy() { | |
| 32 | + public Cluster.Builder createClusterBuilder() { | |
| 33 | + return Cluster.builder().withRetryPolicy(new RetryPolicy() { | |
| 34 | 34 | @Override |
| 35 | 35 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { |
| 36 | 36 | return retryDecision; |
| @@ -49,7 +49,7 @@ | ||
| 49 | 49 | } |
| 50 | 50 | |
| 51 | 51 | @Override |
| 52 | - protected Collection<String> getTableDefinitions() { | |
| 52 | + public Collection<String> createTestFixtures() { | |
| 53 | 53 | return Lists.newArrayList("CREATE TABLE test (k int primary key, v int)", |
| 54 | 54 | "INSERT INTO test (k, v) VALUES (1, 1)"); |
| 55 | 55 | } |
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +28 −39
| @@ -23,6 +23,8 @@ | ||
| 23 | 23 | import java.net.InetAddress; |
| 24 | 24 | import java.net.InetSocketAddress; |
| 25 | 25 | |
| 26 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 27 | +import static java.util.Collections.singleton; | |
| 26 | 28 | import static org.testng.Assert.assertEquals; |
| 27 | 29 | import static org.testng.Assert.assertNull; |
| 28 | 30 | |
| @@ -31,53 +33,40 @@ | ||
| 31 | 33 | * <p/> |
| 32 | 34 | * This can happen because of gossip bugs. We want to ignore these hosts because this is most likely indicative of an error state. |
| 33 | 35 | */ |
| 34 | -public class MissingRpcAddressTest { | |
| 36 | +@CreateCCM(PER_METHOD) | |
| 37 | +@CCMConfig(numberOfNodes = 2, dirtiesContext = true, createCluster = false) | |
| 38 | +public class MissingRpcAddressTest extends CCMTestsSupport { | |
| 35 | 39 | |
| 36 | 40 | @Test(groups = "short") |
| 37 | 41 | public void testMissingRpcAddressAtStartup() throws Exception { |
| 38 | - CCMBridge ccm = CCMBridge.builder("ccm").withNodes(2).build(); | |
| 42 | + deleteNode2RpcAddressFromNode1(); | |
| 43 | + // Use only one contact point to make sure that the control connection is on node1 | |
| 44 | + Cluster cluster = register(Cluster.builder() | |
| 45 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 46 | + .withAddressTranslater(getAddressTranslator()) | |
| 47 | + .build()); | |
| 48 | + cluster.connect(); | |
| 39 | 49 | |
| 40 | - Cluster cluster = null; | |
| 41 | - try { | |
| 42 | - deleteNode2RpcAddressFromNode1(); | |
| 43 | - // Use only one contact point to make sure that the control connection is on node1 | |
| 44 | - cluster = Cluster.builder() | |
| 45 | - .addContactPoint(CCMBridge.IP_PREFIX + "1") | |
| 46 | - .build(); | |
| 47 | - cluster.connect(); | |
| 48 | - | |
| 49 | - // Since node2's RPC address is unknown on our control host, it should have been ignored | |
| 50 | - assertEquals(cluster.getMetrics().getConnectedToHosts().getValue().intValue(), 1); | |
| 51 | - assertNull(cluster.getMetadata().getHost(socketAddress(2))); | |
| 52 | - } finally { | |
| 53 | - if (cluster != null) | |
| 54 | - cluster.close(); | |
| 55 | - ccm.remove(); | |
| 56 | - } | |
| 50 | + // Since node2's RPC address is unknown on our control host, it should have been ignored | |
| 51 | + assertEquals(cluster.getMetrics().getConnectedToHosts().getValue().intValue(), 1); | |
| 52 | + assertNull(cluster.getMetadata().getHost(getInitialContactPoints().get(1))); | |
| 57 | 53 | } |
| 58 | 54 | |
| 59 | 55 | // Artificially modify the system tables to simulate the missing rpc_address. |
| 60 | 56 | private void deleteNode2RpcAddressFromNode1() throws Exception { |
| 61 | - Cluster cluster = null; | |
| 62 | - try { | |
| 63 | - cluster = Cluster.builder() | |
| 64 | - .addContactPoint(CCMBridge.IP_PREFIX + "1") | |
| 65 | - // ensure we will only connect to node1 | |
| 66 | - .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(), | |
| 67 | - Lists.newArrayList(socketAddress(1)))) | |
| 68 | - .build(); | |
| 69 | - Session session = cluster.connect(); | |
| 70 | - String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'", | |
| 71 | - InetAddress.getByName(CCMBridge.IP_PREFIX + "2").getHostName()); | |
| 72 | - session.execute(deleteStmt); | |
| 73 | - session.close(); | |
| 74 | - } finally { | |
| 75 | - if (cluster != null) | |
| 76 | - cluster.close(); | |
| 77 | - } | |
| 57 | + InetSocketAddress firstHost = getHostAddress(1); | |
| 58 | + Cluster cluster = register(Cluster.builder() | |
| 59 | + .addContactPointsWithPorts(singleton(firstHost)) | |
| 60 | + .withAddressTranslater(getAddressTranslator()) | |
| 61 | + // ensure we will only connect to node1 | |
| 62 | + .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(), | |
| 63 | + Lists.newArrayList(firstHost))) | |
| 64 | + .build()); | |
| 65 | + Session session = cluster.connect(); | |
| 66 | + String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'", | |
| 67 | + InetAddress.getByName(TestUtils.IP_PREFIX + "2").getHostName()); | |
| 68 | + session.execute(deleteStmt); | |
| 69 | + session.close(); | |
| 78 | 70 | } |
| 79 | 71 | |
| 80 | - private static InetSocketAddress socketAddress(int node) { | |
| 81 | - return new InetSocketAddress(CCMBridge.IP_PREFIX + Integer.toString(node), 9042); | |
| 82 | - } | |
| 83 | 72 | } |
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +4 −4
| @@ -30,7 +30,6 @@ | ||
| 30 | 30 | |
| 31 | 31 | import java.util.concurrent.ThreadFactory; |
| 32 | 32 | |
| 33 | -import static com.datastax.driver.core.CCMBridge.ipOfNode; | |
| 34 | 33 | import static org.mockito.Answers.CALLS_REAL_METHODS; |
| 35 | 34 | import static org.mockito.Matchers.any; |
| 36 | 35 | import static org.mockito.Mockito.*; |
| @@ -46,7 +45,7 @@ | ||
| 46 | 45 | @Test(groups = "long", dataProvider = "NettyOptionsTest") |
| 47 | 46 | public void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception { |
| 48 | 47 | //given |
| 49 | - CCMBridge ccm = CCMBridge.builder("test").withNodes(hosts).build(); | |
| 48 | + CCMBridge ccm = CCMBridge.builder().withNodes(hosts).build(); | |
| 50 | 49 | Cluster cluster = null; |
| 51 | 50 | try { |
| 52 | 51 | NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get()); |
| @@ -64,7 +63,8 @@ | ||
| 64 | 63 | } |
| 65 | 64 | }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class)); |
| 66 | 65 | cluster = Cluster.builder() |
| 67 | - .addContactPoint(ipOfNode(1)) | |
| 66 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 67 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 68 | 68 | .withPoolingOptions(new PoolingOptions() |
| 69 | 69 | .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections) |
| 70 | 70 | ) |
| @@ -100,4 +100,4 @@ | ||
| 100 | 100 | } |
| 101 | 101 | } |
| 102 | 102 | |
| 103 | -} | |
| No newline at the end of the file | ||
| 103 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +34 −31
| @@ -641,36 +641,39 @@ | ||
| 641 | 641 | public void should_warn_if_replication_factor_cannot_be_met() { |
| 642 | 642 | Logger logger = Logger.getLogger(ReplicationStrategy.NetworkTopologyStrategy.class); |
| 643 | 643 | MemoryAppender logs = new MemoryAppender(); |
| 644 | - logger.setLevel(Level.WARN); | |
| 645 | - logger.addAppender(logs); | |
| 646 | - | |
| 647 | - List<Token> ring = ImmutableList.<Token>builder() | |
| 648 | - .add(TOKEN01) | |
| 649 | - .add(TOKEN02) | |
| 650 | - .add(TOKEN03) | |
| 651 | - .add(TOKEN04) | |
| 652 | - .build(); | |
| 653 | - | |
| 654 | - Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder() | |
| 655 | - .put(TOKEN01, host(IP1, DC1, RACK11)) | |
| 656 | - .put(TOKEN02, host(IP2, DC1, RACK12)) | |
| 657 | - .put(TOKEN03, host(IP3, DC2, RACK21)) | |
| 658 | - .put(TOKEN04, host(IP4, DC2, RACK22)) | |
| 659 | - .build(); | |
| 660 | - | |
| 661 | - // Wrong configuration: impossible replication factor for DC2 | |
| 662 | - networkTopologyStrategy(rf(DC1, 2), rf(DC2, 3)) | |
| 663 | - .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring); | |
| 664 | - assertThat(logs.getNext()) | |
| 665 | - .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, DC2)); | |
| 666 | - | |
| 667 | - // Wrong configuration: non-existing datacenter | |
| 668 | - networkTopologyStrategy(rf(DC1, 2), rf("does_not_exist", 2)) | |
| 669 | - .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring); | |
| 670 | - assertThat(logs.getNext()) | |
| 671 | - .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, "does_not_exist")); | |
| 672 | - | |
| 673 | - logger.setLevel(null); | |
| 674 | - logger.removeAppender(logs); | |
| 644 | + Level originalLevel = logger.getLevel(); | |
| 645 | + try { | |
| 646 | + logger.setLevel(Level.WARN); | |
| 647 | + logger.addAppender(logs); | |
| 648 | + | |
| 649 | + List<Token> ring = ImmutableList.<Token>builder() | |
| 650 | + .add(TOKEN01) | |
| 651 | + .add(TOKEN02) | |
| 652 | + .add(TOKEN03) | |
| 653 | + .add(TOKEN04) | |
| 654 | + .build(); | |
| 655 | + | |
| 656 | + Map<Token, Host> tokenToPrimary = ImmutableMap.<Token, Host>builder() | |
| 657 | + .put(TOKEN01, host(IP1, DC1, RACK11)) | |
| 658 | + .put(TOKEN02, host(IP2, DC1, RACK12)) | |
| 659 | + .put(TOKEN03, host(IP3, DC2, RACK21)) | |
| 660 | + .put(TOKEN04, host(IP4, DC2, RACK22)) | |
| 661 | + .build(); | |
| 662 | + | |
| 663 | + // Wrong configuration: impossible replication factor for DC2 | |
| 664 | + networkTopologyStrategy(rf(DC1, 2), rf(DC2, 3)) | |
| 665 | + .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring); | |
| 666 | + assertThat(logs.getNext()) | |
| 667 | + .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, DC2)); | |
| 668 | + | |
| 669 | + // Wrong configuration: non-existing datacenter | |
| 670 | + networkTopologyStrategy(rf(DC1, 2), rf("does_not_exist", 2)) | |
| 671 | + .computeTokenToReplicaMap(keyspace, tokenToPrimary, ring); | |
| 672 | + assertThat(logs.getNext()) | |
| 673 | + .contains(String.format("Error while computing token map for keyspace %s with datacenter %s", keyspace, "does_not_exist")); | |
| 674 | + } finally { | |
| 675 | + logger.setLevel(originalLevel); | |
| 676 | + logger.removeAppender(logs); | |
| 677 | + } | |
| 675 | 678 | } |
| 676 | 679 | } |
modified driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +8 −20
| @@ -15,18 +15,20 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import org.testng.annotations.AfterClass; | |
| 19 | 18 | import org.testng.annotations.AfterMethod; |
| 20 | -import org.testng.annotations.BeforeClass; | |
| 19 | +import org.testng.annotations.BeforeMethod; | |
| 21 | 20 | import org.testng.annotations.Test; |
| 22 | 21 | |
| 23 | 22 | import java.util.Collection; |
| 24 | 23 | |
| 24 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 25 | 25 | import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; |
| 26 | 26 | import static com.google.common.collect.Lists.newArrayList; |
| 27 | 27 | import static org.mockito.Mockito.*; |
| 28 | 28 | |
| 29 | -public class NodeListRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 29 | +@CreateCCM(PER_METHOD) | |
| 30 | +@CCMConfig(dirtiesContext = true, createKeyspace = false) | |
| 31 | +public class NodeListRefreshDebouncerTest extends CCMTestsSupport { | |
| 30 | 32 | |
| 31 | 33 | private static final int DEBOUNCE_TIME = 2000; |
| 32 | 34 | |
| @@ -42,20 +44,15 @@ | ||
| 42 | 44 | // Keyspaces to drop after test completes. |
| 43 | 45 | private Collection<String> keyspaces = newArrayList(); |
| 44 | 46 | |
| 45 | - @Override | |
| 46 | - protected Collection<String> getTableDefinitions() { | |
| 47 | - return newArrayList(); | |
| 48 | - } | |
| 49 | - | |
| 50 | - @BeforeClass(groups = "short") | |
| 47 | + @BeforeMethod(groups = "short") | |
| 51 | 48 | public void setup() { |
| 52 | 49 | queryOptions = new QueryOptions(); |
| 53 | 50 | queryOptions.setRefreshNodeListIntervalMillis(DEBOUNCE_TIME); |
| 54 | 51 | queryOptions.setMaxPendingRefreshNodeListRequests(5); |
| 55 | 52 | queryOptions.setRefreshSchemaIntervalMillis(0); |
| 56 | 53 | // Create a separate cluster that will receive the schema events on its control connection. |
| 57 | - cluster2 = this.configure(Cluster.builder()) | |
| 58 | - .addContactPointsWithPorts(newArrayList(hostAddress)) | |
| 54 | + cluster2 = Cluster.builder() | |
| 55 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 59 | 56 | .withQueryOptions(queryOptions) |
| 60 | 57 | .build(); |
| 61 | 58 | session2 = cluster2.connect(); |
| @@ -67,17 +64,8 @@ | ||
| 67 | 64 | } |
| 68 | 65 | |
| 69 | 66 | @AfterMethod(groups = "short") |
| 70 | - public void beforeMethod() { | |
| 71 | - reset(controlConnection); | |
| 72 | - } | |
| 73 | - | |
| 74 | - @AfterClass(groups = "short") | |
| 75 | 67 | public void teardown() { |
| 76 | 68 | cluster2.close(); |
| 77 | - // drop all keyspaces | |
| 78 | - for (String keyspace : keyspaces) { | |
| 79 | - session.execute("DROP KEYSPACE " + keyspace); | |
| 80 | - } | |
| 81 | 69 | } |
| 82 | 70 | |
| 83 | 71 | /** |
modified driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +23 −34
| @@ -18,20 +18,14 @@ | ||
| 18 | 18 | import org.mockito.ArgumentCaptor; |
| 19 | 19 | import org.testng.annotations.Test; |
| 20 | 20 | |
| 21 | -import java.util.Collection; | |
| 22 | 21 | import java.util.concurrent.TimeUnit; |
| 23 | 22 | |
| 24 | 23 | import static com.datastax.driver.core.Assertions.assertThat; |
| 25 | -import static com.google.common.collect.Lists.newArrayList; | |
| 26 | 24 | import static org.mockito.ArgumentCaptor.forClass; |
| 27 | 25 | import static org.mockito.Mockito.*; |
| 28 | 26 | |
| 29 | -public class NodeRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 30 | - | |
| 31 | - @Override | |
| 32 | - protected Collection<String> getTableDefinitions() { | |
| 33 | - return newArrayList(); | |
| 34 | - } | |
| 27 | +@CCMConfig(dirtiesContext = true, createCluster = false) | |
| 28 | +public class NodeRefreshDebouncerTest extends CCMTestsSupport { | |
| 35 | 29 | |
| 36 | 30 | /** |
| 37 | 31 | * Ensures that when a new node is bootstrapped into the cluster, stopped, and then subsequently |
| @@ -46,33 +40,28 @@ | ||
| 46 | 40 | */ |
| 47 | 41 | @Test(groups = "long") |
| 48 | 42 | public void should_call_onAdd_with_bootstrap_stop_start() { |
| 49 | - int refreshNodeInterval = 10000; | |
| 43 | + int refreshNodeInterval = 30000; | |
| 50 | 44 | QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval); |
| 51 | - CCMBridge ccm = CCMBridge.builder("test").withNodes(1).build(); | |
| 52 | - Cluster cluster = Cluster.builder() | |
| 53 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 45 | + Cluster cluster = register(Cluster.builder() | |
| 46 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 47 | + .withAddressTranslater(getAddressTranslator()) | |
| 54 | 48 | .withQueryOptions(queryOptions) |
| 55 | - .build(); | |
| 56 | - | |
| 57 | - try { | |
| 58 | - cluster.connect(); | |
| 59 | - Host.StateListener listener = mock(Host.StateListener.class); | |
| 60 | - cluster.register(listener); | |
| 61 | - ccm.bootstrapNode(2); | |
| 62 | - ccm.stop(2); | |
| 63 | - ccm.start(2); | |
| 64 | - | |
| 65 | - ArgumentCaptor<Host> captor = forClass(Host.class); | |
| 66 | - | |
| 67 | - // Only onAdd should be called, since stop and start should be discarded. | |
| 68 | - verify(listener, timeout(refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS)).only()).onAdd(captor.capture()); | |
| 69 | - | |
| 70 | - // The hosts state should be UP. | |
| 71 | - assertThat(captor.getValue().getState()).isEqualTo("UP"); | |
| 72 | - assertThat(cluster).host(2).hasState(Host.State.UP); | |
| 73 | - } finally { | |
| 74 | - cluster.close(); | |
| 75 | - ccm.remove(); | |
| 76 | - } | |
| 49 | + .build()); | |
| 50 | + cluster.connect(); | |
| 51 | + Host.StateListener listener = mock(Host.StateListener.class); | |
| 52 | + cluster.register(listener); | |
| 53 | + ccm.add(2); | |
| 54 | + ccm.start(2); | |
| 55 | + ccm.stop(2); | |
| 56 | + ccm.start(2); | |
| 57 | + | |
| 58 | + ArgumentCaptor<Host> captor = forClass(Host.class); | |
| 59 | + | |
| 60 | + // Only onAdd should be called, since stop and start should be discarded. | |
| 61 | + verify(listener, timeout(refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS)).only()).onAdd(captor.capture()); | |
| 62 | + | |
| 63 | + // The hosts state should be UP. | |
| 64 | + assertThat(captor.getValue().getState()).isEqualTo("UP"); | |
| 65 | + assertThat(cluster).host(2).hasState(Host.State.UP); | |
| 77 | 66 | } |
| 78 | 67 | } |
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenIntegrationTest.java +3 −1
| @@ -17,9 +17,11 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.Token.OPPToken; |
| 19 | 19 | |
| 20 | +@CCMConfig(options = "-p ByteOrderedPartitioner") | |
| 20 | 21 | public class OPPTokenIntegrationTest extends TokenIntegrationTest { |
| 22 | + | |
| 21 | 23 | public OPPTokenIntegrationTest() { |
| 22 | - super("-p ByteOrderedPartitioner", DataType.blob()); | |
| 24 | + super(DataType.blob(), false); | |
| 23 | 25 | } |
| 24 | 26 | |
| 25 | 27 | @Override |
modified driver-core/src/test/java/com/datastax/driver/core/OPPTokenVnodeIntegrationTest.java +3 −1
| @@ -15,9 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +@CCMConfig(options = {"-p ByteOrderedPartitioner", "--vnodes"}) | |
| 18 | 19 | public class OPPTokenVnodeIntegrationTest extends TokenIntegrationTest { |
| 20 | + | |
| 19 | 21 | public OPPTokenVnodeIntegrationTest() { |
| 20 | - super("-p ByteOrderedPartitioner", DataType.blob(), true); | |
| 22 | + super(DataType.blob(), true); | |
| 21 | 23 | } |
| 22 | 24 | |
| 23 | 25 | @Override |
modified driver-core/src/test/java/com/datastax/driver/core/PagingStateTest.java +4 −2
| @@ -29,12 +29,14 @@ | ||
| 29 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 30 | 30 | |
| 31 | 31 | @CassandraVersion(major = 2.0) |
| 32 | -public class PagingStateTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 32 | +public class PagingStateTest extends CCMTestsSupport { | |
| 33 | + | |
| 33 | 34 | private static final Logger logger = LoggerFactory.getLogger(PagingStateTest.class); |
| 35 | + | |
| 34 | 36 | public static final String KEY = "paging_test"; |
| 35 | 37 | |
| 36 | 38 | @Override |
| 37 | - protected Collection<String> getTableDefinitions() { | |
| 39 | + public Collection<String> createTestFixtures() { | |
| 38 | 40 | return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))"); |
| 39 | 41 | } |
| 40 | 42 |
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java +34 −36
| @@ -15,10 +15,9 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import org.testng.annotations.AfterMethod; | |
| 18 | 19 | import org.testng.annotations.Test; |
| 19 | 20 | |
| 20 | -import java.util.Collection; | |
| 21 | -import java.util.Collections; | |
| 22 | 21 | import java.util.concurrent.LinkedBlockingQueue; |
| 23 | 22 | import java.util.concurrent.ThreadPoolExecutor; |
| 24 | 23 | import java.util.concurrent.TimeUnit; |
| @@ -27,10 +26,23 @@ | ||
| 27 | 26 | import static org.mockito.Matchers.any; |
| 28 | 27 | import static org.mockito.Mockito.*; |
| 29 | 28 | |
| 30 | -public class PoolingOptionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 29 | +@CCMConfig(createSession = false) | |
| 30 | +public class PoolingOptionsIntegrationTest extends CCMTestsSupport { | |
| 31 | + | |
| 32 | + private ThreadPoolExecutor executor; | |
| 33 | + | |
| 31 | 34 | @Override |
| 32 | - protected Collection<String> getTableDefinitions() { | |
| 33 | - return Collections.emptyList(); | |
| 35 | + public Cluster.Builder createClusterBuilder() { | |
| 36 | + executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())); | |
| 37 | + PoolingOptions poolingOptions = new PoolingOptions(); | |
| 38 | + poolingOptions.setInitializationExecutor(executor); | |
| 39 | + return Cluster.builder().withPoolingOptions(poolingOptions); | |
| 40 | + } | |
| 41 | + | |
| 42 | + @AfterMethod(groups = "short") | |
| 43 | + public void shutdownExecutor() { | |
| 44 | + if (executor != null) | |
| 45 | + executor.shutdown(); | |
| 34 | 46 | } |
| 35 | 47 | |
| 36 | 48 | /** |
| @@ -46,44 +58,30 @@ | ||
| 46 | 58 | */ |
| 47 | 59 | @Test(groups = "short") |
| 48 | 60 | public void should_be_able_to_use_custom_initialization_executor() { |
| 49 | - ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, | |
| 50 | - new LinkedBlockingQueue<Runnable>())); | |
| 51 | - | |
| 52 | - PoolingOptions poolingOptions = new PoolingOptions(); | |
| 53 | - poolingOptions.setInitializationExecutor(executor); | |
| 61 | + cluster.init(); | |
| 62 | + // Ensure executor used. | |
| 63 | + verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 54 | 64 | |
| 55 | - Cluster cluster = Cluster.builder() | |
| 56 | - .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 57 | - .withPoolingOptions(poolingOptions).build(); | |
| 58 | - try { | |
| 59 | - cluster.init(); | |
| 60 | - // Ensure executor used. | |
| 61 | - verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 65 | + // Reset invocation count. | |
| 66 | + reset(); | |
| 62 | 67 | |
| 63 | - // Reset invocation count. | |
| 64 | - reset(); | |
| 68 | + Session session = cluster.connect(); | |
| 65 | 69 | |
| 66 | - Session session = cluster.connect(); | |
| 70 | + // Ensure executor used again to establish core connections. | |
| 71 | + verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 67 | 72 | |
| 68 | - // Ensure executor used again to establish core connections. | |
| 69 | - verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 73 | + // Expect core connections + control connection. | |
| 74 | + assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo( | |
| 75 | + TestUtils.numberOfLocalCoreConnections(cluster) + 1); | |
| 70 | 76 | |
| 71 | - // Expect core connections + control connection. | |
| 72 | - assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo( | |
| 73 | - TestUtils.numberOfLocalCoreConnections(cluster) + 1); | |
| 77 | + reset(); | |
| 74 | 78 | |
| 75 | - reset(); | |
| 79 | + session.close(); | |
| 76 | 80 | |
| 77 | - session.close(); | |
| 81 | + // Executor should have been used to close connections associated with the session. | |
| 82 | + verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 78 | 83 | |
| 79 | - // Executor should have been used to close connections associated with the session. | |
| 80 | - verify(executor, atLeastOnce()).execute(any(Runnable.class)); | |
| 81 | - | |
| 82 | - // Only the control connection should remain. | |
| 83 | - assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1); | |
| 84 | - } finally { | |
| 85 | - cluster.close(); | |
| 86 | - executor.shutdown(); | |
| 87 | - } | |
| 84 | + // Only the control connection should remain. | |
| 85 | + assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1); | |
| 88 | 86 | } |
| 89 | 87 | } |
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +5 −10
| @@ -18,7 +18,6 @@ | ||
| 18 | 18 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 19 | 19 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 20 | 20 | import com.datastax.driver.core.utils.CassandraVersion; |
| 21 | -import com.google.common.collect.ImmutableList; | |
| 22 | 21 | import org.testng.annotations.Test; |
| 23 | 22 | |
| 24 | 23 | import java.net.InetAddress; |
| @@ -33,7 +32,8 @@ | ||
| 33 | 32 | * <p/> |
| 34 | 33 | * Note: this class also happens to test all the get methods from Row. |
| 35 | 34 | */ |
| 36 | -public class PreparedStatementTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 35 | +@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing") | |
| 36 | +public class PreparedStatementTest extends CCMTestsSupport { | |
| 37 | 37 | |
| 38 | 38 | private static final String ALL_NATIVE_TABLE = "all_native"; |
| 39 | 39 | private static final String ALL_LIST_TABLE = "all_list"; |
| @@ -47,7 +47,7 @@ | ||
| 47 | 47 | } |
| 48 | 48 | |
| 49 | 49 | @Override |
| 50 | - protected Collection<String> getTableDefinitions() { | |
| 50 | + public Collection<String> createTestFixtures() { | |
| 51 | 51 | |
| 52 | 52 | List<String> defs = new ArrayList<String>(4); |
| 53 | 53 | |
| @@ -105,11 +105,6 @@ | ||
| 105 | 105 | return defs; |
| 106 | 106 | } |
| 107 | 107 | |
| 108 | - @Override | |
| 109 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 110 | - return builder.withQueryOptions(TestUtils.nonDebouncingQueryOptions()); | |
| 111 | - } | |
| 112 | - | |
| 113 | 108 | @Test(groups = "short") |
| 114 | 109 | public void preparedNativeTest() { |
| 115 | 110 | // Test preparing/bounding for all native types |
| @@ -346,7 +341,7 @@ | ||
| 346 | 341 | */ |
| 347 | 342 | @Test(groups = {"docs"}) |
| 348 | 343 | public void printTableDefinitions() { |
| 349 | - for (String definition : getTableDefinitions()) { | |
| 344 | + for (String definition : createTestFixtures()) { | |
| 350 | 345 | System.out.println(definition); |
| 351 | 346 | } |
| 352 | 347 | } |
| @@ -424,7 +419,7 @@ | ||
| 424 | 419 | @Test(groups = "short", expectedExceptions = InvalidQueryException.class) |
| 425 | 420 | public void should_fail_when_prepared_on_another_cluster() throws Exception { |
| 426 | 421 | Cluster otherCluster = Cluster.builder() |
| 427 | - .addContactPointsWithPorts(ImmutableList.of(hostAddress)) | |
| 422 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 428 | 423 | .build(); |
| 429 | 424 | try { |
| 430 | 425 | PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?"); |
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +9 −4
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.*; |
| 19 | +import org.apache.log4j.Level; | |
| 19 | 20 | import org.apache.log4j.Logger; |
| 20 | 21 | import org.scassandra.http.client.PrimingRequest; |
| 21 | 22 | import org.testng.annotations.AfterMethod; |
| @@ -48,9 +49,13 @@ | ||
| 48 | 49 | private Cluster cluster = null; |
| 49 | 50 | private Session session = null; |
| 50 | 51 | private QueryLogger queryLogger = null; |
| 52 | + private Level originalError; | |
| 53 | + private Level originalSlow; | |
| 51 | 54 | |
| 52 | 55 | @BeforeMethod(groups = {"short", "unit"}) |
| 53 | 56 | public void setUp() { |
| 57 | + originalSlow = slow.getLevel(); | |
| 58 | + originalError = error.getLevel(); | |
| 54 | 59 | slow.setLevel(INFO); |
| 55 | 60 | error.setLevel(INFO); |
| 56 | 61 | slow.addAppender(slowAppender = new MemoryAppender()); |
| @@ -62,10 +67,10 @@ | ||
| 62 | 67 | session = cluster.connect(); |
| 63 | 68 | } |
| 64 | 69 | |
| 65 | - @AfterMethod(groups = {"short", "unit"}) | |
| 70 | + @AfterMethod(groups = {"short", "unit"}, alwaysRun = true) | |
| 66 | 71 | public void tearDown() { |
| 67 | - slow.setLevel(null); | |
| 68 | - error.setLevel(null); | |
| 72 | + slow.setLevel(originalSlow); | |
| 73 | + error.setLevel(originalError); | |
| 69 | 74 | slow.removeAppender(slowAppender); |
| 70 | 75 | error.removeAppender(errorAppender); |
| 71 | 76 | |
| @@ -194,4 +199,4 @@ | ||
| 194 | 199 | .contains(loggedException.getName()); |
| 195 | 200 | } |
| 196 | 201 | |
| 197 | -} | |
| No newline at the end of the file | ||
| 202 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerTest.java +19 −16
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | import com.google.common.collect.Lists; |
| 24 | 24 | import com.google.common.collect.Sets; |
| 25 | 25 | import com.google.common.primitives.Bytes; |
| 26 | +import org.apache.log4j.Level; | |
| 26 | 27 | import org.apache.log4j.Logger; |
| 27 | 28 | import org.testng.annotations.AfterMethod; |
| 28 | 29 | import org.testng.annotations.BeforeMethod; |
| @@ -34,9 +35,9 @@ | ||
| 34 | 35 | |
| 35 | 36 | import static com.datastax.driver.core.BatchStatement.Type.COUNTER; |
| 36 | 37 | import static com.datastax.driver.core.BatchStatement.Type.UNLOGGED; |
| 37 | -import static com.datastax.driver.core.CCMBridge.ipOfNode; | |
| 38 | 38 | import static com.datastax.driver.core.QueryLogger.*; |
| 39 | 39 | import static com.datastax.driver.core.TestUtils.getFixedValue; |
| 40 | +import static com.datastax.driver.core.TestUtils.ipOfNode; | |
| 40 | 41 | import static org.apache.log4j.Level.*; |
| 41 | 42 | import static org.assertj.core.api.Assertions.assertThat; |
| 42 | 43 | import static org.mockito.Mockito.mock; |
| @@ -46,7 +47,7 @@ | ||
| 46 | 47 | * More tests, specifically targeting slow and unsuccessful queries, can be found in |
| 47 | 48 | * {@link QueryLoggerErrorsTest}. |
| 48 | 49 | */ |
| 49 | -public class QueryLoggerTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 50 | +public class QueryLoggerTest extends CCMTestsSupport { | |
| 50 | 51 | |
| 51 | 52 | private static final List<DataType> dataTypes = new ArrayList<DataType>(Sets.filter(DataType.allPrimitiveTypes(), new Predicate<DataType>() { |
| 52 | 53 | @Override |
| @@ -92,32 +93,34 @@ | ||
| 92 | 93 | private MemoryAppender errorAppender; |
| 93 | 94 | |
| 94 | 95 | private QueryLogger queryLogger; |
| 96 | + private Level originalNormal; | |
| 97 | + private Level originalSlow; | |
| 98 | + private Level originalError; | |
| 95 | 99 | |
| 96 | 100 | @BeforeMethod(groups = {"short", "unit"}) |
| 97 | 101 | public void startCapturingLogs() { |
| 102 | + originalNormal = normal.getLevel(); | |
| 103 | + originalSlow = slow.getLevel(); | |
| 104 | + originalError = error.getLevel(); | |
| 105 | + normal.setLevel(INFO); | |
| 106 | + slow.setLevel(INFO); | |
| 107 | + error.setLevel(INFO); | |
| 98 | 108 | normal.addAppender(normalAppender = new MemoryAppender()); |
| 99 | 109 | slow.addAppender(slowAppender = new MemoryAppender()); |
| 100 | 110 | error.addAppender(errorAppender = new MemoryAppender()); |
| 101 | 111 | } |
| 102 | 112 | |
| 103 | - @AfterMethod(groups = {"short", "unit"}) | |
| 113 | + @AfterMethod(groups = {"short", "unit"}, alwaysRun = true) | |
| 104 | 114 | public void stopCapturingLogs() { |
| 105 | - normal.setLevel(null); | |
| 106 | - slow.setLevel(null); | |
| 107 | - error.setLevel(null); | |
| 115 | + normal.setLevel(originalNormal); | |
| 116 | + slow.setLevel(originalSlow); | |
| 117 | + error.setLevel(originalError); | |
| 108 | 118 | normal.removeAppender(normalAppender); |
| 109 | 119 | slow.removeAppender(slowAppender); |
| 110 | 120 | error.removeAppender(errorAppender); |
| 111 | 121 | } |
| 112 | 122 | |
| 113 | - @BeforeMethod(groups = {"short", "unit"}) | |
| 114 | - public void resetLogLevels() { | |
| 115 | - normal.setLevel(INFO); | |
| 116 | - slow.setLevel(INFO); | |
| 117 | - error.setLevel(INFO); | |
| 118 | - } | |
| 119 | - | |
| 120 | - @AfterMethod(groups = {"short", "unit"}) | |
| 123 | + @AfterMethod(groups = {"short", "unit"}, alwaysRun = true) | |
| 121 | 124 | public void unregisterQueryLogger() { |
| 122 | 125 | if (cluster != null && queryLogger != null) { |
| 123 | 126 | cluster.unregister(queryLogger); |
| @@ -714,8 +717,8 @@ | ||
| 714 | 717 | } |
| 715 | 718 | |
| 716 | 719 | @Override |
| 717 | - protected List<String> getTableDefinitions() { | |
| 720 | + public List<String> createTestFixtures() { | |
| 718 | 721 | return Lists.newArrayList("CREATE TABLE test (pk int PRIMARY KEY, " + definitions + ")"); |
| 719 | 722 | } |
| 720 | 723 | |
| 721 | -} | |
| No newline at the end of the file | ||
| 724 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java +15 −2
| @@ -22,12 +22,14 @@ | ||
| 22 | 22 | import org.testng.annotations.Test; |
| 23 | 23 | |
| 24 | 24 | import java.util.List; |
| 25 | +import java.util.concurrent.Callable; | |
| 25 | 26 | import java.util.concurrent.TimeUnit; |
| 26 | 27 | |
| 27 | 28 | import static com.datastax.driver.core.Assertions.assertThat; |
| 28 | 29 | import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; |
| 29 | 30 | |
| 30 | 31 | public class QueryOptionsTest { |
| 32 | + | |
| 31 | 33 | ScassandraCluster scassandra; |
| 32 | 34 | |
| 33 | 35 | QueryOptions queryOptions; |
| @@ -47,7 +49,8 @@ | ||
| 47 | 49 | queryOptions = new QueryOptions(); |
| 48 | 50 | loadBalancingPolicy = new SortingLoadBalancingPolicy(); |
| 49 | 51 | cluster = Cluster.builder() |
| 50 | - .addContactPoint(CCMBridge.ipOfNode(2)) | |
| 52 | + .addContactPointsWithPorts(scassandra.address(2)) | |
| 53 | + .withAddressTranslater(scassandra.addressTranslator()) | |
| 51 | 54 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 52 | 55 | .withQueryOptions(queryOptions) |
| 53 | 56 | .withNettyOptions(nonQuietClusterCloseOptions) |
| @@ -62,6 +65,7 @@ | ||
| 62 | 65 | // Make sure there are no prepares |
| 63 | 66 | for (int host : Lists.newArrayList(1, 2, 3)) { |
| 64 | 67 | assertThat(scassandra.node(host).activityClient().retrievePreparedStatementPreparations()).hasSize(0); |
| 68 | + scassandra.node(host).activityClient().clearAllRecordedActivity(); | |
| 65 | 69 | } |
| 66 | 70 | } |
| 67 | 71 | |
| @@ -158,6 +162,15 @@ | ||
| 158 | 162 | |
| 159 | 163 | preparationOne = scassandra.node(1).activityClient().retrievePreparedStatementPreparations(); |
| 160 | 164 | if (expectReprepare) { |
| 165 | + // tests fail randomly at this point, probably due to | |
| 166 | + // https://github.com/scassandra/scassandra-server/issues/116 | |
| 167 | + ConditionChecker.awaitWhile(new Callable<Boolean>() { | |
| 168 | + @Override | |
| 169 | + public Boolean call() { | |
| 170 | + return session.getState().getConnectedHosts().size() < 3 | |
| 171 | + || scassandra.node(1).activityClient().retrievePreparedStatementPreparations().isEmpty(); | |
| 172 | + } | |
| 173 | + }, TimeUnit.MINUTES.toMillis(1)); | |
| 161 | 174 | assertThat(preparationOne).hasSize(1); |
| 162 | 175 | assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query); |
| 163 | 176 | } else { |
| @@ -215,7 +228,7 @@ | ||
| 215 | 228 | valideReprepareOnUp(false); |
| 216 | 229 | } |
| 217 | 230 | |
| 218 | - @AfterMethod(groups = "short") | |
| 231 | + @AfterMethod(groups = "short", alwaysRun = true) | |
| 219 | 232 | public void afterMethod() { |
| 220 | 233 | if (cluster != null) |
| 221 | 234 | cluster.close(); |
modified driver-core/src/test/java/com/datastax/driver/core/QueryTimestampTest.java +4 −5
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.Cluster.Builder; | |
| 19 | 18 | import com.datastax.driver.core.Metrics.Errors; |
| 20 | 19 | import com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy; |
| 21 | 20 | import com.datastax.driver.core.utils.CassandraVersion; |
| @@ -32,18 +31,18 @@ | ||
| 32 | 31 | * Tests the behavior of client-provided timestamps with protocol v3. |
| 33 | 32 | */ |
| 34 | 33 | @CassandraVersion(major = 2.1) |
| 35 | -public class QueryTimestampTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 34 | +public class QueryTimestampTest extends CCMTestsSupport { | |
| 36 | 35 | |
| 37 | 36 | @Override |
| 38 | - protected Collection<String> getTableDefinitions() { | |
| 37 | + public Collection<String> createTestFixtures() { | |
| 39 | 38 | return Lists.newArrayList("CREATE TABLE foo (k int PRIMARY KEY, v int)"); |
| 40 | 39 | } |
| 41 | 40 | |
| 42 | 41 | private volatile long timestampFromGenerator; |
| 43 | 42 | |
| 44 | 43 | @Override |
| 45 | - protected Builder configure(Builder builder) { | |
| 46 | - return builder | |
| 44 | + public Cluster.Builder createClusterBuilder() { | |
| 45 | + return Cluster.builder() | |
| 47 | 46 | .withTimestampGenerator(new TimestampGenerator() { |
| 48 | 47 | @Override |
| 49 | 48 | public long next() { |
modified driver-core/src/test/java/com/datastax/driver/core/QueryTracker.java +3 −2
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | import org.assertj.core.util.Maps; |
| 22 | 22 | |
| 23 | 23 | import java.net.InetAddress; |
| 24 | +import java.net.InetSocketAddress; | |
| 24 | 25 | import java.util.List; |
| 25 | 26 | import java.util.Map; |
| 26 | 27 | import java.util.concurrent.ExecutionException; |
| @@ -88,8 +89,8 @@ | ||
| 88 | 89 | |
| 89 | 90 | public int queryCount(ScassandraCluster sCluster, int dc, int node) { |
| 90 | 91 | try { |
| 91 | - String host = sCluster.address(dc, node); | |
| 92 | - Integer queried = coordinators.get(InetAddress.getByName(host)); | |
| 92 | + InetSocketAddress host = sCluster.address(dc, node); | |
| 93 | + Integer queried = coordinators.get(host.getAddress()); | |
| 93 | 94 | return queried != null ? queried : 0; |
| 94 | 95 | } catch (Exception e) { |
| 95 | 96 | throw new RuntimeException(e); |
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenIntegrationTest.java +3 −1
| @@ -17,9 +17,11 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.Token.RPToken; |
| 19 | 19 | |
| 20 | +@CCMConfig(options = "-p RandomPartitioner") | |
| 20 | 21 | public class RPTokenIntegrationTest extends TokenIntegrationTest { |
| 22 | + | |
| 21 | 23 | public RPTokenIntegrationTest() { |
| 22 | - super("-p RandomPartitioner", DataType.varint()); | |
| 24 | + super(DataType.varint(), false); | |
| 23 | 25 | } |
| 24 | 26 | |
| 25 | 27 | @Override |
modified driver-core/src/test/java/com/datastax/driver/core/RPTokenVnodeIntegrationTest.java +3 −1
| @@ -15,9 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +@CCMConfig(options = {"-p RandomPartitioner", "--vnodes"}) | |
| 18 | 19 | public class RPTokenVnodeIntegrationTest extends TokenIntegrationTest { |
| 20 | + | |
| 19 | 21 | public RPTokenVnodeIntegrationTest() { |
| 20 | - super("-p RandomPartitioner", DataType.varint(), true); | |
| 22 | + super(DataType.varint(), true); | |
| 21 | 23 | } |
| 22 | 24 | |
| 23 | 25 | @Override |
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +39 −14
| @@ -44,20 +44,26 @@ | ||
| 44 | 44 | |
| 45 | 45 | @Test(groups = "long") |
| 46 | 46 | public void should_ignore_recommissioned_node_on_reconnection_attempt() throws Exception { |
| 47 | - mainCcm = CCMBridge.builder("main").withNodes(3).build(); | |
| 47 | + mainCcm = CCMBridge.builder().withNodes(3).build(); | |
| 48 | 48 | // node1 will be our "recommissioned" node, for now we just stop it so that it stays in the peers table. |
| 49 | 49 | mainCcm.stop(1); |
| 50 | 50 | mainCcm.waitForDown(1); |
| 51 | 51 | |
| 52 | 52 | // Now start the driver that will connect to node2 and node3, and consider node1 down |
| 53 | - mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2") | |
| 53 | + mainCluster = Cluster.builder() | |
| 54 | + .addContactPointsWithPorts(mainCcm.addressOfNode(2)) | |
| 55 | + .withAddressTranslater(mainCcm.addressTranslator()) | |
| 54 | 56 | .withQueryOptions(nonDebouncingQueryOptions()).build(); |
| 55 | 57 | mainCluster.connect(); |
| 56 | 58 | waitForCountUpHosts(mainCluster, 2); |
| 57 | 59 | // From that point, reconnections to node1 have been scheduled. |
| 58 | 60 | |
| 59 | 61 | // Start another ccm that will reuse node1's address |
| 60 | - otherCcm = CCMBridge.builder("other").withNodes(1).build(); | |
| 62 | + otherCcm = CCMBridge.builder() | |
| 63 | + .withStoragePort(mainCcm.getStoragePort()) | |
| 64 | + .withThriftPort(mainCcm.getThriftPort()) | |
| 65 | + .withBinaryPort(mainCcm.getBinaryPort()) | |
| 66 | + .withNodes(1).build(); | |
| 61 | 67 | otherCcm.waitForUp(1); |
| 62 | 68 | |
| 63 | 69 | // Give the driver the time to notice the node is back up and try to connect to it. |
| @@ -68,18 +74,24 @@ | ||
| 68 | 74 | |
| 69 | 75 | @Test(groups = "long") |
| 70 | 76 | public void should_ignore_recommissioned_node_on_control_connection_reconnect() throws Exception { |
| 71 | - mainCcm = CCMBridge.builder("main").withNodes(2).build(); | |
| 77 | + mainCcm = CCMBridge.builder().withNodes(2).build(); | |
| 72 | 78 | mainCcm.stop(1); |
| 73 | 79 | mainCcm.waitForDown(1); |
| 74 | 80 | |
| 75 | 81 | // Start the driver, the control connection will be on node2 |
| 76 | - mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2") | |
| 82 | + mainCluster = Cluster.builder() | |
| 83 | + .addContactPointsWithPorts(mainCcm.addressOfNode(2)) | |
| 84 | + .withAddressTranslater(mainCcm.addressTranslator()) | |
| 77 | 85 | .withQueryOptions(nonDebouncingQueryOptions()).build(); |
| 78 | 86 | mainCluster.connect(); |
| 79 | 87 | waitForCountUpHosts(mainCluster, 1); |
| 80 | 88 | |
| 81 | 89 | // Start another ccm that will reuse node1's address |
| 82 | - otherCcm = CCMBridge.builder("other").withNodes(1).build(); | |
| 90 | + otherCcm = CCMBridge.builder() | |
| 91 | + .withStoragePort(mainCcm.getStoragePort()) | |
| 92 | + .withThriftPort(mainCcm.getThriftPort()) | |
| 93 | + .withBinaryPort(mainCcm.getBinaryPort()) | |
| 94 | + .withNodes(1).build(); | |
| 83 | 95 | otherCcm.waitForUp(1); |
| 84 | 96 | |
| 85 | 97 | // Stop node2, the control connection gets defunct |
| @@ -93,15 +105,21 @@ | ||
| 93 | 105 | @Test(groups = "long") |
| 94 | 106 | public void should_ignore_recommissioned_node_on_session_init() throws Exception { |
| 95 | 107 | // Simulate the bug before starting the cluster |
| 96 | - mainCcm = CCMBridge.builder("main").withNodes(2).build(); | |
| 108 | + mainCcm = CCMBridge.builder().withNodes(2).build(); | |
| 97 | 109 | mainCcm.stop(1); |
| 98 | 110 | mainCcm.waitForDown(1); |
| 99 | 111 | |
| 100 | - otherCcm = CCMBridge.builder("other").withNodes(1).build(); | |
| 112 | + otherCcm = CCMBridge.builder() | |
| 113 | + .withStoragePort(mainCcm.getStoragePort()) | |
| 114 | + .withThriftPort(mainCcm.getThriftPort()) | |
| 115 | + .withBinaryPort(mainCcm.getBinaryPort()) | |
| 116 | + .withNodes(1).build(); | |
| 101 | 117 | otherCcm.waitForUp(1); |
| 102 | 118 | |
| 103 | 119 | // Start the driver, it should only connect to node 2 |
| 104 | - mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2") | |
| 120 | + mainCluster = Cluster.builder() | |
| 121 | + .addContactPointsWithPorts(mainCcm.addressOfNode(2)) | |
| 122 | + .withAddressTranslater(mainCcm.addressTranslator()) | |
| 105 | 123 | .withQueryOptions(nonDebouncingQueryOptions()).build(); |
| 106 | 124 | |
| 107 | 125 | // When we first initialize the Cluster, all hosts are marked UP |
| @@ -122,15 +140,22 @@ | ||
| 122 | 140 | @CassandraVersion(major = 2.0) |
| 123 | 141 | public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception { |
| 124 | 142 | // Simulate the bug before starting the cluster |
| 125 | - mainCcm = CCMBridge.builder("main").withNodes(2).build(); | |
| 143 | + mainCcm = CCMBridge.builder().withNodes(2).build(); | |
| 126 | 144 | mainCcm.stop(1); |
| 127 | 145 | mainCcm.waitForDown(1); |
| 128 | 146 | |
| 129 | - otherCcm = CCMBridge.builder("main").withNodes(1).withCassandraVersion("1.2.19").build(); | |
| 147 | + otherCcm = CCMBridge.builder().withNodes(1) | |
| 148 | + .withStoragePort(mainCcm.getStoragePort()) | |
| 149 | + .withThriftPort(mainCcm.getThriftPort()) | |
| 150 | + .withBinaryPort(mainCcm.getBinaryPort()) | |
| 151 | + .withVersion("1.2.19") | |
| 152 | + .build(); | |
| 130 | 153 | otherCcm.waitForUp(1); |
| 131 | 154 | |
| 132 | 155 | // Start the driver, it should only connect to node 2 |
| 133 | - mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2") | |
| 156 | + mainCluster = Cluster.builder() | |
| 157 | + .addContactPointsWithPorts(mainCcm.addressOfNode(2)) | |
| 158 | + .withAddressTranslater(mainCcm.addressTranslator()) | |
| 134 | 159 | .withQueryOptions(nonDebouncingQueryOptions()).build(); |
| 135 | 160 | |
| 136 | 161 | // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version. |
| @@ -151,7 +176,7 @@ | ||
| 151 | 176 | otherCcm = null; |
| 152 | 177 | } |
| 153 | 178 | |
| 154 | - @AfterMethod(groups = "long") | |
| 179 | + @AfterMethod(groups = "long", alwaysRun = true) | |
| 155 | 180 | public void teardown() { |
| 156 | 181 | if (mainCluster != null) |
| 157 | 182 | mainCluster.close(); |
| @@ -189,4 +214,4 @@ | ||
| 189 | 214 | TimeUnit.SECONDS.sleep(interval); |
| 190 | 215 | } |
| 191 | 216 | } |
| 192 | -} | |
| No newline at the end of the file | ||
| 217 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionPolicyTest.java +84 −76
| @@ -21,25 +21,37 @@ | ||
| 21 | 21 | import com.datastax.driver.core.policies.ReconnectionPolicy; |
| 22 | 22 | import org.testng.annotations.Test; |
| 23 | 23 | |
| 24 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 24 | 25 | import static org.testng.Assert.assertTrue; |
| 25 | 26 | import static org.testng.Assert.fail; |
| 26 | 27 | |
| 28 | +@CreateCCM(PER_METHOD) | |
| 29 | +@CCMConfig(dirtiesContext = true, createKeyspace = false) | |
| 30 | +@SuppressWarnings("unused") | |
| 27 | 31 | public class ReconnectionPolicyTest extends AbstractPoliciesTest { |
| 28 | 32 | |
| 33 | + private Cluster.Builder exponential() { | |
| 34 | + return Cluster.builder().withReconnectionPolicy(new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000)); | |
| 35 | + } | |
| 36 | + | |
| 37 | + private Cluster.Builder constant() { | |
| 38 | + return Cluster.builder().withReconnectionPolicy(new ConstantReconnectionPolicy(10 * 1000)); | |
| 39 | + } | |
| 40 | + | |
| 29 | 41 | /* |
| 30 | 42 | * Test the ExponentialReconnectionPolicy. |
| 31 | 43 | */ |
| 32 | 44 | @Test(groups = "long") |
| 45 | + @CCMConfig(clusterProvider = "exponential") | |
| 33 | 46 | public void exponentialReconnectionPolicyTest() throws Throwable { |
| 34 | - Cluster.Builder builder = Cluster.builder().withReconnectionPolicy(new ExponentialReconnectionPolicy(2 * 1000, 5 * 60 * 1000)); | |
| 35 | 47 | |
| 36 | 48 | // Ensure that ExponentialReconnectionPolicy is what we should be testing |
| 37 | - if (!(builder.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ExponentialReconnectionPolicy)) { | |
| 49 | + if (!(cluster.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ExponentialReconnectionPolicy)) { | |
| 38 | 50 | fail("Set policy does not match retrieved policy."); |
| 39 | 51 | } |
| 40 | 52 | |
| 41 | 53 | // Test basic getters |
| 42 | - ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy) builder.getConfiguration().getPolicies().getReconnectionPolicy(); | |
| 54 | + ExponentialReconnectionPolicy reconnectionPolicy = (ExponentialReconnectionPolicy) cluster.getConfiguration().getPolicies().getReconnectionPolicy(); | |
| 43 | 55 | assertTrue(reconnectionPolicy.getBaseDelayMs() == 2 * 1000); |
| 44 | 56 | assertTrue(reconnectionPolicy.getMaxDelayMs() == 5 * 60 * 1000); |
| 45 | 57 | |
| @@ -48,24 +60,28 @@ | ||
| 48 | 60 | new ExponentialReconnectionPolicy(-1, 1); |
| 49 | 61 | fail(); |
| 50 | 62 | } catch (IllegalArgumentException e) { |
| 63 | + //ok | |
| 51 | 64 | } |
| 52 | 65 | |
| 53 | 66 | try { |
| 54 | 67 | new ExponentialReconnectionPolicy(1, -1); |
| 55 | 68 | fail(); |
| 56 | 69 | } catch (IllegalArgumentException e) { |
| 70 | + //ok | |
| 57 | 71 | } |
| 58 | 72 | |
| 59 | 73 | try { |
| 60 | 74 | new ExponentialReconnectionPolicy(-1, -1); |
| 61 | 75 | fail(); |
| 62 | 76 | } catch (IllegalArgumentException e) { |
| 77 | + //ok | |
| 63 | 78 | } |
| 64 | 79 | |
| 65 | 80 | try { |
| 66 | 81 | new ExponentialReconnectionPolicy(2, 1); |
| 67 | 82 | fail(); |
| 68 | 83 | } catch (IllegalArgumentException e) { |
| 84 | + //ok | |
| 69 | 85 | } |
| 70 | 86 | |
| 71 | 87 | // Test nextDelays() |
| @@ -85,23 +101,23 @@ | ||
| 85 | 101 | long breakTime = 62; // time until next reconnection attempt |
| 86 | 102 | |
| 87 | 103 | // TODO: Try to sort out variance |
| 88 | - //reconnectionPolicyTest(builder, restartTime, retryTime, breakTime); | |
| 104 | + //reconnectionPolicyTest(restartTime, retryTime, breakTime); | |
| 89 | 105 | } |
| 90 | 106 | |
| 91 | 107 | /* |
| 92 | 108 | * Test the ConstantReconnectionPolicy. |
| 93 | 109 | */ |
| 94 | 110 | @Test(groups = "long") |
| 111 | + @CCMConfig(clusterProvider = "constant") | |
| 95 | 112 | public void constantReconnectionPolicyTest() throws Throwable { |
| 96 | - Cluster.Builder builder = Cluster.builder().withReconnectionPolicy(new ConstantReconnectionPolicy(10 * 1000)); | |
| 97 | 113 | |
| 98 | 114 | // Ensure that ConstantReconnectionPolicy is what we should be testing |
| 99 | - if (!(builder.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ConstantReconnectionPolicy)) { | |
| 115 | + if (!(cluster.getConfiguration().getPolicies().getReconnectionPolicy() instanceof ConstantReconnectionPolicy)) { | |
| 100 | 116 | fail("Set policy does not match retrieved policy."); |
| 101 | 117 | } |
| 102 | 118 | |
| 103 | 119 | // Test basic getters |
| 104 | - ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy) builder.getConfiguration().getPolicies().getReconnectionPolicy(); | |
| 120 | + ConstantReconnectionPolicy reconnectionPolicy = (ConstantReconnectionPolicy) cluster.getConfiguration().getPolicies().getReconnectionPolicy(); | |
| 105 | 121 | assertTrue(reconnectionPolicy.getConstantDelayMs() == 10 * 1000); |
| 106 | 122 | |
| 107 | 123 | // Test erroneous instantiations |
| @@ -109,6 +125,7 @@ | ||
| 109 | 125 | new ConstantReconnectionPolicy(-1); |
| 110 | 126 | fail(); |
| 111 | 127 | } catch (IllegalArgumentException e) { |
| 128 | + //ok | |
| 112 | 129 | } |
| 113 | 130 | |
| 114 | 131 | // Test nextDelays() |
| @@ -125,46 +142,87 @@ | ||
| 125 | 142 | long breakTime = 10; // time until next reconnection attempt |
| 126 | 143 | |
| 127 | 144 | // TODO: Try to sort out variance |
| 128 | - //reconnectionPolicyTest(builder, restartTime, retryTime, breakTime); | |
| 145 | + //reconnectionPolicyTest(restartTime, retryTime, breakTime); | |
| 129 | 146 | } |
| 130 | 147 | |
| 131 | - public void reconnectionPolicyTest(Cluster.Builder builder, long restartTime, long retryTime, long breakTime) throws Throwable { | |
| 132 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); | |
| 133 | - | |
| 148 | + public void reconnectionPolicyTest(long restartTime, long retryTime, long breakTime) throws Throwable { | |
| 149 | + createSchema(1); | |
| 150 | + init(12); | |
| 151 | + query(12); | |
| 152 | + | |
| 153 | + // Ensure a basic test works | |
| 154 | + assertQueried(TestUtils.IP_PREFIX + '1', 12); | |
| 155 | + resetCoordinators(); | |
| 156 | + ccm.forceStop(1); | |
| 157 | + | |
| 158 | + // Start timing and ensure that the node is down | |
| 159 | + long startTime = 0; | |
| 134 | 160 | try { |
| 135 | - createSchema(c.session, 1); | |
| 136 | - init(c, 12); | |
| 137 | - query(c, 12); | |
| 138 | - | |
| 139 | - // Ensure a basic test works | |
| 140 | - assertQueried(CCMBridge.IP_PREFIX + '1', 12); | |
| 161 | + startTime = System.nanoTime() / 1000000000; | |
| 162 | + query(12); | |
| 163 | + fail("Test race condition where node has not shut off quickly enough."); | |
| 164 | + } catch (NoHostAvailableException e) { | |
| 165 | + //ok | |
| 166 | + } | |
| 167 | + | |
| 168 | + long thisTime; | |
| 169 | + boolean restarted = false; | |
| 170 | + while (true) { | |
| 171 | + thisTime = System.nanoTime() / 1000000000; | |
| 172 | + | |
| 173 | + // Restart node at restartTime | |
| 174 | + if (!restarted && thisTime - startTime > restartTime) { | |
| 175 | + ccm.start(1); | |
| 176 | + restarted = true; | |
| 177 | + } | |
| 178 | + | |
| 179 | + // Continue testing queries each second | |
| 180 | + try { | |
| 181 | + query(12); | |
| 182 | + assertQueried(TestUtils.IP_PREFIX + '1', 12); | |
| 183 | + resetCoordinators(); | |
| 184 | + | |
| 185 | + // Ensure the time when the query completes successfully is what was expected | |
| 186 | + assertTrue(retryTime - 2 < thisTime - startTime && thisTime - startTime < retryTime + 2, String.format("Waited %s seconds instead an expected %s seconds wait", thisTime - startTime, retryTime)); | |
| 187 | + } catch (NoHostAvailableException e) { | |
| 188 | + Thread.sleep(1000); | |
| 189 | + continue; | |
| 190 | + } | |
| 191 | + | |
| 192 | + Thread.sleep(breakTime); | |
| 193 | + | |
| 194 | + // The the same query once more, just to be sure | |
| 195 | + query(12); | |
| 196 | + assertQueried(TestUtils.IP_PREFIX + '1', 12); | |
| 141 | 197 | resetCoordinators(); |
| 142 | - c.cassandraCluster.forceStop(1); | |
| 198 | + | |
| 199 | + // Ensure the reconnection times reset | |
| 200 | + ccm.forceStop(1); | |
| 143 | 201 | |
| 144 | 202 | // Start timing and ensure that the node is down |
| 145 | - long startTime = 0; | |
| 203 | + startTime = 0; | |
| 146 | 204 | try { |
| 147 | 205 | startTime = System.nanoTime() / 1000000000; |
| 148 | - query(c, 12); | |
| 206 | + query(12); | |
| 149 | 207 | fail("Test race condition where node has not shut off quickly enough."); |
| 150 | 208 | } catch (NoHostAvailableException e) { |
| 209 | + //ok | |
| 151 | 210 | } |
| 152 | 211 | |
| 153 | - long thisTime; | |
| 154 | - boolean restarted = false; | |
| 212 | + restarted = false; | |
| 155 | 213 | while (true) { |
| 156 | 214 | thisTime = System.nanoTime() / 1000000000; |
| 157 | 215 | |
| 158 | 216 | // Restart node at restartTime |
| 159 | 217 | if (!restarted && thisTime - startTime > restartTime) { |
| 160 | - c.cassandraCluster.start(1); | |
| 218 | + ccm.start(1); | |
| 161 | 219 | restarted = true; |
| 162 | 220 | } |
| 163 | 221 | |
| 164 | 222 | // Continue testing queries each second |
| 165 | 223 | try { |
| 166 | - query(c, 12); | |
| 167 | - assertQueried(CCMBridge.IP_PREFIX + '1', 12); | |
| 224 | + query(12); | |
| 225 | + assertQueried(TestUtils.IP_PREFIX + '1', 12); | |
| 168 | 226 | resetCoordinators(); |
| 169 | 227 | |
| 170 | 228 | // Ensure the time when the query completes successfully is what was expected |
| @@ -173,59 +231,9 @@ | ||
| 173 | 231 | Thread.sleep(1000); |
| 174 | 232 | continue; |
| 175 | 233 | } |
| 176 | - | |
| 177 | - Thread.sleep(breakTime); | |
| 178 | - | |
| 179 | - // The the same query once more, just to be sure | |
| 180 | - query(c, 12); | |
| 181 | - assertQueried(CCMBridge.IP_PREFIX + '1', 12); | |
| 182 | - resetCoordinators(); | |
| 183 | - | |
| 184 | - // Ensure the reconnection times reset | |
| 185 | - c.cassandraCluster.forceStop(1); | |
| 186 | - | |
| 187 | - // Start timing and ensure that the node is down | |
| 188 | - startTime = 0; | |
| 189 | - try { | |
| 190 | - startTime = System.nanoTime() / 1000000000; | |
| 191 | - query(c, 12); | |
| 192 | - fail("Test race condition where node has not shut off quickly enough."); | |
| 193 | - } catch (NoHostAvailableException e) { | |
| 194 | - } | |
| 195 | - | |
| 196 | - restarted = false; | |
| 197 | - while (true) { | |
| 198 | - thisTime = System.nanoTime() / 1000000000; | |
| 199 | - | |
| 200 | - // Restart node at restartTime | |
| 201 | - if (!restarted && thisTime - startTime > restartTime) { | |
| 202 | - c.cassandraCluster.start(1); | |
| 203 | - restarted = true; | |
| 204 | - } | |
| 205 | - | |
| 206 | - // Continue testing queries each second | |
| 207 | - try { | |
| 208 | - query(c, 12); | |
| 209 | - assertQueried(CCMBridge.IP_PREFIX + '1', 12); | |
| 210 | - resetCoordinators(); | |
| 211 | - | |
| 212 | - // Ensure the time when the query completes successfully is what was expected | |
| 213 | - assertTrue(retryTime - 2 < thisTime - startTime && thisTime - startTime < retryTime + 2, String.format("Waited %s seconds instead an expected %s seconds wait", thisTime - startTime, retryTime)); | |
| 214 | - } catch (NoHostAvailableException e) { | |
| 215 | - Thread.sleep(1000); | |
| 216 | - continue; | |
| 217 | - } | |
| 218 | - break; | |
| 219 | - } | |
| 220 | 234 | break; |
| 221 | 235 | } |
| 222 | - | |
| 223 | - } catch (Throwable e) { | |
| 224 | - c.errorOut(); | |
| 225 | - throw e; | |
| 226 | - } finally { | |
| 227 | - resetCoordinators(); | |
| 228 | - c.discard(); | |
| 236 | + break; | |
| 229 | 237 | } |
| 230 | 238 | } |
| 231 | 239 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +181 −224
| @@ -21,6 +21,7 @@ | ||
| 21 | 21 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| 22 | 22 | import com.datastax.driver.core.policies.RoundRobinPolicy; |
| 23 | 23 | import com.google.common.util.concurrent.ListenableFuture; |
| 24 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 24 | 25 | import org.testng.annotations.Test; |
| 25 | 26 | |
| 26 | 27 | import java.io.IOException; |
| @@ -33,267 +34,223 @@ | ||
| 33 | 34 | import java.util.concurrent.atomic.AtomicInteger; |
| 34 | 35 | |
| 35 | 36 | import static com.datastax.driver.core.Assertions.assertThat; |
| 37 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 36 | 38 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 37 | -import static org.assertj.core.api.Assertions.assertThat; | |
| 38 | 39 | import static org.mockito.Mockito.*; |
| 39 | 40 | |
| 40 | 41 | /** |
| 41 | 42 | * Scenarios where a Cluster loses connection to a host and reconnects. |
| 42 | 43 | */ |
| 43 | -public class ReconnectionTest { | |
| 44 | +@CreateCCM(PER_METHOD) | |
| 45 | +public class ReconnectionTest extends CCMTestsSupport { | |
| 44 | 46 | |
| 47 | + private final int reconnectionDelayMillis = 1000; | |
| 48 | + | |
| 49 | + @CCMConfig(dirtiesContext = true, numberOfNodes = 2, createCluster = false) | |
| 45 | 50 | @Test(groups = "long") |
| 46 | 51 | public void should_reconnect_after_full_connectivity_loss() throws InterruptedException { |
| 47 | - CCMBridge ccm = null; | |
| 48 | - Cluster cluster = null; | |
| 49 | - try { | |
| 50 | - ccm = CCMBridge.builder("test").withNodes(2).build(); | |
| 51 | - int reconnectionDelay = 1000; | |
| 52 | - cluster = Cluster.builder() | |
| 53 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 54 | - .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay)) | |
| 55 | - .build(); | |
| 56 | - cluster.connect(); | |
| 57 | - | |
| 58 | - assertThat(cluster).usesControlHost(1); | |
| 59 | - | |
| 60 | - // Stop all nodes. We won't get notifications anymore, so the only mechanism to | |
| 61 | - // reconnect is the background reconnection attempts. | |
| 62 | - ccm.stop(2); | |
| 63 | - ccm.stop(1); | |
| 64 | - | |
| 65 | - ccm.waitForDown(2); | |
| 66 | - ccm.start(2); | |
| 67 | - ccm.waitForUp(2); | |
| 68 | - | |
| 69 | - assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 70 | - | |
| 71 | - // Give the control connection a few moments to reconnect | |
| 72 | - TimeUnit.MILLISECONDS.sleep(reconnectionDelay * 2); | |
| 73 | - assertThat(cluster).usesControlHost(2); | |
| 74 | - } finally { | |
| 75 | - if (cluster != null) | |
| 76 | - cluster.close(); | |
| 77 | - if (ccm != null) | |
| 78 | - ccm.remove(); | |
| 79 | - } | |
| 52 | + Cluster cluster = register(Cluster.builder() | |
| 53 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 54 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 55 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)) | |
| 56 | + .build()); | |
| 57 | + cluster.connect(); | |
| 58 | + | |
| 59 | + assertThat(cluster).usesControlHost(1); | |
| 60 | + | |
| 61 | + // Stop all nodes. We won't get notifications anymore, so the only mechanism to | |
| 62 | + // reconnect is the background reconnection attempts. | |
| 63 | + ccm.stop(2); | |
| 64 | + ccm.stop(1); | |
| 65 | + | |
| 66 | + ccm.waitForDown(2); | |
| 67 | + ccm.start(2); | |
| 68 | + ccm.waitForUp(2); | |
| 69 | + | |
| 70 | + assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 71 | + | |
| 72 | + // Give the control connection a few moments to reconnect | |
| 73 | + TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2); | |
| 74 | + assertThat(cluster).usesControlHost(2); | |
| 80 | 75 | } |
| 81 | 76 | |
| 77 | + @CCMConfig( | |
| 78 | + dirtiesContext = true, | |
| 79 | + config = "authenticator:PasswordAuthenticator", | |
| 80 | + jvmArgs = "-Dcassandra.superuser_setup_delay_ms=0", | |
| 81 | + createCluster = false) | |
| 82 | 82 | @Test(groups = "long") |
| 83 | 83 | public void should_keep_reconnecting_on_authentication_error() throws InterruptedException { |
| 84 | - CCMBridge ccm = null; | |
| 85 | - Cluster cluster = null; | |
| 86 | - try { | |
| 87 | - ccm = CCMBridge.builder("test") | |
| 88 | - .withCassandraConfiguration("authenticator", "PasswordAuthenticator") // default credentials: cassandra / cassandra | |
| 89 | - .notStarted() | |
| 90 | - .build(); | |
| 91 | - ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0"); | |
| 92 | - | |
| 93 | - CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra"); | |
| 94 | - int reconnectionDelayMs = 1000; | |
| 95 | - CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs)); | |
| 96 | - | |
| 97 | - cluster = Cluster.builder() | |
| 98 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 99 | - // Start with the correct auth so that we can initialize the server | |
| 100 | - .withAuthProvider(authProvider) | |
| 101 | - .withReconnectionPolicy(reconnectionPolicy) | |
| 102 | - .build(); | |
| 103 | - | |
| 104 | - cluster.init(); | |
| 105 | - assertThat(cluster).usesControlHost(1); | |
| 106 | - | |
| 107 | - // Stop the server, set wrong credentials and restart | |
| 108 | - ccm.stop(1); | |
| 109 | - ccm.waitForDown(1); | |
| 110 | - authProvider.setPassword("wrongPassword"); | |
| 111 | - ccm.start(1); | |
| 112 | - ccm.waitForUp(1); | |
| 113 | - | |
| 114 | - // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least once | |
| 115 | - // NB: authentication errors show up in the logs | |
| 116 | - int initialCount = authProvider.count.get(); | |
| 117 | - int iterations = 0, maxIterations = 12; // make sure we don't wait indefinitely | |
| 118 | - do { | |
| 119 | - iterations += 1; | |
| 120 | - TimeUnit.SECONDS.sleep(5); | |
| 121 | - } while (iterations < maxIterations && authProvider.count.get() <= initialCount); | |
| 122 | - assertThat(iterations).isLessThan(maxIterations); | |
| 123 | - | |
| 124 | - // Fix the credentials | |
| 125 | - authProvider.setPassword("cassandra"); | |
| 126 | - | |
| 127 | - // The driver should eventually reconnect to the node | |
| 128 | - assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 129 | - } finally { | |
| 130 | - if (cluster != null) | |
| 131 | - cluster.close(); | |
| 132 | - if (ccm != null) | |
| 133 | - ccm.remove(); | |
| 84 | + // For C* 1.2, sleep before attempting to connect as there is a small delay between | |
| 85 | + // user being created. | |
| 86 | + if (ccm.getVersion().getMajor() < 2) { | |
| 87 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 134 | 88 | } |
| 89 | + CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)); | |
| 90 | + CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra"); | |
| 91 | + Cluster cluster = register(Cluster.builder() | |
| 92 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 93 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 94 | + // Start with the correct auth so that we can initialize the server | |
| 95 | + .withAuthProvider(authProvider) | |
| 96 | + .withReconnectionPolicy(reconnectionPolicy) | |
| 97 | + .build()); | |
| 98 | + | |
| 99 | + cluster.init(); | |
| 100 | + assertThat(cluster).usesControlHost(1); | |
| 101 | + | |
| 102 | + // Stop the server, set wrong credentials and restart | |
| 103 | + ccm.stop(1); | |
| 104 | + ccm.waitForDown(1); | |
| 105 | + authProvider.setPassword("wrongPassword"); | |
| 106 | + ccm.start(1); | |
| 107 | + ccm.waitForUp(1); | |
| 108 | + | |
| 109 | + // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least once | |
| 110 | + // NB: authentication errors show up in the logs | |
| 111 | + int initialCount = authProvider.count.get(); | |
| 112 | + int iterations = 0, maxIterations = 12; // make sure we don't wait indefinitely | |
| 113 | + do { | |
| 114 | + iterations += 1; | |
| 115 | + TimeUnit.SECONDS.sleep(5); | |
| 116 | + } while (iterations < maxIterations && authProvider.count.get() <= initialCount); | |
| 117 | + assertThat(iterations).isLessThan(maxIterations); | |
| 118 | + | |
| 119 | + // Fix the credentials | |
| 120 | + authProvider.setPassword("cassandra"); | |
| 121 | + | |
| 122 | + // The driver should eventually reconnect to the node | |
| 123 | + assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 135 | 124 | } |
| 136 | 125 | |
| 126 | + @CCMConfig(dirtiesContext = true, numberOfNodes = 2, createCluster = false) | |
| 137 | 127 | @Test(groups = "long") |
| 138 | 128 | public void should_cancel_reconnection_attempts() throws InterruptedException { |
| 139 | - CCMBridge ccm = null; | |
| 140 | - Cluster cluster = null; | |
| 141 | - | |
| 142 | - long reconnectionDelayMillis = 1000; | |
| 129 | + // Stop a node and cancel the reconnection attempts to it | |
| 143 | 130 | CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)); |
| 144 | 131 | |
| 145 | - try { | |
| 146 | - ccm = CCMBridge.builder("test").withNodes(2).build(); | |
| 147 | - cluster = Cluster.builder() | |
| 148 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 149 | - .withReconnectionPolicy(reconnectionPolicy) | |
| 150 | - .build(); | |
| 151 | - cluster.connect(); | |
| 152 | - | |
| 153 | - // Stop a node and cancel the reconnection attempts to it | |
| 154 | - ccm.stop(2); | |
| 155 | - Host host2 = TestUtils.findHost(cluster, 2); | |
| 156 | - host2.getReconnectionAttemptFuture().cancel(false); | |
| 157 | - | |
| 158 | - // The reconnection count should not vary over time anymore | |
| 159 | - int initialCount = reconnectionPolicy.count.get(); | |
| 160 | - TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2); | |
| 161 | - assertThat(reconnectionPolicy.count.get()).isEqualTo(initialCount); | |
| 162 | - | |
| 163 | - // Restart the node, which will trigger an UP notification | |
| 164 | - ccm.start(2); | |
| 165 | - ccm.waitForUp(2); | |
| 166 | - | |
| 167 | - // The driver should now see the node as UP again | |
| 168 | - assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 169 | - | |
| 170 | - } finally { | |
| 171 | - if (cluster != null) | |
| 172 | - cluster.close(); | |
| 173 | - if (ccm != null) | |
| 174 | - ccm.remove(); | |
| 175 | - } | |
| 132 | + Cluster cluster = register(Cluster.builder() | |
| 133 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 134 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 135 | + .withReconnectionPolicy(reconnectionPolicy).build()); | |
| 136 | + cluster.connect(); | |
| 137 | + | |
| 138 | + // Stop a node and cancel the reconnection attempts to it | |
| 139 | + ccm.stop(2); | |
| 140 | + Host host2 = TestUtils.findHost(cluster, 2); | |
| 141 | + host2.getReconnectionAttemptFuture().cancel(false); | |
| 142 | + | |
| 143 | + // The reconnection count should not vary over time anymore | |
| 144 | + int initialCount = reconnectionPolicy.count.get(); | |
| 145 | + TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2); | |
| 146 | + assertThat(reconnectionPolicy.count.get()).isEqualTo(initialCount); | |
| 147 | + | |
| 148 | + // Restart the node, which will trigger an UP notification | |
| 149 | + ccm.start(2); | |
| 150 | + ccm.waitForUp(2); | |
| 151 | + | |
| 152 | + // The driver should now see the node as UP again | |
| 153 | + assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 176 | 154 | } |
| 177 | 155 | |
| 156 | + @CCMConfig(dirtiesContext = true, createCluster = false) | |
| 178 | 157 | @Test(groups = "long") |
| 179 | 158 | public void should_trigger_one_time_reconnect() throws InterruptedException, IOException { |
| 180 | - CCMBridge ccm = null; | |
| 181 | - Cluster cluster = null; | |
| 182 | - | |
| 183 | - long reconnectionDelayMillis = 1000; | |
| 184 | 159 | TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy()); |
| 185 | - | |
| 186 | - try { | |
| 187 | - ccm = CCMBridge.builder("test").withNodes(1).build(); | |
| 188 | - cluster = Cluster.builder() | |
| 189 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 190 | - .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 191 | - .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)) | |
| 192 | - .build(); | |
| 193 | - cluster.connect(); | |
| 194 | - | |
| 195 | - // Tweak the LBP so that the control connection never reconnects, otherwise | |
| 196 | - // it would interfere with the rest of the test (this is a bit of a hack) | |
| 197 | - loadBalancingPolicy.returnEmptyQueryPlan = true; | |
| 198 | - | |
| 199 | - // Stop the node, ignore it and cancel reconnection attempts to it | |
| 200 | - ccm.stop(1); | |
| 201 | - ccm.waitForDown(1); | |
| 202 | - assertThat(cluster).host(1).goesDownWithin(20, SECONDS); | |
| 203 | - Host host1 = TestUtils.findHost(cluster, 1); | |
| 204 | - loadBalancingPolicy.setDistance(TestUtils.findHost(cluster, 1), HostDistance.IGNORED); | |
| 205 | - ListenableFuture<?> reconnectionAttemptFuture = host1.getReconnectionAttemptFuture(); | |
| 206 | - if (reconnectionAttemptFuture != null) | |
| 207 | - reconnectionAttemptFuture.cancel(false); | |
| 208 | - | |
| 209 | - // Trigger a one-time reconnection attempt (this will fail) | |
| 210 | - host1.tryReconnectOnce(); | |
| 211 | - | |
| 212 | - // Wait for a few reconnection cycles before checking | |
| 213 | - TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2); | |
| 214 | - assertThat(cluster).host(1).hasState(State.DOWN); | |
| 215 | - | |
| 216 | - // Restart the node (this will not trigger an UP notification thanks to our | |
| 217 | - // hack to disable the control connection reconnects). The host should stay | |
| 218 | - // down for the driver. | |
| 219 | - ccm.start(1); | |
| 220 | - ccm.waitForUp(1); | |
| 221 | - assertThat(cluster).host(1).hasState(State.DOWN); | |
| 222 | - | |
| 223 | - TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS); | |
| 224 | - assertThat(cluster).host(1).hasState(State.DOWN); | |
| 225 | - | |
| 226 | - // Trigger another one-time reconnection attempt (this will succeed). The | |
| 227 | - // host should be back up. | |
| 228 | - host1.tryReconnectOnce(); | |
| 229 | - assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 230 | - } finally { | |
| 231 | - if (cluster != null) | |
| 232 | - cluster.close(); | |
| 233 | - if (ccm != null) | |
| 234 | - ccm.remove(); | |
| 235 | - } | |
| 160 | + Cluster cluster = register(Cluster.builder() | |
| 161 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 162 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 163 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 164 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)) | |
| 165 | + .build()); | |
| 166 | + cluster.connect(); | |
| 167 | + | |
| 168 | + // Tweak the LBP so that the control connection never reconnects, otherwise | |
| 169 | + // it would interfere with the rest of the test (this is a bit of a hack) | |
| 170 | + loadBalancingPolicy.returnEmptyQueryPlan = true; | |
| 171 | + | |
| 172 | + // Stop the node, ignore it and cancel reconnection attempts to it | |
| 173 | + ccm.stop(1); | |
| 174 | + ccm.waitForDown(1); | |
| 175 | + assertThat(cluster).host(1).goesDownWithin(20, SECONDS); | |
| 176 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 177 | + loadBalancingPolicy.setDistance(TestUtils.findHost(cluster, 1), HostDistance.IGNORED); | |
| 178 | + ListenableFuture<?> reconnectionAttemptFuture = host1.getReconnectionAttemptFuture(); | |
| 179 | + if (reconnectionAttemptFuture != null) | |
| 180 | + reconnectionAttemptFuture.cancel(false); | |
| 181 | + | |
| 182 | + // Trigger a one-time reconnection attempt (this will fail) | |
| 183 | + host1.tryReconnectOnce(); | |
| 184 | + | |
| 185 | + // Wait for a few reconnection cycles before checking | |
| 186 | + TimeUnit.MILLISECONDS.sleep(reconnectionDelayMillis * 2); | |
| 187 | + assertThat(cluster).host(1).hasState(State.DOWN); | |
| 188 | + | |
| 189 | + // Restart the node (this will not trigger an UP notification thanks to our | |
| 190 | + // hack to disable the control connection reconnects). The host should stay | |
| 191 | + // down for the driver. | |
| 192 | + ccm.start(1); | |
| 193 | + ccm.waitForUp(1); | |
| 194 | + assertThat(cluster).host(1).hasState(State.DOWN); | |
| 195 | + | |
| 196 | + TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS); | |
| 197 | + assertThat(cluster).host(1).hasState(State.DOWN); | |
| 198 | + | |
| 199 | + // Trigger another one-time reconnection attempt (this will succeed). The | |
| 200 | + // host should be back up. | |
| 201 | + host1.tryReconnectOnce(); | |
| 202 | + assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 236 | 203 | } |
| 237 | 204 | |
| 238 | 205 | /** |
| 239 | 206 | * The connection established by a successful reconnection attempt should be reused in one of the |
| 240 | 207 | * connection pools (JAVA-505). |
| 241 | 208 | */ |
| 209 | + @CCMConfig(dirtiesContext = true, createCluster = false) | |
| 242 | 210 | @Test(groups = "long") |
| 243 | 211 | public void should_use_connection_from_reconnection_in_pool() { |
| 244 | - CCMBridge ccm = null; | |
| 245 | - Cluster cluster = null; | |
| 246 | - | |
| 247 | 212 | TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy()); |
| 248 | 213 | |
| 249 | 214 | // Spy SocketOptions.getKeepAlive to count how many connections were instantiated. |
| 250 | 215 | SocketOptions socketOptions = spy(new SocketOptions()); |
| 251 | - | |
| 252 | - try { | |
| 253 | - ccm = CCMBridge.builder("test").withNodes(1).build(); | |
| 254 | - cluster = Cluster.builder() | |
| 255 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 256 | - .withReconnectionPolicy(new ConstantReconnectionPolicy(5000)) | |
| 257 | - .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 258 | - .withSocketOptions(socketOptions) | |
| 259 | - .withProtocolVersion(TestUtils.getDesiredProtocolVersion()) | |
| 260 | - .build(); | |
| 261 | - // Create two sessions to have multiple pools | |
| 262 | - cluster.connect(); | |
| 263 | - cluster.connect(); | |
| 264 | - | |
| 265 | - int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster); | |
| 266 | - | |
| 267 | - // Right after init, 1 connection has been opened by the control connection, and the core size for each pool. | |
| 268 | - verify(socketOptions, times(1 + corePoolSize * 2)).getKeepAlive(); | |
| 269 | - | |
| 270 | - // Tweak the LBP so that the control connection never reconnects. This makes it easier | |
| 271 | - // to reason about the number of connection attempts. | |
| 272 | - loadBalancingPolicy.returnEmptyQueryPlan = true; | |
| 273 | - | |
| 274 | - // Stop the node and cancel the reconnection attempts to it | |
| 275 | - ccm.stop(1); | |
| 276 | - ccm.waitForDown(1); | |
| 277 | - assertThat(cluster).host(1).goesDownWithin(20, SECONDS); | |
| 278 | - Host host1 = TestUtils.findHost(cluster, 1); | |
| 279 | - host1.getReconnectionAttemptFuture().cancel(false); | |
| 280 | - | |
| 281 | - ccm.start(1); | |
| 282 | - ccm.waitForUp(1); | |
| 283 | - | |
| 284 | - // Reset the spy and count the number of connections attempts for 1 reconnect | |
| 285 | - reset(socketOptions); | |
| 286 | - host1.tryReconnectOnce(); | |
| 287 | - assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 288 | - // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4 | |
| 289 | - // but the one from the reconnection attempt gets reused). | |
| 290 | - verify(socketOptions, times(corePoolSize * 2)).getKeepAlive(); | |
| 291 | - } finally { | |
| 292 | - if (cluster != null) | |
| 293 | - cluster.close(); | |
| 294 | - if (ccm != null) | |
| 295 | - ccm.remove(); | |
| 296 | - } | |
| 216 | + Cluster cluster = register(Cluster.builder() | |
| 217 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 218 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 219 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(5000)) | |
| 220 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 221 | + .withSocketOptions(socketOptions) | |
| 222 | + .withProtocolVersion(TestUtils.getDesiredProtocolVersion()) | |
| 223 | + .build()); | |
| 224 | + // Create two sessions to have multiple pools | |
| 225 | + cluster.connect(); | |
| 226 | + cluster.connect(); | |
| 227 | + | |
| 228 | + int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster); | |
| 229 | + | |
| 230 | + // Right after init, 1 connection has been opened by the control connection, and the core size for each pool. | |
| 231 | + verify(socketOptions, times(1 + corePoolSize * 2)).getKeepAlive(); | |
| 232 | + | |
| 233 | + // Tweak the LBP so that the control connection never reconnects. This makes it easier | |
| 234 | + // to reason about the number of connection attempts. | |
| 235 | + loadBalancingPolicy.returnEmptyQueryPlan = true; | |
| 236 | + | |
| 237 | + // Stop the node and cancel the reconnection attempts to it | |
| 238 | + ccm.stop(1); | |
| 239 | + ccm.waitForDown(1); | |
| 240 | + assertThat(cluster).host(1).goesDownWithin(20, SECONDS); | |
| 241 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 242 | + host1.getReconnectionAttemptFuture().cancel(false); | |
| 243 | + | |
| 244 | + ccm.start(1); | |
| 245 | + ccm.waitForUp(1); | |
| 246 | + | |
| 247 | + // Reset the spy and count the number of connections attempts for 1 reconnect | |
| 248 | + reset(socketOptions); | |
| 249 | + host1.tryReconnectOnce(); | |
| 250 | + assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS * 2, SECONDS); | |
| 251 | + // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4 | |
| 252 | + // but the one from the reconnection attempt gets reused). | |
| 253 | + verify(socketOptions, times(corePoolSize * 2)).getKeepAlive(); | |
| 297 | 254 | } |
| 298 | 255 | |
| 299 | 256 | /** |
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +67 −77
| @@ -25,88 +25,78 @@ | ||
| 25 | 25 | import static com.datastax.driver.core.Assertions.assertThat; |
| 26 | 26 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 27 | 27 | |
| 28 | -public class RefreshConnectedHostTest { | |
| 28 | +@CCMConfig( | |
| 29 | + dirtiesContext = true, | |
| 30 | + numberOfNodes = 2, | |
| 31 | + createCluster = false | |
| 32 | +) | |
| 33 | +public class RefreshConnectedHostTest extends CCMTestsSupport { | |
| 29 | 34 | |
| 30 | 35 | /** |
| 31 | 36 | * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy. |
| 32 | 37 | */ |
| 33 | 38 | @Test(groups = "long") |
| 34 | 39 | public void should_refresh_single_connected_host() { |
| 35 | - CCMBridge ccm = null; | |
| 36 | - Cluster cluster = null; | |
| 37 | - try { | |
| 38 | - // This will make the driver use at most 2 hosts, the others will be ignored | |
| 39 | - LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1); | |
| 40 | - | |
| 41 | - // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use | |
| 42 | - ccm = CCMBridge.builder("test").withNodes(3).notStarted().build(); | |
| 43 | - ccm.start(1); | |
| 44 | - ccm.start(2); | |
| 45 | - ccm.waitForUp(1); | |
| 46 | - ccm.waitForUp(2); | |
| 47 | - | |
| 48 | - PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions()); | |
| 49 | - cluster = Cluster.builder() | |
| 50 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 51 | - .withPoolingOptions(poolingOptions) | |
| 52 | - .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 53 | - .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) | |
| 54 | - .withQueryOptions(TestUtils.nonDebouncingQueryOptions()) | |
| 55 | - .build(); | |
| 56 | - | |
| 57 | - Session session = cluster.connect(); | |
| 58 | - | |
| 59 | - assertThat(cluster).usesControlHost(1); | |
| 60 | - assertThat(cluster).host(1) | |
| 61 | - .hasState(State.UP) | |
| 62 | - .isAtDistance(HostDistance.LOCAL); | |
| 63 | - // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line | |
| 64 | - // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up | |
| 65 | - assertThat(cluster).host(2) | |
| 66 | - .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS) | |
| 67 | - .isAtDistance(HostDistance.LOCAL); | |
| 68 | - | |
| 69 | - // Bring host 3 up, its presence should be acknowledged but it should be ignored | |
| 70 | - ccm.start(3); | |
| 71 | - ccm.waitForUp(3); | |
| 72 | - | |
| 73 | - assertThat(cluster).host(1) | |
| 74 | - .hasState(State.UP) | |
| 75 | - .isAtDistance(HostDistance.LOCAL); | |
| 76 | - assertThat(cluster).host(2) | |
| 77 | - .hasState(State.UP) | |
| 78 | - .isAtDistance(HostDistance.LOCAL); | |
| 79 | - | |
| 80 | - // Ensure that the host is added to the Cluster. | |
| 81 | - assertThat(cluster).host(3) | |
| 82 | - .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS) | |
| 83 | - .isAtDistance(HostDistance.IGNORED); | |
| 84 | - assertThat(session).hasNoPoolFor(3); | |
| 85 | - | |
| 86 | - // Kill host 2, host 3 should take its place | |
| 87 | - ccm.stop(2); | |
| 88 | - TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster); | |
| 89 | - | |
| 90 | - assertThat(cluster).host(1) | |
| 91 | - .hasState(State.UP) | |
| 92 | - .isAtDistance(HostDistance.LOCAL); | |
| 93 | - assertThat(cluster).host(2) | |
| 94 | - .hasState(State.DOWN); | |
| 95 | - assertThat(cluster).host(3) | |
| 96 | - .hasState(State.UP) | |
| 97 | - .isAtDistance(HostDistance.LOCAL); | |
| 98 | - assertThat(session).hasPoolFor(3); | |
| 99 | - | |
| 100 | - // This is when refreshConnectedHost should have been invoked, it triggers pool creation when | |
| 101 | - // we switch the node from IGNORED to UP: | |
| 102 | - Mockito.verify(poolingOptions) | |
| 103 | - .refreshConnectedHost(TestUtils.findHost(cluster, 3)); | |
| 104 | - | |
| 105 | - } finally { | |
| 106 | - if (cluster != null) | |
| 107 | - cluster.close(); | |
| 108 | - if (ccm != null) | |
| 109 | - ccm.remove(); | |
| 110 | - } | |
| 40 | + // This will make the driver use at most 2 hosts, the others will be ignored | |
| 41 | + LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1); | |
| 42 | + | |
| 43 | + PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions()); | |
| 44 | + cluster = register(Cluster.builder() | |
| 45 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 46 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 47 | + .withPoolingOptions(poolingOptions) | |
| 48 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 49 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) | |
| 50 | + .withQueryOptions(TestUtils.nonDebouncingQueryOptions()) | |
| 51 | + .build()); | |
| 52 | + | |
| 53 | + Session session = cluster.connect(); | |
| 54 | + | |
| 55 | + assertThat(cluster).usesControlHost(1); | |
| 56 | + assertThat(cluster).host(1) | |
| 57 | + .hasState(State.UP) | |
| 58 | + .isAtDistance(HostDistance.LOCAL); | |
| 59 | + // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line | |
| 60 | + // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up | |
| 61 | + assertThat(cluster).host(2) | |
| 62 | + .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS) | |
| 63 | + .isAtDistance(HostDistance.LOCAL); | |
| 64 | + | |
| 65 | + // Add and bring host 3 up, its presence should be acknowledged but it should be ignored | |
| 66 | + ccm.add(3); | |
| 67 | + ccm.start(3); | |
| 68 | + ccm.waitForUp(3); | |
| 69 | + | |
| 70 | + assertThat(cluster).host(1) | |
| 71 | + .hasState(State.UP) | |
| 72 | + .isAtDistance(HostDistance.LOCAL); | |
| 73 | + assertThat(cluster).host(2) | |
| 74 | + .hasState(State.UP) | |
| 75 | + .isAtDistance(HostDistance.LOCAL); | |
| 76 | + | |
| 77 | + // Ensure that the host is added to the Cluster. | |
| 78 | + assertThat(cluster).host(3) | |
| 79 | + .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS + 1, SECONDS) | |
| 80 | + .isAtDistance(HostDistance.IGNORED); | |
| 81 | + assertThat(session).hasNoPoolFor(3); | |
| 82 | + | |
| 83 | + // Kill host 2, host 3 should take its place | |
| 84 | + ccm.stop(2); | |
| 85 | + TestUtils.waitFor(TestUtils.ipOfNode(3), cluster); | |
| 86 | + | |
| 87 | + assertThat(cluster).host(1) | |
| 88 | + .hasState(State.UP) | |
| 89 | + .isAtDistance(HostDistance.LOCAL); | |
| 90 | + assertThat(cluster).host(2) | |
| 91 | + .hasState(State.DOWN); | |
| 92 | + assertThat(cluster).host(3) | |
| 93 | + .hasState(State.UP) | |
| 94 | + .isAtDistance(HostDistance.LOCAL); | |
| 95 | + assertThat(session).hasPoolFor(3); | |
| 96 | + | |
| 97 | + // This is when refreshConnectedHost should have been invoked, it triggers pool creation when | |
| 98 | + // we switch the node from IGNORED to UP: | |
| 99 | + Mockito.verify(poolingOptions) | |
| 100 | + .refreshConnectedHost(TestUtils.findHost(cluster, 3)); | |
| 111 | 101 | } |
| 112 | 102 | } |
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +3 −1
| @@ -43,7 +43,9 @@ | ||
| 43 | 43 | .build() |
| 44 | 44 | ); |
| 45 | 45 | |
| 46 | - cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(scassandra.getBinaryPort()) | |
| 46 | + cluster = Cluster.builder() | |
| 47 | + .addContactPoint(TestUtils.ipOfNode(1)) | |
| 48 | + .withPort(scassandra.getBinaryPort()) | |
| 47 | 49 | .withPoolingOptions(new PoolingOptions() |
| 48 | 50 | .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) |
| 49 | 51 | .setMaxConnectionsPerHost(HostDistance.LOCAL, 1) |
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +13 −6
| @@ -21,12 +21,9 @@ | ||
| 21 | 21 | |
| 22 | 22 | import static com.datastax.driver.core.CCMBridge.*; |
| 23 | 23 | |
| 24 | +@CCMConfig(auth = true) | |
| 24 | 25 | public class SSLAuthenticatedEncryptionTest extends SSLTestBase { |
| 25 | 26 | |
| 26 | - public SSLAuthenticatedEncryptionTest() { | |
| 27 | - super(true); | |
| 28 | - } | |
| 29 | - | |
| 30 | 27 | /** |
| 31 | 28 | * <p> |
| 32 | 29 | * Validates that an SSL connection can be established with client auth if the target |
| @@ -72,7 +69,17 @@ | ||
| 72 | 69 | System.setProperty("javax.net.ssl.keyStorePassword", DEFAULT_CLIENT_KEYSTORE_PASSWORD); |
| 73 | 70 | System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath()); |
| 74 | 71 | System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD); |
| 75 | - | |
| 76 | - connectWithSSL(); | |
| 72 | + try { | |
| 73 | + connectWithSSL(); | |
| 74 | + } finally { | |
| 75 | + try { | |
| 76 | + System.clearProperty("javax.net.ssl.keyStore"); | |
| 77 | + System.clearProperty("javax.net.ssl.keyStorePassword"); | |
| 78 | + System.clearProperty("javax.net.ssl.trustStore"); | |
| 79 | + System.clearProperty("javax.net.ssl.trustStorePassword"); | |
| 80 | + } catch (SecurityException e) { | |
| 81 | + // ok | |
| 82 | + } | |
| 83 | + } | |
| 77 | 84 | } |
| 78 | 85 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +26 −31
| @@ -24,12 +24,9 @@ | ||
| 24 | 24 | import static com.datastax.driver.core.Assertions.assertThat; |
| 25 | 25 | import static com.datastax.driver.core.CCMBridge.*; |
| 26 | 26 | |
| 27 | +@CCMConfig(auth = false) | |
| 27 | 28 | public class SSLEncryptionTest extends SSLTestBase { |
| 28 | 29 | |
| 29 | - public SSLEncryptionTest() { | |
| 30 | - super(false); | |
| 31 | - } | |
| 32 | - | |
| 33 | 30 | /** |
| 34 | 31 | * <p> |
| 35 | 32 | * Validates that an SSL connection can be established without client auth if the target |
| @@ -74,17 +71,11 @@ | ||
| 74 | 71 | */ |
| 75 | 72 | @Test(groups = "short", expectedExceptions = {NoHostAvailableException.class}) |
| 76 | 73 | public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception { |
| 77 | - Cluster cluster = null; | |
| 78 | - try { | |
| 79 | - cluster = Cluster.builder() | |
| 80 | - .addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 81 | - .build(); | |
| 82 | - | |
| 83 | - cluster.connect(); | |
| 84 | - } finally { | |
| 85 | - if (cluster != null) | |
| 86 | - cluster.close(); | |
| 87 | - } | |
| 74 | + Cluster cluster = register(Cluster.builder() | |
| 75 | + .addContactPointsWithPorts(this.getInitialContactPoints()) | |
| 76 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 77 | + .build()); | |
| 78 | + cluster.connect(); | |
| 88 | 79 | } |
| 89 | 80 | |
| 90 | 81 | /** |
| @@ -96,25 +87,21 @@ | ||
| 96 | 87 | * @test_category connection:ssl |
| 97 | 88 | * @expected_result Connection is re-established within a sufficient amount of time after a node comes back online. |
| 98 | 89 | */ |
| 90 | + @CCMConfig(dirtiesContext = true) | |
| 99 | 91 | @Test(groups = "long") |
| 100 | 92 | public void should_reconnect_with_ssl_on_node_up() throws Exception { |
| 101 | - Cluster cluster = null; | |
| 102 | - try { | |
| 103 | - cluster = Cluster.builder() | |
| 104 | - .addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 105 | - .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH))) | |
| 106 | - .build(); | |
| 93 | + Cluster cluster = register(Cluster.builder() | |
| 94 | + .addContactPointsWithPorts(this.getInitialContactPoints()) | |
| 95 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 96 | + .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH))) | |
| 97 | + .build()); | |
| 107 | 98 | |
| 108 | - cluster.connect(); | |
| 99 | + cluster.connect(); | |
| 109 | 100 | |
| 110 | - ccm.stop(1); | |
| 111 | - ccm.start(1); | |
| 101 | + ccm.stop(1); | |
| 102 | + ccm.start(1); | |
| 112 | 103 | |
| 113 | - assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS); | |
| 114 | - } finally { | |
| 115 | - if (cluster != null) | |
| 116 | - cluster.close(); | |
| 117 | - } | |
| 104 | + assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS); | |
| 118 | 105 | } |
| 119 | 106 | |
| 120 | 107 | /** |
| @@ -129,7 +116,15 @@ | ||
| 129 | 116 | public void should_use_system_properties_with_default_ssl_options() throws Exception { |
| 130 | 117 | System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath()); |
| 131 | 118 | System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD); |
| 132 | - | |
| 133 | - connectWithSSL(); | |
| 119 | + try { | |
| 120 | + connectWithSSL(); | |
| 121 | + } finally { | |
| 122 | + try { | |
| 123 | + System.clearProperty("javax.net.ssl.trustStore"); | |
| 124 | + System.clearProperty("javax.net.ssl.trustStorePassword"); | |
| 125 | + } catch (SecurityException e) { | |
| 126 | + // ok | |
| 127 | + } | |
| 128 | + } | |
| 134 | 129 | } |
| 135 | 130 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +14 −47
| @@ -16,8 +16,6 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.google.common.base.Optional; |
| 19 | -import org.testng.annotations.AfterClass; | |
| 20 | -import org.testng.annotations.BeforeClass; | |
| 21 | 19 | |
| 22 | 20 | import javax.net.ssl.KeyManagerFactory; |
| 23 | 21 | import javax.net.ssl.SSLContext; |
| @@ -28,27 +26,8 @@ | ||
| 28 | 26 | import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD; |
| 29 | 27 | import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD; |
| 30 | 28 | |
| 31 | -public abstract class SSLTestBase { | |
| 32 | - | |
| 33 | - private final boolean requireClientAuth; | |
| 34 | - | |
| 35 | - protected CCMBridge ccm; | |
| 36 | - | |
| 37 | - public SSLTestBase(boolean requireClientAuth) { | |
| 38 | - this.requireClientAuth = requireClientAuth; | |
| 39 | - } | |
| 40 | - | |
| 41 | - @BeforeClass(groups = {"isolated", "short", "long"}) | |
| 42 | - public void beforeClass() { | |
| 43 | - ccm = CCMBridge.builder("test") | |
| 44 | - .withSSL(requireClientAuth) | |
| 45 | - .build(); | |
| 46 | - } | |
| 47 | - | |
| 48 | - @AfterClass(groups = {"isolated", "short", "long"}) | |
| 49 | - public void afterClass() { | |
| 50 | - ccm.remove(); | |
| 51 | - } | |
| 29 | +@CCMConfig(ssl = true, createCluster = false) | |
| 30 | +public abstract class SSLTestBase extends CCMTestsSupport { | |
| 52 | 31 | |
| 53 | 32 | /** |
| 54 | 33 | * <p> |
| @@ -61,18 +40,12 @@ | ||
| 61 | 40 | * raised here if connection cannot be established. |
| 62 | 41 | */ |
| 63 | 42 | protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception { |
| 64 | - Cluster cluster = null; | |
| 65 | - try { | |
| 66 | - cluster = Cluster.builder() | |
| 67 | - .addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 68 | - .withSSL(sslOptions) | |
| 69 | - .build(); | |
| 70 | - | |
| 71 | - cluster.connect(); | |
| 72 | - } finally { | |
| 73 | - if (cluster != null) | |
| 74 | - cluster.close(); | |
| 75 | - } | |
| 43 | + Cluster cluster = register(Cluster.builder() | |
| 44 | + .addContactPointsWithPorts(this.getInitialContactPoints()) | |
| 45 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 46 | + .withSSL(sslOptions) | |
| 47 | + .build()); | |
| 48 | + cluster.connect(); | |
| 76 | 49 | } |
| 77 | 50 | |
| 78 | 51 | /** |
| @@ -85,18 +58,12 @@ | ||
| 85 | 58 | * raised here if connection cannot be established. |
| 86 | 59 | */ |
| 87 | 60 | protected void connectWithSSL() throws Exception { |
| 88 | - Cluster cluster = null; | |
| 89 | - try { | |
| 90 | - cluster = Cluster.builder() | |
| 91 | - .addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 92 | - .withSSL() | |
| 93 | - .build(); | |
| 94 | - | |
| 95 | - cluster.connect(); | |
| 96 | - } finally { | |
| 97 | - if (cluster != null) | |
| 98 | - cluster.close(); | |
| 99 | - } | |
| 61 | + Cluster cluster = register(Cluster.builder() | |
| 62 | + .addContactPointsWithPorts(this.getInitialContactPoints()) | |
| 63 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 64 | + .withSSL() | |
| 65 | + .build()); | |
| 66 | + cluster.connect(); | |
| 100 | 67 | } |
| 101 | 68 | |
| 102 | 69 | /** |
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraCluster.java +43 −13
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.beust.jcommander.internal.Lists; |
| 19 | 19 | import com.beust.jcommander.internal.Maps; |
| 20 | +import com.datastax.driver.core.policies.AddressTranslater; | |
| 20 | 21 | import com.google.common.collect.ImmutableList; |
| 21 | 22 | import com.google.common.collect.ImmutableMap; |
| 22 | 23 | import com.google.common.collect.ImmutableSet; |
| @@ -27,6 +28,8 @@ | ||
| 27 | 28 | import org.slf4j.Logger; |
| 28 | 29 | import org.slf4j.LoggerFactory; |
| 29 | 30 | |
| 31 | +import java.net.InetAddress; | |
| 32 | +import java.net.InetSocketAddress; | |
| 30 | 33 | import java.util.List; |
| 31 | 34 | import java.util.Map; |
| 32 | 35 | import java.util.TreeSet; |
| @@ -45,18 +48,22 @@ | ||
| 45 | 48 | |
| 46 | 49 | private final String ipPrefix; |
| 47 | 50 | |
| 51 | + private final int binaryPort; | |
| 52 | + | |
| 48 | 53 | private final List<Scassandra> instances; |
| 49 | 54 | |
| 50 | 55 | private final Map<Integer, List<Scassandra>> dcNodeMap; |
| 51 | 56 | |
| 52 | - private final List<Map<String, ? extends Object>> keyspaceRows; | |
| 57 | + private final List<Map<String, ?>> keyspaceRows; | |
| 58 | + | |
| 53 | 59 | |
| 54 | 60 | private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos; |
| 55 | 61 | |
| 56 | 62 | ScassandraCluster(Integer[] nodes, String ipPrefix, int binaryPort, int adminPort, |
| 57 | - List<Map<String, ? extends Object>> keyspaceRows, | |
| 63 | + List<Map<String, ?>> keyspaceRows, | |
| 58 | 64 | Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos) { |
| 59 | 65 | this.ipPrefix = ipPrefix; |
| 66 | + this.binaryPort = binaryPort; | |
| 60 | 67 | this.forcedPeerInfos = forcedPeerInfos; |
| 61 | 68 | |
| 62 | 69 | int node = 1; |
| @@ -85,10 +92,6 @@ | ||
| 85 | 92 | return instances; |
| 86 | 93 | } |
| 87 | 94 | |
| 88 | - public String address(int node) { | |
| 89 | - return ipPrefix + node; | |
| 90 | - } | |
| 91 | - | |
| 92 | 95 | public Scassandra node(int dc, int node) { |
| 93 | 96 | return dcNodeMap.get(dc).get(node - 1); |
| 94 | 97 | } |
| @@ -112,16 +115,43 @@ | ||
| 112 | 115 | return -1; |
| 113 | 116 | } |
| 114 | 117 | |
| 115 | - public String address(int dc, int node) { | |
| 118 | + public InetSocketAddress address(int node) { | |
| 119 | + return new InetSocketAddress(ipPrefix + node, binaryPort); | |
| 120 | + } | |
| 121 | + | |
| 122 | + public InetSocketAddress address(int dc, int node) { | |
| 116 | 123 | // TODO: Scassandra should be updated to include address to avoid O(n) lookup. |
| 117 | 124 | int ipSuffix = ipSuffix(dc, node); |
| 118 | - return ipSuffix == -1 ? null : ipPrefix + ipSuffix; | |
| 125 | + if (ipSuffix == -1) | |
| 126 | + return null; | |
| 127 | + return new InetSocketAddress(ipPrefix + ipSuffix, binaryPort); | |
| 128 | + } | |
| 129 | + | |
| 130 | + /** | |
| 131 | + * Returns an {@link AddressTranslater} to use when tests must manually create | |
| 132 | + * {@link Cluster} instances. | |
| 133 | + * <p/> | |
| 134 | + * This translator is necessary because hosts create with this class do not use standard ports. | |
| 135 | + * <p/> | |
| 136 | + * This method should not be called before the test has started, nor after the test is finished. | |
| 137 | + * | |
| 138 | + * @return an {@link AddressTranslater} to use when tests must manually create | |
| 139 | + * {@link Cluster} instances. | |
| 140 | + */ | |
| 141 | + public AddressTranslater addressTranslator() { | |
| 142 | + return new AddressTranslater() { | |
| 143 | + @Override | |
| 144 | + public InetSocketAddress translate(InetSocketAddress address) { | |
| 145 | + return new InetSocketAddress(address.getAddress(), binaryPort); | |
| 146 | + } | |
| 147 | + }; | |
| 119 | 148 | } |
| 120 | 149 | |
| 150 | + | |
| 121 | 151 | public Host host(Cluster cluster, int dc, int node) { |
| 122 | - String address = address(dc, node); | |
| 152 | + InetAddress address = address(dc, node).getAddress(); | |
| 123 | 153 | for (Host host : cluster.getMetadata().getAllHosts()) { |
| 124 | - if (host.getAddress().getHostAddress().equals(address)) { | |
| 154 | + if (host.getAddress().equals(address)) { | |
| 125 | 155 | return host; |
| 126 | 156 | } |
| 127 | 157 | } |
| @@ -441,8 +471,8 @@ | ||
| 441 | 471 | public static class ScassandraClusterBuilder { |
| 442 | 472 | |
| 443 | 473 | private Integer nodes[] = {1}; |
| 444 | - private String ipPrefix = CCMBridge.IP_PREFIX; | |
| 445 | - private final List<Map<String, ? extends Object>> keyspaceRows = Lists.newArrayList(); | |
| 474 | + private String ipPrefix = TestUtils.IP_PREFIX; | |
| 475 | + private final List<Map<String, ?>> keyspaceRows = Lists.newArrayList(); | |
| 446 | 476 | private final Map<Integer, Map<Integer, Map<String, Object>>> forcedPeerInfos = Maps.newHashMap(); |
| 447 | 477 | |
| 448 | 478 | public ScassandraClusterBuilder withNodes(Integer... nodes) { |
| @@ -506,7 +536,7 @@ | ||
| 506 | 536 | } |
| 507 | 537 | |
| 508 | 538 | public ScassandraCluster build() { |
| 509 | - return new ScassandraCluster(nodes, ipPrefix, 9042, 9052, keyspaceRows, forcedPeerInfos); | |
| 539 | + return new ScassandraCluster(nodes, ipPrefix, TestUtils.findAvailablePort(), TestUtils.findAvailablePort(), keyspaceRows, forcedPeerInfos); | |
| 510 | 540 | } |
| 511 | 541 | } |
| 512 | 542 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +12 −8
| @@ -15,8 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import com.datastax.driver.core.policies.AddressTranslater; | |
| 18 | 19 | import org.scassandra.Scassandra; |
| 19 | -import org.scassandra.ScassandraFactory; | |
| 20 | 20 | import org.scassandra.http.client.ActivityClient; |
| 21 | 21 | import org.scassandra.http.client.CurrentClient; |
| 22 | 22 | import org.scassandra.http.client.PrimingClient; |
| @@ -41,8 +41,6 @@ | ||
| 41 | 41 | * consider using {@link com.datastax.driver.core.ScassandraTestBase.PerClassCluster} instead. |
| 42 | 42 | */ |
| 43 | 43 | public abstract class ScassandraTestBase { |
| 44 | - private static final int BINARY_PORT = 9042; | |
| 45 | - private static final int ADMIN_PORT = 9052; | |
| 46 | 44 | |
| 47 | 45 | private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class); |
| 48 | 46 | |
| @@ -56,11 +54,11 @@ | ||
| 56 | 54 | |
| 57 | 55 | protected CurrentClient currentClient; |
| 58 | 56 | |
| 59 | - protected static String ip = CCMBridge.IP_PREFIX + "1"; | |
| 57 | + protected static String ip = TestUtils.ipOfNode(1); | |
| 60 | 58 | |
| 61 | 59 | @BeforeClass(groups = {"short", "long"}) |
| 62 | 60 | public void startScassandra() { |
| 63 | - scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT); | |
| 61 | + scassandra = TestUtils.createScassandraServer(); | |
| 64 | 62 | scassandra.start(); |
| 65 | 63 | primingClient = scassandra.primingClient(); |
| 66 | 64 | activityClient = scassandra.activityClient(); |
| @@ -85,6 +83,12 @@ | ||
| 85 | 83 | protected Cluster.Builder createClusterBuilder() { |
| 86 | 84 | Cluster.Builder builder = Cluster.builder() |
| 87 | 85 | .addContactPointsWithPorts(Collections.singletonList(hostAddress)) |
| 86 | + .withAddressTranslater(new AddressTranslater() { | |
| 87 | + @Override | |
| 88 | + public InetSocketAddress translate(InetSocketAddress address) { | |
| 89 | + return new InetSocketAddress(address.getAddress(), scassandra.getBinaryPort()); | |
| 90 | + } | |
| 91 | + }) | |
| 88 | 92 | .withPoolingOptions(new PoolingOptions() |
| 89 | 93 | .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) |
| 90 | 94 | .setMaxConnectionsPerHost(HostDistance.LOCAL, 1) |
| @@ -132,13 +136,13 @@ | ||
| 132 | 136 | session = cluster.connect(); |
| 133 | 137 | } |
| 134 | 138 | |
| 135 | - @AfterClass(groups = {"short", "long"}) | |
| 139 | + @AfterClass(groups = {"short", "long"}, alwaysRun = true) | |
| 136 | 140 | public void closeCluster() { |
| 137 | 141 | if (cluster != null) |
| 138 | 142 | cluster.close(); |
| 139 | 143 | } |
| 140 | 144 | |
| 141 | - @AfterClass(groups = {"short", "long"}, dependsOnMethods = "closeCluster") | |
| 145 | + @AfterClass(groups = {"short", "long"}, dependsOnMethods = "closeCluster", alwaysRun = true) | |
| 142 | 146 | @Override |
| 143 | 147 | public void stopScassandra() { |
| 144 | 148 | super.stopScassandra(); |
| @@ -146,4 +150,4 @@ | ||
| 146 | 150 | |
| 147 | 151 | } |
| 148 | 152 | |
| 149 | -} | |
| No newline at the end of the file | ||
| 153 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaAgreementTest.java +30 −64
| @@ -15,48 +15,34 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.exceptions.DriverException; | |
| 19 | 18 | import com.datastax.driver.core.utils.UUIDs; |
| 20 | -import org.testng.annotations.AfterClass; | |
| 21 | -import org.testng.annotations.AfterMethod; | |
| 22 | -import org.testng.annotations.BeforeClass; | |
| 23 | 19 | import org.testng.annotations.Test; |
| 24 | 20 | |
| 25 | 21 | import java.net.InetAddress; |
| 26 | 22 | import java.util.UUID; |
| 23 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 27 | 24 | |
| 28 | 25 | import static org.assertj.core.api.Assertions.assertThat; |
| 29 | 26 | |
| 30 | -public class SchemaAgreementTest { | |
| 27 | +@CCMConfig(numberOfNodes = 2) | |
| 28 | +public class SchemaAgreementTest extends CCMTestsSupport { | |
| 31 | 29 | |
| 32 | 30 | // Don't use "IF EXISTS" to remain compatible with older C* versions |
| 33 | - static final String CREATE_TABLE = "CREATE TABLE foo (k int primary key, v int)"; | |
| 34 | - static final String DROP_TABLE = "DROP TABLE foo"; | |
| 35 | - | |
| 36 | - CCMBridge ccm; | |
| 37 | - Cluster cluster; | |
| 38 | - Session session; | |
| 39 | - ProtocolOptions protocolOptions; | |
| 40 | - | |
| 41 | - @BeforeClass(groups = "short") | |
| 42 | - public void setup() { | |
| 43 | - ccm = CCMBridge.builder("schema_agreement").withNodes(2).build(); | |
| 44 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 45 | - session = cluster.connect(); | |
| 46 | - session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 47 | - session.execute("use test"); | |
| 48 | - protocolOptions = cluster.getConfiguration().getProtocolOptions(); | |
| 49 | - } | |
| 31 | + static final String CREATE_TABLE = "CREATE TABLE table_%s (k int primary key, v int)"; | |
| 32 | + | |
| 33 | + static final AtomicInteger COUNTER = new AtomicInteger(1); | |
| 50 | 34 | |
| 51 | 35 | @Test(groups = "short") |
| 52 | 36 | public void should_set_flag_on_successful_agreement() { |
| 37 | + ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions(); | |
| 53 | 38 | protocolOptions.maxSchemaAgreementWaitSeconds = 10; |
| 54 | - ResultSet rs = session.execute(CREATE_TABLE); | |
| 39 | + ResultSet rs = session.execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement())); | |
| 55 | 40 | assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue(); |
| 56 | 41 | } |
| 57 | 42 | |
| 58 | 43 | @Test(groups = "short") |
| 59 | 44 | public void should_set_flag_on_non_schema_altering_statement() { |
| 45 | + ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions(); | |
| 60 | 46 | protocolOptions.maxSchemaAgreementWaitSeconds = 10; |
| 61 | 47 | ResultSet rs = session.execute("select release_version from system.local"); |
| 62 | 48 | assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue(); |
| @@ -65,38 +51,33 @@ | ||
| 65 | 51 | @Test(groups = "short") |
| 66 | 52 | public void should_unset_flag_on_failed_agreement() { |
| 67 | 53 | // Setting to 0 results in no query being set, so agreement fails |
| 54 | + ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions(); | |
| 68 | 55 | protocolOptions.maxSchemaAgreementWaitSeconds = 0; |
| 69 | - ResultSet rs = session.execute(CREATE_TABLE); | |
| 56 | + ResultSet rs = session.execute(String.format(CREATE_TABLE, COUNTER.getAndIncrement())); | |
| 70 | 57 | assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isFalse(); |
| 71 | 58 | } |
| 72 | 59 | |
| 73 | 60 | @Test(groups = "short") |
| 74 | 61 | public void should_check_agreement_through_cluster_metadata() { |
| 75 | - Cluster controlCluster = null; | |
| 76 | - try { | |
| 77 | - controlCluster = TestUtils.buildControlCluster(cluster); | |
| 78 | - Session controlSession = controlCluster.connect(); | |
| 79 | - | |
| 80 | - Row localRow = controlSession.execute("SELECT schema_version FROM system.local").one(); | |
| 81 | - UUID localVersion = localRow.getUUID("schema_version"); | |
| 82 | - Row peerRow = controlSession.execute("SELECT peer, schema_version FROM system.peers").one(); | |
| 83 | - InetAddress peerAddress = peerRow.getInet("peer"); | |
| 84 | - UUID peerVersion = peerRow.getUUID("schema_version"); | |
| 85 | - // The two nodes should be in agreement at this point, but check just in case: | |
| 86 | - assertThat(localVersion).isEqualTo(peerVersion); | |
| 87 | - | |
| 88 | - // Now check the method under test: | |
| 89 | - assertThat(cluster.getMetadata().checkSchemaAgreement()).isTrue(); | |
| 90 | - | |
| 91 | - // Insert a fake version to simulate a disagreement: | |
| 92 | - forceSchemaVersion(controlSession, peerAddress, UUIDs.random()); | |
| 93 | - assertThat(cluster.getMetadata().checkSchemaAgreement()).isFalse(); | |
| 94 | - | |
| 95 | - forceSchemaVersion(controlSession, peerAddress, peerVersion); | |
| 96 | - } finally { | |
| 97 | - if (controlCluster != null) | |
| 98 | - controlCluster.close(); | |
| 99 | - } | |
| 62 | + Cluster controlCluster = register(TestUtils.buildControlCluster(cluster, ccm)); | |
| 63 | + Session controlSession = controlCluster.connect(); | |
| 64 | + | |
| 65 | + Row localRow = controlSession.execute("SELECT schema_version FROM system.local").one(); | |
| 66 | + UUID localVersion = localRow.getUUID("schema_version"); | |
| 67 | + Row peerRow = controlSession.execute("SELECT peer, schema_version FROM system.peers").one(); | |
| 68 | + InetAddress peerAddress = peerRow.getInet("peer"); | |
| 69 | + UUID peerVersion = peerRow.getUUID("schema_version"); | |
| 70 | + // The two nodes should be in agreement at this point, but check just in case: | |
| 71 | + assertThat(localVersion).isEqualTo(peerVersion); | |
| 72 | + | |
| 73 | + // Now check the method under test: | |
| 74 | + assertThat(cluster.getMetadata().checkSchemaAgreement()).isTrue(); | |
| 75 | + | |
| 76 | + // Insert a fake version to simulate a disagreement: | |
| 77 | + forceSchemaVersion(controlSession, peerAddress, UUIDs.random()); | |
| 78 | + assertThat(cluster.getMetadata().checkSchemaAgreement()).isFalse(); | |
| 79 | + | |
| 80 | + forceSchemaVersion(controlSession, peerAddress, peerVersion); | |
| 100 | 81 | } |
| 101 | 82 | |
| 102 | 83 | private static void forceSchemaVersion(Session session, InetAddress peerAddress, UUID schemaVersion) { |
| @@ -104,20 +85,5 @@ | ||
| 104 | 85 | DataType.uuid().format(schemaVersion), DataType.inet().format(peerAddress))); |
| 105 | 86 | } |
| 106 | 87 | |
| 107 | - @AfterMethod(groups = "short") | |
| 108 | - public void cleanupSchema() { | |
| 109 | - protocolOptions.maxSchemaAgreementWaitSeconds = 10; | |
| 110 | - try { | |
| 111 | - session.execute(DROP_TABLE); | |
| 112 | - } catch (DriverException e) { /*ignore*/ } | |
| 113 | - } | |
| 114 | - | |
| 115 | - @AfterClass(groups = "short") | |
| 116 | - public void teardown() { | |
| 117 | - if (cluster != null) | |
| 118 | - cluster.close(); | |
| 119 | - if (ccm != null) | |
| 120 | - ccm.remove(); | |
| 121 | - } | |
| 122 | 88 | } |
| 123 | 89 |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java +134 −132
| @@ -31,7 +31,8 @@ | ||
| 31 | 31 | import static org.mockito.Matchers.any; |
| 32 | 32 | import static org.mockito.Mockito.*; |
| 33 | 33 | |
| 34 | -public class SchemaChangesCCTest { | |
| 34 | +@CCMConfig(numberOfNodes = 2, dirtiesContext = true, createCluster = false) | |
| 35 | +public class SchemaChangesCCTest extends CCMTestsSupport { | |
| 35 | 36 | |
| 36 | 37 | private static final int NOTIF_TIMEOUT_MS = 5000; |
| 37 | 38 | |
| @@ -52,139 +53,140 @@ | ||
| 52 | 53 | @Test(groups = "long") |
| 53 | 54 | public void should_receive_changes_made_while_control_connection_is_down_on_reconnect() throws Exception { |
| 54 | 55 | ToggleablePolicy lbPolicy = new ToggleablePolicy(Policies.defaultLoadBalancingPolicy()); |
| 55 | - | |
| 56 | - CCMBridge ccm = CCMBridge.builder("SchemaChangesCCTest").withNodes(2).build(); | |
| 57 | - Cluster.Builder builder = Cluster.builder() | |
| 58 | - .withLoadBalancingPolicy(lbPolicy); | |
| 59 | - Cluster cluster = builder.addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 56 | + Cluster cluster = register( | |
| 57 | + Cluster.builder() | |
| 58 | + .withLoadBalancingPolicy(lbPolicy) | |
| 59 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 60 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 61 | + .build()); | |
| 60 | 62 | // Put cluster2 control connection on node 2 so it doesn't go down (to prevent noise for debugging). |
| 61 | - Cluster cluster2 = builder.addContactPoint(CCMBridge.ipOfNode(2)).build(); | |
| 62 | - try { | |
| 63 | - SchemaChangeListener listener = mock(SchemaChangeListener.class); | |
| 64 | - | |
| 65 | - cluster.init(); | |
| 66 | - cluster.register(listener); | |
| 67 | - | |
| 68 | - Session session2 = cluster2.connect(); | |
| 69 | - // Create two keyspaces to experiment with. | |
| 70 | - session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks1", 1)); | |
| 71 | - session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks2", 1)); | |
| 72 | - session2.execute("create table ks1.tbl1 (k text primary key, v text)"); | |
| 73 | - session2.execute("create table ks1.tbl2 (k text primary key, v text)"); | |
| 74 | - | |
| 75 | - // Wait for both create events to be received. | |
| 76 | - verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onKeyspaceAdded(any(KeyspaceMetadata.class)); | |
| 77 | - verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onTableAdded(any(TableMetadata.class)); | |
| 78 | - | |
| 79 | - | |
| 80 | - KeyspaceMetadata prealteredKeyspace = cluster.getMetadata().getKeyspace("ks1"); | |
| 81 | - KeyspaceMetadata predroppedKeyspace = cluster.getMetadata().getKeyspace("ks2"); | |
| 82 | - TableMetadata prealteredTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl1"); | |
| 83 | - TableMetadata predroppedTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl2"); | |
| 84 | - | |
| 85 | - // Enable returning empty query plan for default statements. This will | |
| 86 | - // prevent the control connection from being able to reconnect. | |
| 87 | - lbPolicy.returnEmptyQueryPlan = true; | |
| 88 | - | |
| 89 | - // Stop node 1, which hosts the control connection. | |
| 90 | - ccm.stop(1); | |
| 91 | - assertThat(cluster).host(1).goesDownWithin(20, TimeUnit.SECONDS); | |
| 92 | - | |
| 93 | - // Ensure control connection is down. | |
| 94 | - assertThat(cluster.manager.controlConnection.isOpen()).isFalse(); | |
| 95 | - | |
| 96 | - // Perform some schema changes that we'll validate when the control connection comes back. | |
| 97 | - session2.execute("drop keyspace ks2"); | |
| 98 | - session2.execute("drop table ks1.tbl2"); | |
| 99 | - session2.execute("alter keyspace ks1 with durable_writes=false"); | |
| 100 | - session2.execute("alter table ks1.tbl1 alter v type blob"); | |
| 101 | - session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks3", 1)); | |
| 102 | - session2.execute("create table ks1.tbl3 (k text primary key, v text)"); | |
| 103 | - | |
| 104 | - // Reset the mock to clear invocations. (sanity check to ensure all events happen after CC comes back up) | |
| 105 | - reset(listener); | |
| 106 | - | |
| 107 | - // Switch the flag so the control connection may now be established. | |
| 108 | - lbPolicy.returnEmptyQueryPlan = false; | |
| 109 | - | |
| 110 | - // Poll on the control connection and wait for it to be reestablished. | |
| 111 | - long maxControlConnectionWait = 60000; | |
| 112 | - long startTime = System.currentTimeMillis(); | |
| 113 | - while (!cluster.manager.controlConnection.isOpen() && System.currentTimeMillis() - startTime < maxControlConnectionWait) { | |
| 114 | - Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 115 | - } | |
| 116 | - | |
| 117 | - assertThat(cluster.manager.controlConnection.isOpen()) | |
| 118 | - .as("Control connection was not opened after %dms.", maxControlConnectionWait) | |
| 119 | - .isTrue(); | |
| 120 | - | |
| 121 | - // Ensure the drop keyspace event shows up. | |
| 122 | - ArgumentCaptor<KeyspaceMetadata> removedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 123 | - verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(removedKeyspace.capture()); | |
| 124 | - assertThat(removedKeyspace.getValue()) | |
| 125 | - .hasName("ks2") | |
| 126 | - .isEqualTo(predroppedKeyspace); | |
| 127 | - | |
| 128 | - // Ensure the drop table event shows up. | |
| 129 | - ArgumentCaptor<TableMetadata> droppedTable = ArgumentCaptor.forClass(TableMetadata.class); | |
| 130 | - verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(droppedTable.capture()); | |
| 131 | - | |
| 132 | - assertThat(droppedTable.getValue()) | |
| 133 | - .isInKeyspace("ks1") | |
| 134 | - .hasName("tbl2") | |
| 135 | - .isEqualTo(predroppedTable); | |
| 136 | - | |
| 137 | - // Ensure that the alter keyspace event shows up. | |
| 138 | - ArgumentCaptor<KeyspaceMetadata> alteredKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 139 | - ArgumentCaptor<KeyspaceMetadata> originalKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 140 | - verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(alteredKeyspace.capture(), originalKeyspace.capture()); | |
| 141 | - | |
| 142 | - // Previous metadata should match the metadata observed before disconnect. | |
| 143 | - assertThat(originalKeyspace.getValue()) | |
| 144 | - .hasName("ks1") | |
| 145 | - .isDurableWrites() | |
| 146 | - .isEqualTo(prealteredKeyspace); | |
| 147 | - | |
| 148 | - // New metadata should reflect that the durable writes attribute changed. | |
| 149 | - assertThat(alteredKeyspace.getValue()) | |
| 150 | - .hasName("ks1") | |
| 151 | - .isNotDurableWrites(); | |
| 152 | - | |
| 153 | - // Ensure the alter table event shows up. | |
| 154 | - ArgumentCaptor<TableMetadata> alteredTable = ArgumentCaptor.forClass(TableMetadata.class); | |
| 155 | - ArgumentCaptor<TableMetadata> originalTable = ArgumentCaptor.forClass(TableMetadata.class); | |
| 156 | - verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(alteredTable.capture(), originalTable.capture()); | |
| 157 | - | |
| 158 | - // Previous metadata should match the metadata observed before disconnect. | |
| 159 | - assertThat(originalTable.getValue()) | |
| 160 | - .isInKeyspace("ks1") | |
| 161 | - .hasName("tbl1") | |
| 162 | - .hasColumn("v", DataType.text()) | |
| 163 | - .isEqualTo(prealteredTable); | |
| 164 | - | |
| 165 | - // New metadata should reflect that the column type changed. | |
| 166 | - assertThat(alteredTable.getValue()) | |
| 167 | - .isInKeyspace("ks1") | |
| 168 | - .hasName("tbl1") | |
| 169 | - .hasColumn("v", DataType.blob()); | |
| 170 | - | |
| 171 | - // Ensure the add keyspace event shows up. | |
| 172 | - ArgumentCaptor<KeyspaceMetadata> addedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 173 | - verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(addedKeyspace.capture()); | |
| 174 | - | |
| 175 | - assertThat(addedKeyspace.getValue()).hasName("ks3"); | |
| 176 | - | |
| 177 | - // Ensure the add table event shows up. | |
| 178 | - ArgumentCaptor<TableMetadata> addedTable = ArgumentCaptor.forClass(TableMetadata.class); | |
| 179 | - verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(addedTable.capture()); | |
| 180 | - | |
| 181 | - assertThat(addedTable.getValue()) | |
| 182 | - .isInKeyspace("ks1") | |
| 183 | - .hasName("tbl3"); | |
| 184 | - } finally { | |
| 185 | - cluster.close(); | |
| 186 | - ccm.remove(); | |
| 63 | + Cluster cluster2 = register( | |
| 64 | + Cluster.builder() | |
| 65 | + .withLoadBalancingPolicy(lbPolicy) | |
| 66 | + .addContactPointsWithPorts(ccm.addressOfNode(2)) | |
| 67 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 68 | + .build()); | |
| 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); | |
| 187 | 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"); | |
| 188 | 190 | } |
| 189 | 191 | |
| 190 | 192 | /** |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +56 −62
| @@ -23,8 +23,6 @@ | ||
| 23 | 23 | import org.mockito.ArgumentCaptor; |
| 24 | 24 | import org.testng.annotations.*; |
| 25 | 25 | |
| 26 | -import java.util.Collection; | |
| 27 | -import java.util.Collections; | |
| 28 | 26 | import java.util.List; |
| 29 | 27 | |
| 30 | 28 | import static com.datastax.driver.core.Assertions.assertThat; |
| @@ -33,7 +31,8 @@ | ||
| 33 | 31 | import static org.mockito.Matchers.any; |
| 34 | 32 | import static org.mockito.Mockito.*; |
| 35 | 33 | |
| 36 | -public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 34 | +@CCMConfig(createCluster = false) | |
| 35 | +public class SchemaChangesTest extends CCMTestsSupport { | |
| 37 | 36 | |
| 38 | 37 | private static final String CREATE_KEYSPACE = "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }"; |
| 39 | 38 | private static final String ALTER_KEYSPACE = "ALTER KEYSPACE %s WITH durable_writes = false"; |
| @@ -46,15 +45,12 @@ | ||
| 46 | 45 | /** |
| 47 | 46 | * The maximum time that the test will wait to check that listeners have been notified |
| 48 | 47 | */ |
| 49 | - private static final int NOTIF_TIMEOUT_MS = 5000; | |
| 48 | + private static final int NOTIF_TIMEOUT_MS = 120000; | |
| 50 | 49 | |
| 51 | 50 | Cluster cluster1; |
| 52 | 51 | Cluster cluster2; // a second cluster to check that other clients also get notified |
| 53 | 52 | Cluster schemaDisabledCluster; // a cluster with schema metadata disabled. |
| 54 | 53 | |
| 55 | - // The metadatas of the two clusters (we'll test that they're kept in sync) | |
| 56 | - List<Metadata> metadatas; | |
| 57 | - | |
| 58 | 54 | Session session1; |
| 59 | 55 | |
| 60 | 56 | Session schemaDisabledSession; |
| @@ -67,20 +63,15 @@ | ||
| 67 | 63 | |
| 68 | 64 | ControlConnection schemaDisabledControlConnection; |
| 69 | 65 | |
| 70 | - @Override | |
| 71 | - protected Collection<String> getTableDefinitions() { | |
| 72 | - return Lists.newArrayList(); | |
| 73 | - } | |
| 74 | - | |
| 75 | 66 | @BeforeClass(groups = "short") |
| 76 | 67 | public void setup() throws InterruptedException { |
| 77 | - Cluster.Builder builder = configure(Cluster.builder()) | |
| 78 | - .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 68 | + Cluster.Builder builder = Cluster.builder() | |
| 69 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 79 | 70 | .withQueryOptions(nonDebouncingQueryOptions()); |
| 80 | 71 | cluster1 = builder.build(); |
| 81 | 72 | cluster2 = builder.build(); |
| 82 | - schemaDisabledCluster = spy(configure(Cluster.builder()) | |
| 83 | - .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 73 | + schemaDisabledCluster = spy(Cluster.builder() | |
| 74 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 84 | 75 | .withClusterName("schema-disabled") |
| 85 | 76 | .withQueryOptions(nonDebouncingQueryOptions() |
| 86 | 77 | .setMetadataEnabled(false) |
| @@ -91,8 +82,6 @@ | ||
| 91 | 82 | schemaDisabledControlConnection = spy(schemaDisabledCluster.manager.controlConnection); |
| 92 | 83 | schemaDisabledCluster.manager.controlConnection = schemaDisabledControlConnection; |
| 93 | 84 | |
| 94 | - metadatas = Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata()); | |
| 95 | - | |
| 96 | 85 | session1 = cluster1.connect(); |
| 97 | 86 | |
| 98 | 87 | cluster1.register(listener1 = mock(SchemaChangeListener.class)); |
| @@ -106,7 +95,7 @@ | ||
| 106 | 95 | execute(CREATE_KEYSPACE, "\"CaseSensitive\""); |
| 107 | 96 | } |
| 108 | 97 | |
| 109 | - @AfterClass(groups = "short") | |
| 98 | + @AfterClass(groups = "short", alwaysRun = true) | |
| 110 | 99 | public void teardown() { |
| 111 | 100 | if (cluster1 != null) |
| 112 | 101 | cluster1.close(); |
| @@ -157,16 +146,13 @@ | ||
| 157 | 146 | .isInKeyspace(handleId(keyspace)) |
| 158 | 147 | .hasName("table1"); |
| 159 | 148 | } |
| 160 | - | |
| 161 | - for (Metadata m : metadatas) | |
| 149 | + for (Metadata m : metadatas()) | |
| 162 | 150 | assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull(); |
| 163 | 151 | } |
| 164 | 152 | |
| 165 | 153 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 166 | 154 | public void should_notify_of_table_update(String keyspace) throws InterruptedException { |
| 167 | 155 | execute(CREATE_TABLE, keyspace); |
| 168 | - for (Metadata m : metadatas) | |
| 169 | - assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j"); | |
| 170 | 156 | ArgumentCaptor<TableMetadata> added = null; |
| 171 | 157 | for (SchemaChangeListener listener : listeners) { |
| 172 | 158 | added = ArgumentCaptor.forClass(TableMetadata.class); |
| @@ -175,6 +161,9 @@ | ||
| 175 | 161 | .isInKeyspace(handleId(keyspace)) |
| 176 | 162 | .hasName("table1"); |
| 177 | 163 | } |
| 164 | + for (Metadata m : metadatas()) | |
| 165 | + assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j"); | |
| 166 | + assert added != null; | |
| 178 | 167 | execute(ALTER_TABLE, keyspace); |
| 179 | 168 | for (SchemaChangeListener listener : listeners) { |
| 180 | 169 | ArgumentCaptor<TableMetadata> current = ArgumentCaptor.forClass(TableMetadata.class); |
| @@ -188,7 +177,7 @@ | ||
| 188 | 177 | .hasName("table1") |
| 189 | 178 | .hasColumn("j"); |
| 190 | 179 | } |
| 191 | - for (Metadata m : metadatas) | |
| 180 | + for (Metadata m : metadatas()) | |
| 192 | 181 | assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j"); |
| 193 | 182 | } |
| 194 | 183 | |
| @@ -203,38 +192,35 @@ | ||
| 203 | 192 | .isInKeyspace(handleId(keyspace)); |
| 204 | 193 | } |
| 205 | 194 | execute(DROP_TABLE, keyspace); |
| 206 | - for (Metadata m : metadatas) | |
| 207 | - assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull(); | |
| 208 | 195 | for (SchemaChangeListener listener : listeners) { |
| 209 | 196 | ArgumentCaptor<TableMetadata> removed = ArgumentCaptor.forClass(TableMetadata.class); |
| 210 | 197 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(removed.capture()); |
| 211 | 198 | assertThat(removed.getValue()).hasName("table1"); |
| 212 | 199 | } |
| 200 | + for (Metadata m : metadatas()) | |
| 201 | + assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull(); | |
| 213 | 202 | } |
| 214 | 203 | |
| 204 | + @SuppressWarnings("RedundantCast") | |
| 215 | 205 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 216 | 206 | @CassandraVersion(major = 2.1) |
| 217 | 207 | public void should_notify_of_udt_creation(String keyspace) { |
| 218 | - session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); | |
| 219 | - | |
| 208 | + session1.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); | |
| 220 | 209 | for (SchemaChangeListener listener : listeners) { |
| 221 | 210 | ArgumentCaptor<UserType> added = ArgumentCaptor.forClass(UserType.class); |
| 222 | 211 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeAdded(added.capture()); |
| 223 | 212 | assertThat((DataType) added.getValue()) |
| 224 | 213 | .isUserType(handleId(keyspace), "type1"); |
| 225 | 214 | } |
| 226 | - | |
| 227 | - for (Metadata m : metadatas) | |
| 228 | - assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")) | |
| 229 | - .isNotNull(); | |
| 215 | + for (Metadata m : metadatas()) | |
| 216 | + assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNotNull(); | |
| 230 | 217 | } |
| 231 | 218 | |
| 232 | 219 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 233 | 220 | @CassandraVersion(major = 2.1) |
| 234 | 221 | public void should_notify_of_udt_update(String keyspace) { |
| 235 | - session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); | |
| 236 | - session.execute(String.format("ALTER TYPE %s.type1 ADD j int", keyspace)); | |
| 237 | - | |
| 222 | + session1.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); | |
| 223 | + session1.execute(String.format("ALTER TYPE %s.type1 ADD j int", keyspace)); | |
| 238 | 224 | for (SchemaChangeListener listener : listeners) { |
| 239 | 225 | ArgumentCaptor<UserType> current = ArgumentCaptor.forClass(UserType.class); |
| 240 | 226 | ArgumentCaptor<UserType> previous = ArgumentCaptor.forClass(UserType.class); |
| @@ -242,39 +228,35 @@ | ||
| 242 | 228 | assertThat(previous.getValue().getFieldNames()).doesNotContain("j"); |
| 243 | 229 | assertThat(current.getValue().getFieldNames()).contains("j"); |
| 244 | 230 | } |
| 245 | - | |
| 246 | - for (Metadata m : metadatas) | |
| 247 | - assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j")) | |
| 248 | - .isNotNull(); | |
| 231 | + for (Metadata m : metadatas()) | |
| 232 | + assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j")).isNotNull(); | |
| 249 | 233 | } |
| 250 | 234 | |
| 235 | + @SuppressWarnings("RedundantCast") | |
| 251 | 236 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 252 | 237 | @CassandraVersion(major = 2.1) |
| 253 | 238 | public void should_notify_of_udt_drop(String keyspace) { |
| 254 | - session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); | |
| 255 | - session.execute(String.format("DROP TYPE %s.type1", keyspace)); | |
| 256 | - | |
| 239 | + session1.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); | |
| 240 | + session1.execute(String.format("DROP TYPE %s.type1", keyspace)); | |
| 257 | 241 | for (SchemaChangeListener listener : listeners) { |
| 258 | 242 | ArgumentCaptor<UserType> removed = ArgumentCaptor.forClass(UserType.class); |
| 259 | 243 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeRemoved(removed.capture()); |
| 260 | 244 | assertThat((DataType) removed.getValue()).isUserType(handleId(keyspace), "type1"); |
| 261 | 245 | } |
| 262 | - | |
| 263 | - for (Metadata m : metadatas) | |
| 264 | - assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")) | |
| 265 | - .isNull(); | |
| 246 | + for (Metadata m : metadatas()) | |
| 247 | + assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")).isNull(); | |
| 266 | 248 | } |
| 267 | 249 | |
| 268 | 250 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 269 | 251 | public void should_notify_of_keyspace_creation(String keyspace) throws InterruptedException { |
| 270 | 252 | execute(CREATE_KEYSPACE, keyspace); |
| 271 | - for (Metadata m : metadatas) | |
| 272 | - assertThat(m.getKeyspace(keyspace)).isNotNull(); | |
| 273 | 253 | for (SchemaChangeListener listener : listeners) { |
| 274 | 254 | ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class); |
| 275 | 255 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); |
| 276 | 256 | assertThat(added.getValue()).hasName(handleId(keyspace)); |
| 277 | 257 | } |
| 258 | + for (Metadata m : metadatas()) | |
| 259 | + assertThat(m.getKeyspace(keyspace)).isNotNull(); | |
| 278 | 260 | } |
| 279 | 261 | |
| 280 | 262 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| @@ -286,7 +268,8 @@ | ||
| 286 | 268 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); |
| 287 | 269 | assertThat(added.getValue()).hasName(handleId(keyspace)); |
| 288 | 270 | } |
| 289 | - for (Metadata m : metadatas) | |
| 271 | + assert added != null; | |
| 272 | + for (Metadata m : metadatas()) | |
| 290 | 273 | assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue(); |
| 291 | 274 | execute(ALTER_KEYSPACE, keyspace); |
| 292 | 275 | for (SchemaChangeListener listener : listeners) { |
| @@ -300,14 +283,21 @@ | ||
| 300 | 283 | .hasName(handleId(keyspace)) |
| 301 | 284 | .isNotDurableWrites(); |
| 302 | 285 | } |
| 303 | - for (Metadata m : metadatas) | |
| 286 | + for (Metadata m : metadatas()) | |
| 304 | 287 | assertThat(m.getKeyspace(keyspace)).isNotDurableWrites(); |
| 305 | 288 | } |
| 306 | 289 | |
| 307 | 290 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 308 | 291 | public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException { |
| 309 | 292 | execute(CREATE_KEYSPACE, keyspace); |
| 310 | - for (Metadata m : metadatas) | |
| 293 | + ArgumentCaptor<KeyspaceMetadata> added = null; | |
| 294 | + for (SchemaChangeListener listener : listeners) { | |
| 295 | + added = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 296 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); | |
| 297 | + assertThat(added.getValue()).hasName(handleId(keyspace)); | |
| 298 | + } | |
| 299 | + assert added != null; | |
| 300 | + for (Metadata m : metadatas()) | |
| 311 | 301 | assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty(); |
| 312 | 302 | execute(CREATE_TABLE, keyspace); // to test table drop notifications |
| 313 | 303 | execute(DROP_KEYSPACE, keyspace); |
| @@ -317,13 +307,12 @@ | ||
| 317 | 307 | assertThat(table.getValue()) |
| 318 | 308 | .hasName("table1") |
| 319 | 309 | .isInKeyspace(handleId(keyspace)); |
| 320 | - | |
| 321 | 310 | ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class); |
| 322 | 311 | verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture()); |
| 323 | 312 | assertThat(ks.getValue()) |
| 324 | 313 | .hasName(handleId(keyspace)); |
| 325 | 314 | } |
| 326 | - for (Metadata m : metadatas) { | |
| 315 | + for (Metadata m : metadatas()) { | |
| 327 | 316 | assertThat(m.getKeyspace(keyspace)).isNull(); |
| 328 | 317 | assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty(); |
| 329 | 318 | } |
| @@ -339,8 +328,8 @@ | ||
| 339 | 328 | */ |
| 340 | 329 | @Test(groups = "short", expectedExceptions = IllegalStateException.class) |
| 341 | 330 | public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() { |
| 342 | - Cluster cluster = configure(Cluster.builder()) | |
| 343 | - .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 331 | + Cluster cluster = Cluster.builder() | |
| 332 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 344 | 333 | .withQueryOptions(nonDebouncingQueryOptions() |
| 345 | 334 | .setMetadataEnabled(false) |
| 346 | 335 | ).build(); |
| @@ -363,8 +352,8 @@ | ||
| 363 | 352 | */ |
| 364 | 353 | @Test(groups = "short", expectedExceptions = IllegalStateException.class) |
| 365 | 354 | public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() { |
| 366 | - Cluster cluster = configure(Cluster.builder()) | |
| 367 | - .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 355 | + Cluster cluster = Cluster.builder() | |
| 356 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 368 | 357 | .withQueryOptions(nonDebouncingQueryOptions() |
| 369 | 358 | .setMetadataEnabled(false) |
| 370 | 359 | ).build(); |
| @@ -386,8 +375,8 @@ | ||
| 386 | 375 | * @jira_ticket JAVA-858 |
| 387 | 376 | * @since 2.0.11 |
| 388 | 377 | */ |
| 389 | - @Test(groups = "short") | |
| 390 | - public void should_not_refresh_schema_on_schema_change_response() throws InterruptedException { | |
| 378 | + @Test(groups = "short", dataProvider = "existingKeyspaceName") | |
| 379 | + public void should_not_refresh_schema_on_schema_change_response(String keyspace) throws InterruptedException { | |
| 391 | 380 | ResultSet rs = schemaDisabledSession.execute(String.format(CREATE_TABLE, keyspace)); |
| 392 | 381 | |
| 393 | 382 | // Should still wait on schema agreement. |
| @@ -405,8 +394,8 @@ | ||
| 405 | 394 | * @jira_ticket JAVA-858 |
| 406 | 395 | * @since 2.0.11 |
| 407 | 396 | */ |
| 408 | - @Test(groups = "short") | |
| 409 | - public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled() throws Exception { | |
| 397 | + @Test(groups = "short", dataProvider = "existingKeyspaceName") | |
| 398 | + public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled(String keyspace) throws Exception { | |
| 410 | 399 | try { |
| 411 | 400 | schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true); |
| 412 | 401 | |
| @@ -435,7 +424,7 @@ | ||
| 435 | 424 | } |
| 436 | 425 | } |
| 437 | 426 | |
| 438 | - @AfterMethod(groups = "short") | |
| 427 | + @AfterMethod(groups = "short", alwaysRun = true) | |
| 439 | 428 | public void cleanup() throws InterruptedException { |
| 440 | 429 | ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList( |
| 441 | 430 | session1.executeAsync("DROP TABLE lowercase.table1"), |
| @@ -451,4 +440,9 @@ | ||
| 451 | 440 | private void execute(String cql, String keyspace) throws InterruptedException { |
| 452 | 441 | session1.execute(String.format(cql, keyspace)); |
| 453 | 442 | } |
| 443 | + | |
| 444 | + private List<Metadata> metadatas() { | |
| 445 | + return Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata()); | |
| 446 | + } | |
| 447 | + | |
| 454 | 448 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +8 −33
| @@ -16,23 +16,22 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import org.mockito.ArgumentCaptor; |
| 19 | -import org.testng.annotations.AfterClass; | |
| 20 | 19 | import org.testng.annotations.AfterMethod; |
| 21 | -import org.testng.annotations.BeforeClass; | |
| 20 | +import org.testng.annotations.BeforeMethod; | |
| 22 | 21 | import org.testng.annotations.Test; |
| 23 | 22 | |
| 24 | -import java.util.Collection; | |
| 25 | - | |
| 26 | 23 | import static com.datastax.driver.core.Assertions.assertThat; |
| 24 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 27 | 25 | import static com.datastax.driver.core.SchemaElement.KEYSPACE; |
| 28 | 26 | import static com.datastax.driver.core.SchemaElement.TABLE; |
| 29 | 27 | import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; |
| 30 | 28 | import static com.datastax.driver.core.TestUtils.CREATE_TABLE_SIMPLE_FORMAT; |
| 31 | -import static com.google.common.collect.Lists.newArrayList; | |
| 32 | 29 | import static org.mockito.ArgumentCaptor.forClass; |
| 33 | 30 | import static org.mockito.Mockito.*; |
| 34 | 31 | |
| 35 | -public class SchemaRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 32 | +@CreateCCM(PER_METHOD) | |
| 33 | +@CCMConfig(dirtiesContext = true, createKeyspace = false) | |
| 34 | +public class SchemaRefreshDebouncerTest extends CCMTestsSupport { | |
| 36 | 35 | |
| 37 | 36 | // This may need to be tweaked depending on the reliability of the test environment. |
| 38 | 37 | private static final int DEBOUNCE_TIME = 5000; |
| @@ -47,22 +46,14 @@ | ||
| 47 | 46 | private Session session2; |
| 48 | 47 | private Cluster cluster2; |
| 49 | 48 | |
| 50 | - // Keyspaces to drop after test completes. | |
| 51 | - private Collection<String> keyspaces = newArrayList(); | |
| 52 | - | |
| 53 | - @Override | |
| 54 | - protected Collection<String> getTableDefinitions() { | |
| 55 | - return newArrayList(); | |
| 56 | - } | |
| 57 | - | |
| 58 | - @BeforeClass(groups = "short") | |
| 49 | + @BeforeMethod(groups = "short") | |
| 59 | 50 | public void setup() { |
| 60 | 51 | QueryOptions queryOptions = new QueryOptions(); |
| 61 | 52 | queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME); |
| 62 | 53 | queryOptions.setMaxPendingRefreshSchemaRequests(5); |
| 63 | 54 | // Create a separate cluster that will receive the schema events on its control connection. |
| 64 | - cluster2 = this.configure(Cluster.builder()) | |
| 65 | - .addContactPointsWithPorts(newArrayList(hostAddress)) | |
| 55 | + cluster2 = Cluster.builder() | |
| 56 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 66 | 57 | .withQueryOptions(queryOptions) |
| 67 | 58 | .build(); |
| 68 | 59 | session2 = cluster2.connect(); |
| @@ -81,17 +72,7 @@ | ||
| 81 | 72 | |
| 82 | 73 | @AfterMethod(groups = "short") |
| 83 | 74 | public void beforeMethod() { |
| 84 | - reset(listener); | |
| 85 | - reset(controlConnection); | |
| 86 | - } | |
| 87 | - | |
| 88 | - @AfterClass(groups = "short") | |
| 89 | - public void teardown() { | |
| 90 | 75 | cluster2.close(); |
| 91 | - // drop all keyspaces | |
| 92 | - for (String keyspace : keyspaces) { | |
| 93 | - session.execute("DROP KEYSPACE " + keyspace); | |
| 94 | - } | |
| 95 | 76 | } |
| 96 | 77 | |
| 97 | 78 | /** |
| @@ -107,7 +88,6 @@ | ||
| 107 | 88 | public void should_debounce_and_coalesce_create_and_alter_keyspace_into_refresh_keyspace() throws Exception { |
| 108 | 89 | String keyspace = "sdaccaak"; |
| 109 | 90 | session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); |
| 110 | - keyspaces.add(keyspace); | |
| 111 | 91 | session.execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace)); |
| 112 | 92 | |
| 113 | 93 | ArgumentCaptor<KeyspaceMetadata> captor = forClass(KeyspaceMetadata.class); |
| @@ -140,7 +120,6 @@ | ||
| 140 | 120 | String keyspace = "sdacckt"; |
| 141 | 121 | String table = "tbl1"; |
| 142 | 122 | session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); |
| 143 | - keyspaces.add(keyspace); | |
| 144 | 123 | session.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table)); |
| 145 | 124 | |
| 146 | 125 | ArgumentCaptor<KeyspaceMetadata> keyspaceCaptor = forClass(KeyspaceMetadata.class); |
| @@ -175,7 +154,6 @@ | ||
| 175 | 154 | public void should_debounce_and_coalesce_tables_in_same_keyspace_into_refresh_keyspace() throws Exception { |
| 176 | 155 | String keyspace = "sdactisk"; |
| 177 | 156 | session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); |
| 178 | - keyspaces.add(keyspace); | |
| 179 | 157 | // Reset invocations as creating keyspace causes a keyspace refresh. |
| 180 | 158 | reset(controlConnection); |
| 181 | 159 | reset(listener); |
| @@ -220,7 +198,6 @@ | ||
| 220 | 198 | String columnName = "added_column"; |
| 221 | 199 | // Execute on session 2 which refreshes schema as part of processing responses. |
| 222 | 200 | session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); |
| 223 | - keyspaces.add(keyspace); | |
| 224 | 201 | session2.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table)); |
| 225 | 202 | reset(controlConnection); |
| 226 | 203 | reset(listener); |
| @@ -271,7 +248,6 @@ | ||
| 271 | 248 | String prefix = "sdacmkc"; |
| 272 | 249 | for (int i = 0; i < 3; i++) { |
| 273 | 250 | session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1)); |
| 274 | - keyspaces.add(prefix + i); | |
| 275 | 251 | } |
| 276 | 252 | |
| 277 | 253 | verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class)); |
| @@ -298,7 +274,6 @@ | ||
| 298 | 274 | String prefix = "srwmprr"; |
| 299 | 275 | for (int i = 0; i < 5; i++) { |
| 300 | 276 | session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1)); |
| 301 | - keyspaces.add(prefix + i); | |
| 302 | 277 | } |
| 303 | 278 | |
| 304 | 279 | // Event should be processed immediately as we hit our threshold. |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +3 −11
| @@ -26,7 +26,8 @@ | ||
| 26 | 26 | /** |
| 27 | 27 | * Test we correctly process and print schema. |
| 28 | 28 | */ |
| 29 | -public class SchemaTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 29 | +@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing") | |
| 30 | +public class SchemaTest extends CCMTestsSupport { | |
| 30 | 31 | static final Logger logger = LoggerFactory.getLogger(SchemaTest.class); |
| 31 | 32 | |
| 32 | 33 | private static final Map<String, String> cql3 = new HashMap<String, String>(); |
| @@ -35,16 +36,7 @@ | ||
| 35 | 36 | private static String withOptions; |
| 36 | 37 | |
| 37 | 38 | @Override |
| 38 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 39 | - return builder.withQueryOptions(new QueryOptions() | |
| 40 | - .setRefreshNodeIntervalMillis(0) | |
| 41 | - .setRefreshNodeListIntervalMillis(0) | |
| 42 | - .setRefreshSchemaIntervalMillis(0) | |
| 43 | - ); | |
| 44 | - } | |
| 45 | - | |
| 46 | - @Override | |
| 47 | - protected Collection<String> getTableDefinitions() { | |
| 39 | + public Collection<String> createTestFixtures() { | |
| 48 | 40 | |
| 49 | 41 | String sparse = String.format("CREATE TABLE %s.sparse (\n" |
| 50 | 42 | + " k text,\n" |
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +68 −97
| @@ -17,138 +17,109 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 19 | 19 | import com.datastax.driver.core.utils.SocketChannelMonitor; |
| 20 | -import com.google.common.collect.Lists; | |
| 21 | 20 | import org.testng.annotations.Test; |
| 22 | 21 | |
| 23 | -import java.net.InetSocketAddress; | |
| 24 | -import java.util.Collections; | |
| 25 | -import java.util.List; | |
| 26 | 22 | import java.util.concurrent.TimeUnit; |
| 27 | 23 | |
| 28 | 24 | import static com.datastax.driver.core.Assertions.assertThat; |
| 25 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 29 | 26 | import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; |
| 27 | +import static com.google.common.collect.Lists.newArrayList; | |
| 30 | 28 | import static java.util.concurrent.TimeUnit.MINUTES; |
| 31 | 29 | import static org.assertj.core.api.Assertions.fail; |
| 32 | 30 | |
| 33 | -public class SessionLeakTest { | |
| 31 | +@CreateCCM(PER_METHOD) | |
| 32 | +@CCMConfig(dirtiesContext = true, createCluster = false) | |
| 33 | +public class SessionLeakTest extends CCMTestsSupport { | |
| 34 | 34 | |
| 35 | - Cluster cluster; | |
| 36 | - List<InetSocketAddress> nodes = Lists.newArrayList( | |
| 37 | - new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042), | |
| 38 | - new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042)); | |
| 39 | 35 | SocketChannelMonitor channelMonitor; |
| 40 | 36 | |
| 41 | 37 | @Test(groups = "short") |
| 42 | 38 | public void connectionLeakTest() throws Exception { |
| 43 | 39 | // Checking for JAVA-342 |
| 44 | - CCMBridge ccmBridge; | |
| 45 | - ccmBridge = CCMBridge.builder("test").withNodes(1).build(); | |
| 46 | 40 | channelMonitor = new SocketChannelMonitor(); |
| 47 | 41 | channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); |
| 48 | - try { | |
| 49 | - cluster = Cluster.builder() | |
| 50 | - .addContactPointsWithPorts(Collections.singletonList( | |
| 51 | - new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042))) | |
| 52 | - .withNettyOptions(channelMonitor.nettyOptions()) | |
| 53 | - .withQueryOptions(nonDebouncingQueryOptions()) | |
| 54 | - .build(); | |
| 55 | - | |
| 56 | - cluster.init(); | |
| 57 | - | |
| 58 | - assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 59 | - // Should be 1 control connection after initialization. | |
| 60 | - assertOpenConnections(1); | |
| 61 | - | |
| 62 | - // ensure sessions.size() returns with 1 control connection + core pool size. | |
| 63 | - int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster); | |
| 64 | - Session session = cluster.connect(); | |
| 65 | - | |
| 66 | - assertThat(cluster.manager.sessions.size()).isEqualTo(1); | |
| 67 | - assertOpenConnections(1 + corePoolSize); | |
| 68 | - | |
| 69 | - // ensure sessions.size() returns to 0 with only 1 active connection (the control connection) | |
| 70 | - session.close(); | |
| 71 | - assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 72 | - assertOpenConnections(1); | |
| 73 | - | |
| 74 | - // ensure bootstrapping a node does not create additional connections | |
| 75 | - ccmBridge.bootstrapNode(2); | |
| 76 | - assertThat(cluster).host(2).comesUpWithin(2, MINUTES); | |
| 77 | - | |
| 78 | - assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 79 | - assertOpenConnections(1); | |
| 80 | - | |
| 81 | - // ensure a new session gets registered and core connections are established | |
| 82 | - // there should be corePoolSize more connections to accommodate for the new host. | |
| 83 | - Session thisSession = cluster.connect(); | |
| 84 | - assertThat(cluster.manager.sessions.size()).isEqualTo(1); | |
| 85 | - assertOpenConnections(1 + (corePoolSize * 2)); | |
| 86 | - | |
| 87 | - // ensure bootstrapping a node does not create additional connections that won't get cleaned up | |
| 88 | - thisSession.close(); | |
| 89 | - | |
| 90 | - assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 91 | - assertOpenConnections(1); | |
| 92 | - } finally { | |
| 93 | - if (cluster != null) { | |
| 94 | - cluster.close(); | |
| 95 | - } | |
| 96 | - if (ccmBridge != null) { | |
| 97 | - ccmBridge.remove(); | |
| 98 | - } | |
| 99 | - // Ensure no channels remain open. | |
| 100 | - channelMonitor.stop(); | |
| 101 | - channelMonitor.report(); | |
| 102 | - assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(0); | |
| 103 | - } | |
| 42 | + cluster = register(Cluster.builder() | |
| 43 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 44 | + .withAddressTranslater(getAddressTranslator()) | |
| 45 | + .withNettyOptions(channelMonitor.nettyOptions()) | |
| 46 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 47 | + .build()); | |
| 48 | + | |
| 49 | + cluster.init(); | |
| 50 | + | |
| 51 | + assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 52 | + // Should be 1 control connection after initialization. | |
| 53 | + assertOpenConnections(1); | |
| 54 | + | |
| 55 | + // ensure sessions.size() returns with 1 control connection + core pool size. | |
| 56 | + int corePoolSize = TestUtils.numberOfLocalCoreConnections(cluster); | |
| 57 | + Session session = cluster.connect(); | |
| 58 | + | |
| 59 | + assertThat(cluster.manager.sessions.size()).isEqualTo(1); | |
| 60 | + assertOpenConnections(1 + corePoolSize); | |
| 61 | + | |
| 62 | + // ensure sessions.size() returns to 0 with only 1 active connection (the control connection) | |
| 63 | + session.close(); | |
| 64 | + assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 65 | + assertOpenConnections(1); | |
| 66 | + | |
| 67 | + // ensure bootstrapping a node does not create additional connections | |
| 68 | + ccm.add(2); | |
| 69 | + ccm.start(2); | |
| 70 | + assertThat(cluster).host(2).comesUpWithin(2, MINUTES); | |
| 71 | + | |
| 72 | + assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 73 | + assertOpenConnections(1); | |
| 74 | + | |
| 75 | + // ensure a new session gets registered and core connections are established | |
| 76 | + // there should be corePoolSize more connections to accommodate for the new host. | |
| 77 | + Session thisSession = cluster.connect(); | |
| 78 | + assertThat(cluster.manager.sessions.size()).isEqualTo(1); | |
| 79 | + assertOpenConnections(1 + (corePoolSize * 2)); | |
| 80 | + | |
| 81 | + // ensure bootstrapping a node does not create additional connections that won't get cleaned up | |
| 82 | + thisSession.close(); | |
| 83 | + | |
| 84 | + assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 85 | + assertOpenConnections(1); | |
| 86 | + cluster.close(); | |
| 87 | + // Ensure no channels remain open. | |
| 88 | + channelMonitor.stop(); | |
| 89 | + channelMonitor.report(); | |
| 90 | + assertThat(channelMonitor.openChannels(newArrayList(ccm.addressOfNode(1), ccm.addressOfNode(2))).size()).isEqualTo(0); | |
| 104 | 91 | } |
| 105 | 92 | |
| 106 | 93 | @Test(groups = "short") |
| 107 | 94 | public void should_not_leak_session_when_wrong_keyspace() throws Exception { |
| 108 | 95 | // Checking for JAVA-806 |
| 109 | - CCMBridge ccmBridge; | |
| 110 | - ccmBridge = CCMBridge.builder("test").withNodes(1).build(); | |
| 111 | 96 | channelMonitor = new SocketChannelMonitor(); |
| 112 | 97 | channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); |
| 98 | + cluster = register(Cluster.builder() | |
| 99 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 100 | + .withAddressTranslater(getAddressTranslator()) | |
| 101 | + .withNettyOptions(channelMonitor.nettyOptions()) | |
| 102 | + .build()); | |
| 103 | + cluster.init(); | |
| 104 | + assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 113 | 105 | try { |
| 114 | - cluster = Cluster.builder() | |
| 115 | - .addContactPointsWithPorts(Collections.singletonList( | |
| 116 | - new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042))) | |
| 117 | - .withNettyOptions(channelMonitor.nettyOptions()).build(); | |
| 118 | - | |
| 119 | - cluster.init(); | |
| 120 | - | |
| 121 | - assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 122 | 106 | // Should be 1 control connection after initialization. |
| 123 | 107 | assertOpenConnections(1); |
| 124 | - | |
| 125 | 108 | cluster.connect("wrong_keyspace"); |
| 126 | - | |
| 127 | 109 | fail("Should not have connected to a wrong keyspace"); |
| 128 | - | |
| 129 | 110 | } catch (InvalidQueryException e) { |
| 130 | - | |
| 131 | 111 | // ok |
| 132 | - | |
| 133 | - } finally { | |
| 134 | - | |
| 135 | - assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 136 | - | |
| 137 | - if (cluster != null) { | |
| 138 | - cluster.close(); | |
| 139 | - } | |
| 140 | - if (ccmBridge != null) { | |
| 141 | - ccmBridge.remove(); | |
| 142 | - } | |
| 143 | - // Ensure no channels remain open. | |
| 144 | - channelMonitor.stop(); | |
| 145 | - channelMonitor.report(); | |
| 146 | - assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(0); | |
| 147 | 112 | } |
| 113 | + assertThat(cluster.manager.sessions.size()).isEqualTo(0); | |
| 114 | + cluster.close(); | |
| 115 | + // Ensure no channels remain open. | |
| 116 | + channelMonitor.stop(); | |
| 117 | + channelMonitor.report(); | |
| 118 | + assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(0); | |
| 148 | 119 | } |
| 149 | 120 | |
| 150 | 121 | private void assertOpenConnections(int expected) { |
| 151 | 122 | assertThat((cluster.getMetrics().getOpenConnections().getValue())).isEqualTo(expected); |
| 152 | - assertThat(channelMonitor.openChannels(nodes).size()).isEqualTo(expected); | |
| 123 | + assertThat(channelMonitor.openChannels(ccm.addressOfNode(1), ccm.addressOfNode(2)).size()).isEqualTo(expected); | |
| 153 | 124 | } |
| 154 | 125 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +29 −16
| @@ -23,16 +23,19 @@ | ||
| 23 | 23 | import com.google.common.util.concurrent.Uninterruptibles; |
| 24 | 24 | import org.slf4j.Logger; |
| 25 | 25 | import org.slf4j.LoggerFactory; |
| 26 | +import org.testng.annotations.AfterMethod; | |
| 26 | 27 | import org.testng.annotations.Test; |
| 27 | 28 | |
| 28 | -import java.net.InetSocketAddress; | |
| 29 | -import java.util.*; | |
| 29 | +import java.util.Iterator; | |
| 30 | +import java.util.List; | |
| 31 | +import java.util.Stack; | |
| 30 | 32 | import java.util.concurrent.*; |
| 31 | 33 | |
| 32 | 34 | import static org.testng.Assert.assertEquals; |
| 33 | 35 | import static org.testng.Assert.fail; |
| 34 | 36 | |
| 35 | -public class SessionStressTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 37 | +@CCMConfig(dirtiesContext = true) | |
| 38 | +public class SessionStressTest extends CCMTestsSupport { | |
| 36 | 39 | |
| 37 | 40 | private static final Logger logger = LoggerFactory.getLogger(SessionStressTest.class); |
| 38 | 41 | |
| @@ -47,9 +50,16 @@ | ||
| 47 | 50 | executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8)); |
| 48 | 51 | } |
| 49 | 52 | |
| 50 | - @Override | |
| 51 | - protected Collection<String> getTableDefinitions() { | |
| 52 | - return new ArrayList<String>(0); | |
| 53 | + @AfterMethod(groups = "long", alwaysRun = true) | |
| 54 | + public void shutdown() throws Exception { | |
| 55 | + executorService.shutdown(); | |
| 56 | + try { | |
| 57 | + boolean shutdown = executorService.awaitTermination(30, TimeUnit.SECONDS); | |
| 58 | + if (!shutdown) | |
| 59 | + fail("executor ran for longer than expected"); | |
| 60 | + } catch (InterruptedException e) { | |
| 61 | + fail("Interrupted while waiting for executor to shutdown"); | |
| 62 | + } | |
| 53 | 63 | } |
| 54 | 64 | |
| 55 | 65 | /** |
| @@ -77,10 +87,9 @@ | ||
| 77 | 87 | */ |
| 78 | 88 | @Test(groups = "long") |
| 79 | 89 | public void sessions_should_not_leak_connections() { |
| 80 | - List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress); | |
| 81 | 90 | // override inherited field with a new cluster object and ensure 0 sessions and connections |
| 82 | 91 | channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); |
| 83 | - stressCluster = Cluster.builder().addContactPointsWithPorts(contactPoints) | |
| 92 | + stressCluster = Cluster.builder().addContactPointsWithPorts(getInitialContactPoints()) | |
| 84 | 93 | .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)) |
| 85 | 94 | .withNettyOptions(channelMonitor.nettyOptions()).build(); |
| 86 | 95 | |
| @@ -97,13 +106,13 @@ | ||
| 97 | 106 | assertEquals(stressCluster.manager.sessions.size(), 1); |
| 98 | 107 | int coreConnections = TestUtils.numberOfLocalCoreConnections(stressCluster); |
| 99 | 108 | assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections); |
| 100 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections); | |
| 109 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1 + coreConnections); | |
| 101 | 110 | |
| 102 | 111 | // Closing the session keeps the control connection opened |
| 103 | 112 | session.close(); |
| 104 | 113 | assertEquals(stressCluster.manager.sessions.size(), 0); |
| 105 | 114 | assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1); |
| 106 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 115 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1); | |
| 107 | 116 | |
| 108 | 117 | int nbOfSessions = 2000; |
| 109 | 118 | int halfOfTheSessions = nbOfSessions / 2; |
| @@ -120,7 +129,7 @@ | ||
| 120 | 129 | assertEquals(stressCluster.manager.sessions.size(), nbOfSessions); |
| 121 | 130 | assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), |
| 122 | 131 | coreConnections * nbOfSessions + 1); |
| 123 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1); | |
| 132 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), coreConnections * nbOfSessions + 1); | |
| 124 | 133 | |
| 125 | 134 | // Close half of the sessions asynchronously |
| 126 | 135 | logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions); |
| @@ -130,7 +139,7 @@ | ||
| 130 | 139 | assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions); |
| 131 | 140 | assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), |
| 132 | 141 | coreConnections * (nbOfSessions / 2) + 1); |
| 133 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), | |
| 142 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), | |
| 134 | 143 | coreConnections * (nbOfSessions / 2) + 1); |
| 135 | 144 | |
| 136 | 145 | // Close and open the same number of sessions concurrently |
| @@ -148,7 +157,7 @@ | ||
| 148 | 157 | assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions); |
| 149 | 158 | assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), |
| 150 | 159 | coreConnections * (nbOfSessions / 2) + 1); |
| 151 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), | |
| 160 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), | |
| 152 | 161 | coreConnections * (nbOfSessions / 2) + 1); |
| 153 | 162 | |
| 154 | 163 | // Close the remaining sessions |
| @@ -158,7 +167,7 @@ | ||
| 158 | 167 | // Check that we have a clean state |
| 159 | 168 | assertEquals(stressCluster.manager.sessions.size(), 0); |
| 160 | 169 | assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1); |
| 161 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 170 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 1); | |
| 162 | 171 | |
| 163 | 172 | // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl) |
| 164 | 173 | logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime); |
| @@ -168,10 +177,14 @@ | ||
| 168 | 177 | stressCluster.close(); |
| 169 | 178 | |
| 170 | 179 | // Ensure no channels remain open. |
| 171 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 0); | |
| 180 | + assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0); | |
| 172 | 181 | |
| 173 | 182 | channelMonitor.stop(); |
| 174 | 183 | channelMonitor.report(); |
| 184 | + | |
| 185 | + logger.info("Sleeping 60 extra seconds"); | |
| 186 | + Uninterruptibles.sleepUninterruptibly(60, TimeUnit.SECONDS); | |
| 187 | + | |
| 175 | 188 | } |
| 176 | 189 | } |
| 177 | 190 | |
| @@ -264,4 +277,4 @@ | ||
| 264 | 277 | return session.closeAsync(); |
| 265 | 278 | } |
| 266 | 279 | } |
| 267 | -} | |
| No newline at the end of the file | ||
| 280 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +48 −46
| @@ -16,11 +16,12 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.utils.CassandraVersion; |
| 19 | -import org.slf4j.Logger; | |
| 20 | -import org.slf4j.LoggerFactory; | |
| 21 | 19 | import org.testng.annotations.Test; |
| 22 | 20 | |
| 23 | -import java.util.*; | |
| 21 | +import java.util.Arrays; | |
| 22 | +import java.util.Collection; | |
| 23 | +import java.util.List; | |
| 24 | +import java.util.Locale; | |
| 24 | 25 | import java.util.concurrent.CountDownLatch; |
| 25 | 26 | import java.util.concurrent.ExecutorService; |
| 26 | 27 | import java.util.concurrent.Executors; |
| @@ -32,9 +33,7 @@ | ||
| 32 | 33 | /** |
| 33 | 34 | * Simple test of the Sessions methods against a one node cluster. |
| 34 | 35 | */ |
| 35 | -public class SessionTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 36 | - | |
| 37 | - private static final Logger logger = LoggerFactory.getLogger(SessionTest.class); | |
| 36 | +public class SessionTest extends CCMTestsSupport { | |
| 38 | 37 | |
| 39 | 38 | private static final String TABLE1 = "test1"; |
| 40 | 39 | private static final String TABLE2 = "test2"; |
| @@ -42,7 +41,7 @@ | ||
| 42 | 41 | private static final String COUNTER_TABLE = "counters"; |
| 43 | 42 | |
| 44 | 43 | @Override |
| 45 | - protected Collection<String> getTableDefinitions() { | |
| 44 | + public Collection<String> createTestFixtures() { | |
| 46 | 45 | return Arrays.asList(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1), |
| 47 | 46 | String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE2), |
| 48 | 47 | String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE3), |
| @@ -168,49 +167,52 @@ | ||
| 168 | 167 | // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster |
| 169 | 168 | // (note the use of newSession below) |
| 170 | 169 | final Cluster cluster = Cluster.builder() |
| 171 | - .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 170 | + .addContactPointsWithPorts(getInitialContactPoints()) | |
| 172 | 171 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 173 | 172 | .build(); |
| 174 | - final Session session = cluster.newSession(); | |
| 175 | - | |
| 176 | - // Spawn two threads to simulate the race | |
| 177 | - ExecutorService executor = Executors.newFixedThreadPool(2); | |
| 178 | - final CountDownLatch startLatch = new CountDownLatch(1); | |
| 179 | - | |
| 180 | - executor.execute(new Runnable() { | |
| 181 | - @Override | |
| 182 | - public void run() { | |
| 183 | - try { | |
| 184 | - startLatch.await(); | |
| 185 | - cluster.init(); | |
| 186 | - } catch (InterruptedException e) { | |
| 187 | - fail("unexpected interruption", e); | |
| 173 | + try { | |
| 174 | + final Session session = cluster.newSession(); | |
| 175 | + | |
| 176 | + // Spawn two threads to simulate the race | |
| 177 | + ExecutorService executor = Executors.newFixedThreadPool(2); | |
| 178 | + final CountDownLatch startLatch = new CountDownLatch(1); | |
| 179 | + | |
| 180 | + executor.execute(new Runnable() { | |
| 181 | + @Override | |
| 182 | + public void run() { | |
| 183 | + try { | |
| 184 | + startLatch.await(); | |
| 185 | + cluster.init(); | |
| 186 | + } catch (InterruptedException e) { | |
| 187 | + fail("unexpected interruption", e); | |
| 188 | + } | |
| 188 | 189 | } |
| 189 | - } | |
| 190 | - }); | |
| 191 | - | |
| 192 | - executor.execute(new Runnable() { | |
| 193 | - @Override | |
| 194 | - public void run() { | |
| 195 | - try { | |
| 196 | - startLatch.await(); | |
| 197 | - TimeUnit.MILLISECONDS.sleep(10); | |
| 198 | - session.close(); | |
| 199 | - } catch (InterruptedException e) { | |
| 200 | - fail("unexpected interruption", e); | |
| 190 | + }); | |
| 191 | + | |
| 192 | + executor.execute(new Runnable() { | |
| 193 | + @Override | |
| 194 | + public void run() { | |
| 195 | + try { | |
| 196 | + startLatch.await(); | |
| 197 | + TimeUnit.MILLISECONDS.sleep(10); | |
| 198 | + session.close(); | |
| 199 | + } catch (InterruptedException e) { | |
| 200 | + fail("unexpected interruption", e); | |
| 201 | + } | |
| 201 | 202 | } |
| 202 | - } | |
| 203 | - }); | |
| 204 | - | |
| 205 | - // Start the threads | |
| 206 | - startLatch.countDown(); | |
| 207 | - | |
| 208 | - executor.shutdown(); | |
| 209 | - boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS); | |
| 210 | - assertTrue(normalShutdown); | |
| 211 | - | |
| 212 | - // The deadlock occurred here before JAVA-418 | |
| 213 | - cluster.close(); | |
| 203 | + }); | |
| 204 | + | |
| 205 | + // Start the threads | |
| 206 | + startLatch.countDown(); | |
| 207 | + | |
| 208 | + executor.shutdown(); | |
| 209 | + boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS); | |
| 210 | + assertTrue(normalShutdown); | |
| 211 | + | |
| 212 | + } finally { | |
| 213 | + // The deadlock occurred here before JAVA-418 | |
| 214 | + cluster.close(); | |
| 215 | + } | |
| 214 | 216 | } |
| 215 | 217 | } |
| 216 | 218 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +2 −9
| @@ -17,10 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.utils.CassandraVersion; |
| 19 | 19 | import org.testng.annotations.Test; |
| 20 | -import org.testng.collections.Lists; | |
| 21 | 20 | |
| 22 | -import java.net.InetSocketAddress; | |
| 23 | -import java.util.Collection; | |
| 24 | 21 | import java.util.concurrent.Executors; |
| 25 | 22 | import java.util.concurrent.ScheduledExecutorService; |
| 26 | 23 | import java.util.concurrent.TimeUnit; |
| @@ -29,11 +26,7 @@ | ||
| 29 | 26 | import static org.testng.Assert.fail; |
| 30 | 27 | |
| 31 | 28 | @CassandraVersion(major = 2.1) |
| 32 | -public class SingleConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 33 | - @Override | |
| 34 | - protected Collection<String> getTableDefinitions() { | |
| 35 | - return Lists.newArrayList(); | |
| 36 | - } | |
| 29 | +public class SingleConnectionPoolTest extends CCMTestsSupport { | |
| 37 | 30 | |
| 38 | 31 | @Test(groups = "short") |
| 39 | 32 | public void should_throttle_requests() { |
| @@ -44,7 +37,7 @@ | ||
| 44 | 37 | |
| 45 | 38 | // Track in flight requests in a dedicated thread every second |
| 46 | 39 | final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false); |
| 47 | - final Host host = cluster.getMetadata().getHost(new InetSocketAddress(CCMBridge.IP_PREFIX + "1", 9042)); | |
| 40 | + final Host host = cluster.getMetadata().getHost(ccm.addressOfNode(1)); | |
| 48 | 41 | ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1); |
| 49 | 42 | final Runnable openConnectionsWatcher = new Runnable() { |
| 50 | 43 | @Override |
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +27 −49
| @@ -23,59 +23,37 @@ | ||
| 23 | 23 | |
| 24 | 24 | import static com.datastax.driver.core.Assertions.assertThat; |
| 25 | 25 | |
| 26 | -public class SingleTokenIntegrationTest { | |
| 26 | +@CCMConfig( | |
| 27 | + // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken] | |
| 28 | + config = "initial_token:1", | |
| 29 | + clusterProvider = "createClusterBuilderNoDebouncing" | |
| 30 | +) | |
| 31 | +public class SingleTokenIntegrationTest extends CCMTestsSupport { | |
| 32 | + | |
| 27 | 33 | /** |
| 28 | 34 | * JAVA-684: Empty TokenRange returned in a one token cluster |
| 29 | 35 | */ |
| 30 | 36 | @Test(groups = "short") |
| 31 | 37 | public void should_return_single_non_empty_range_when_cluster_has_one_single_token() { |
| 32 | - CCMBridge ccm = null; | |
| 33 | - Cluster cluster = null; | |
| 34 | - | |
| 35 | - try { | |
| 36 | - ccm = CCMBridge.builder("test") | |
| 37 | - // force the initial token to a non-min value to validate that the single range will always be ]minToken, minToken] | |
| 38 | - .withCassandraConfiguration("initial_token", "1") | |
| 39 | - .build(); | |
| 40 | - | |
| 41 | - cluster = Cluster.builder() | |
| 42 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 43 | - .withQueryOptions(new QueryOptions() | |
| 44 | - .setRefreshNodeIntervalMillis(0) | |
| 45 | - .setRefreshNodeListIntervalMillis(0) | |
| 46 | - .setRefreshSchemaIntervalMillis(0) | |
| 47 | - ) | |
| 48 | - .build(); | |
| 49 | - | |
| 50 | - Session session = cluster.connect(); | |
| 51 | - session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); | |
| 52 | - | |
| 53 | - Metadata metadata = cluster.getMetadata(); | |
| 54 | - | |
| 55 | - Set<TokenRange> tokenRanges = metadata.getTokenRanges(); | |
| 56 | - assertThat(tokenRanges).hasSize(1); | |
| 57 | - TokenRange tokenRange = tokenRanges.iterator().next(); | |
| 58 | - assertThat(tokenRange) | |
| 59 | - .startsWith(Token.M3PToken.FACTORY.minToken()) | |
| 60 | - .endsWith(Token.M3PToken.FACTORY.minToken()) | |
| 61 | - .isNotEmpty() | |
| 62 | - .isNotWrappedAround(); | |
| 63 | - | |
| 64 | - Set<Host> hostsForRange = metadata.getReplicas("test", tokenRange); | |
| 65 | - Host host1 = TestUtils.findHost(cluster, 1); | |
| 66 | - assertThat(hostsForRange).containsOnly(host1); | |
| 67 | - | |
| 68 | - ByteBuffer randomPartitionKey = Bytes.fromHexString("0xCAFEBABE"); | |
| 69 | - Set<Host> hostsForKey = metadata.getReplicas("test", randomPartitionKey); | |
| 70 | - assertThat(hostsForKey).containsOnly(host1); | |
| 71 | - | |
| 72 | - Set<TokenRange> rangesForHost = metadata.getTokenRanges("test", host1); | |
| 73 | - assertThat(rangesForHost).containsOnly(tokenRange); | |
| 74 | - } finally { | |
| 75 | - if (cluster != null) | |
| 76 | - cluster.close(); | |
| 77 | - if (ccm != null) | |
| 78 | - ccm.remove(); | |
| 79 | - } | |
| 38 | + Metadata metadata = cluster.getMetadata(); | |
| 39 | + Set<TokenRange> tokenRanges = metadata.getTokenRanges(); | |
| 40 | + assertThat(tokenRanges).hasSize(1); | |
| 41 | + TokenRange tokenRange = tokenRanges.iterator().next(); | |
| 42 | + assertThat(tokenRange) | |
| 43 | + .startsWith(Token.M3PToken.FACTORY.minToken()) | |
| 44 | + .endsWith(Token.M3PToken.FACTORY.minToken()) | |
| 45 | + .isNotEmpty() | |
| 46 | + .isNotWrappedAround(); | |
| 47 | + | |
| 48 | + Set<Host> hostsForRange = metadata.getReplicas(keyspace, tokenRange); | |
| 49 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 50 | + assertThat(hostsForRange).containsOnly(host1); | |
| 51 | + | |
| 52 | + ByteBuffer randomPartitionKey = Bytes.fromHexString("0xCAFEBABE"); | |
| 53 | + Set<Host> hostsForKey = metadata.getReplicas(keyspace, randomPartitionKey); | |
| 54 | + assertThat(hostsForKey).containsOnly(host1); | |
| 55 | + | |
| 56 | + Set<TokenRange> rangesForHost = metadata.getTokenRanges(keyspace, host1); | |
| 57 | + assertThat(rangesForHost).containsOnly(tokenRange); | |
| 80 | 58 | } |
| 81 | 59 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionIntegrationTest.java +4 −4
| @@ -30,19 +30,19 @@ | ||
| 30 | 30 | * Test that needs a real CCM cluster (as opposed to SCassandra for other specex tests), because |
| 31 | 31 | * it uses a protocol v3 feature. |
| 32 | 32 | */ |
| 33 | -public class SpeculativeExecutionIntegrationTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 33 | +public class SpeculativeExecutionIntegrationTest extends CCMTestsSupport { | |
| 34 | 34 | |
| 35 | 35 | TimestampGenerator timestampGenerator; |
| 36 | 36 | |
| 37 | 37 | @Override |
| 38 | - protected Collection<String> getTableDefinitions() { | |
| 38 | + public Collection<String> createTestFixtures() { | |
| 39 | 39 | return Lists.newArrayList("create table foo(k int primary key, v int)"); |
| 40 | 40 | } |
| 41 | 41 | |
| 42 | 42 | @Override |
| 43 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 43 | + public Cluster.Builder createClusterBuilder() { | |
| 44 | 44 | timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE); |
| 45 | - return builder | |
| 45 | + return Cluster.builder() | |
| 46 | 46 | .withTimestampGenerator(timestampGenerator) |
| 47 | 47 | .withQueryOptions(new QueryOptions().setDefaultIdempotence(true)) |
| 48 | 48 | // Set an artificially low timeout to force speculative execution |
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +5 −3
| @@ -50,7 +50,8 @@ | ||
| 50 | 50 | |
| 51 | 51 | loadBalancingPolicy = new SortingLoadBalancingPolicy(); |
| 52 | 52 | cluster = Cluster.builder() |
| 53 | - .addContactPoint(scassandras.address(2)) | |
| 53 | + .addContactPointsWithPorts(scassandras.address(2)) | |
| 54 | + .withAddressTranslater(scassandras.addressTranslator()) | |
| 54 | 55 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 55 | 56 | .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1)) |
| 56 | 57 | .withQueryOptions(new QueryOptions().setDefaultIdempotence(true)) |
| @@ -67,7 +68,7 @@ | ||
| 67 | 68 | errors = cluster.getMetrics().getErrorMetrics(); |
| 68 | 69 | } |
| 69 | 70 | |
| 70 | - @AfterMethod(groups = "short") | |
| 71 | + @AfterMethod(groups = "short", alwaysRun = true) | |
| 71 | 72 | public void afterMethod() { |
| 72 | 73 | if (cluster != null) |
| 73 | 74 | cluster.close(); |
| @@ -200,7 +201,8 @@ | ||
| 200 | 201 | SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class); |
| 201 | 202 | |
| 202 | 203 | Cluster cluster = Cluster.builder() |
| 203 | - .addContactPoint(CCMBridge.ipOfNode(2)) | |
| 204 | + .addContactPointsWithPorts(scassandras.address(2)) | |
| 205 | + .withAddressTranslater(scassandras.addressTranslator()) | |
| 204 | 206 | .withSpeculativeExecutionPolicy(mockPolicy) |
| 205 | 207 | .build(); |
| 206 | 208 |
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +20 −30
| @@ -21,48 +21,38 @@ | ||
| 21 | 21 | |
| 22 | 22 | import java.util.concurrent.CountDownLatch; |
| 23 | 23 | |
| 24 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 24 | 25 | import static com.datastax.driver.core.StateListenerTest.TestListener.Event.*; |
| 25 | 26 | import static java.util.concurrent.TimeUnit.MINUTES; |
| 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; |
| 27 | 28 | |
| 28 | -public class StateListenerTest { | |
| 29 | +@CreateCCM(PER_METHOD) | |
| 30 | +@CCMConfig(dirtiesContext = true, createSession = false) | |
| 31 | +public class StateListenerTest extends CCMTestsSupport { | |
| 32 | + | |
| 29 | 33 | private static final Logger logger = LoggerFactory.getLogger(StateListenerTest.class); |
| 30 | 34 | |
| 31 | 35 | @Test(groups = "long") |
| 32 | 36 | public void should_receive_events_when_node_states_change() throws InterruptedException { |
| 33 | - CCMBridge ccm = null; | |
| 34 | - Cluster cluster = null; | |
| 35 | - try { | |
| 36 | - ccm = CCMBridge.builder("test").build(); | |
| 37 | - cluster = Cluster.builder() | |
| 38 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 39 | - .build(); | |
| 40 | - cluster.init(); | |
| 41 | - TestListener listener = new TestListener(); | |
| 42 | - cluster.register(listener); | |
| 43 | - | |
| 44 | - listener.setExpectedEvent(ADD); | |
| 45 | - ccm.bootstrapNode(2); | |
| 46 | - listener.waitForEvent(); | |
| 37 | + TestListener listener = new TestListener(); | |
| 38 | + cluster.register(listener); | |
| 47 | 39 | |
| 48 | - listener.setExpectedEvent(DOWN); | |
| 49 | - ccm.forceStop(1); | |
| 50 | - listener.waitForEvent(); | |
| 40 | + listener.setExpectedEvent(ADD); | |
| 41 | + ccm.add(2); | |
| 42 | + ccm.start(2); | |
| 43 | + listener.waitForEvent(); | |
| 51 | 44 | |
| 52 | - listener.setExpectedEvent(UP); | |
| 53 | - ccm.start(1); | |
| 54 | - listener.waitForEvent(); | |
| 45 | + listener.setExpectedEvent(DOWN); | |
| 46 | + ccm.forceStop(1); | |
| 47 | + listener.waitForEvent(); | |
| 55 | 48 | |
| 56 | - listener.setExpectedEvent(REMOVE); | |
| 57 | - ccm.decommissionNode(2); | |
| 58 | - listener.waitForEvent(); | |
| 49 | + listener.setExpectedEvent(UP); | |
| 50 | + ccm.start(1); | |
| 51 | + listener.waitForEvent(); | |
| 59 | 52 | |
| 60 | - } finally { | |
| 61 | - if (cluster != null) | |
| 62 | - cluster.close(); | |
| 63 | - if (ccm != null) | |
| 64 | - ccm.remove(); | |
| 65 | - } | |
| 53 | + listener.setExpectedEvent(REMOVE); | |
| 54 | + ccm.decommissionNode(2); | |
| 55 | + listener.waitForEvent(); | |
| 66 | 56 | } |
| 67 | 57 | |
| 68 | 58 | static class TestListener implements Host.StateListener { |
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +4 −10
| @@ -16,28 +16,22 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.policies.*; |
| 19 | -import com.google.common.collect.Lists; | |
| 20 | 19 | import org.testng.annotations.Test; |
| 21 | 20 | |
| 22 | -import java.util.Collection; | |
| 23 | 21 | import java.util.Iterator; |
| 24 | 22 | import java.util.concurrent.atomic.AtomicInteger; |
| 25 | 23 | |
| 26 | 24 | import static org.assertj.core.api.Assertions.assertThat; |
| 27 | 25 | |
| 28 | -public class StatementWrapperTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 29 | - @Override | |
| 30 | - protected Collection<String> getTableDefinitions() { | |
| 31 | - return Lists.newArrayList(); | |
| 32 | - } | |
| 26 | +public class StatementWrapperTest extends CCMTestsSupport { | |
| 33 | 27 | |
| 34 | 28 | CustomLoadBalancingPolicy loadBalancingPolicy = new CustomLoadBalancingPolicy(); |
| 35 | 29 | CustomSpeculativeExecutionPolicy speculativeExecutionPolicy = new CustomSpeculativeExecutionPolicy(); |
| 36 | 30 | CustomRetryPolicy retryPolicy = new CustomRetryPolicy(); |
| 37 | 31 | |
| 38 | 32 | @Override |
| 39 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 40 | - return builder | |
| 33 | + public Cluster.Builder createClusterBuilder() { | |
| 34 | + return Cluster.builder() | |
| 41 | 35 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 42 | 36 | .withSpeculativeExecutionPolicy(speculativeExecutionPolicy) |
| 43 | 37 | .withRetryPolicy(retryPolicy); |
| @@ -151,4 +145,4 @@ | ||
| 151 | 145 | return RetryDecision.rethrow(); |
| 152 | 146 | } |
| 153 | 147 | } |
| 154 | -} | |
| No newline at the end of the file | ||
| 148 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +3 −11
| @@ -22,9 +22,10 @@ | ||
| 22 | 22 | |
| 23 | 23 | import static org.assertj.core.api.Assertions.assertThat; |
| 24 | 24 | |
| 25 | -public class TableMetadataTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 25 | +@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing") | |
| 26 | +public class TableMetadataTest extends CCMTestsSupport { | |
| 26 | 27 | @Override |
| 27 | - protected Collection<String> getTableDefinitions() { | |
| 28 | + public Collection<String> createTestFixtures() { | |
| 28 | 29 | return Lists.newArrayList( |
| 29 | 30 | "CREATE TABLE single_quote (\n" |
| 30 | 31 | + " c1 int PRIMARY KEY\n" |
| @@ -32,15 +33,6 @@ | ||
| 32 | 33 | ); |
| 33 | 34 | } |
| 34 | 35 | |
| 35 | - @Override | |
| 36 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 37 | - return builder.withQueryOptions(new QueryOptions() | |
| 38 | - .setRefreshNodeIntervalMillis(0) | |
| 39 | - .setRefreshNodeListIntervalMillis(0) | |
| 40 | - .setRefreshSchemaIntervalMillis(0) | |
| 41 | - ); | |
| 42 | - } | |
| 43 | - | |
| 44 | 36 | @Test(groups = "short") |
| 45 | 37 | public void should_escape_single_quote_table_comment() { |
| 46 | 38 | TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote"); |
modified driver-core/src/test/java/com/datastax/driver/core/TestListener.java +7 −8
| @@ -32,10 +32,9 @@ | ||
| 32 | 32 | public void onTestFailure(ITestResult tr) { |
| 33 | 33 | long elapsedTime = TimeUnit.NANOSECONDS.toSeconds((System.nanoTime() - start_time)); |
| 34 | 34 | long testTime = tr.getEndMillis() - tr.getStartMillis(); |
| 35 | - | |
| 36 | 35 | tr.getThrowable().printStackTrace(); |
| 37 | - System.out.println("FAILED: " + tr.getName()); | |
| 38 | - System.out.println("Test: " + formatIntoHHMMSS(testTime / 1000)); | |
| 36 | + System.out.println("FAILED : " + tr.getName()); | |
| 37 | + System.out.println("Test : " + formatIntoHHMMSS(testTime / 1000)); | |
| 39 | 38 | System.out.println("Elapsed: " + formatIntoHHMMSS(elapsedTime)); |
| 40 | 39 | System.out.println(); |
| 41 | 40 | } |
| @@ -44,9 +43,8 @@ | ||
| 44 | 43 | public void onTestSkipped(ITestResult tr) { |
| 45 | 44 | long elapsedTime = TimeUnit.NANOSECONDS.toSeconds((System.nanoTime() - start_time)); |
| 46 | 45 | long testTime = tr.getEndMillis() - tr.getStartMillis(); |
| 47 | - | |
| 48 | 46 | System.out.println("SKIPPED: " + tr.getName()); |
| 49 | - System.out.println("Test: " + formatIntoHHMMSS(testTime / 1000)); | |
| 47 | + System.out.println("Test : " + formatIntoHHMMSS(testTime / 1000)); | |
| 50 | 48 | System.out.println("Elapsed: " + formatIntoHHMMSS(elapsedTime)); |
| 51 | 49 | System.out.println(); |
| 52 | 50 | } |
| @@ -55,15 +53,16 @@ | ||
| 55 | 53 | public void onTestSuccess(ITestResult tr) { |
| 56 | 54 | long elapsedTime = TimeUnit.NANOSECONDS.toSeconds((System.nanoTime() - start_time)); |
| 57 | 55 | long testTime = tr.getEndMillis() - tr.getStartMillis(); |
| 58 | - | |
| 59 | 56 | System.out.println("SUCCESS: " + tr.getName()); |
| 60 | - System.out.println("Test: " + formatIntoHHMMSS(testTime / 1000)); | |
| 57 | + System.out.println("Test : " + formatIntoHHMMSS(testTime / 1000)); | |
| 61 | 58 | System.out.println("Elapsed: " + formatIntoHHMMSS(elapsedTime)); |
| 62 | - System.out.println("\n"); | |
| 59 | + System.out.println(); | |
| 63 | 60 | } |
| 64 | 61 | |
| 65 | 62 | @Override |
| 66 | 63 | public void onTestStart(ITestResult tr) { |
| 64 | + System.out.println(); | |
| 65 | + System.out.println("-----------------------------------------------"); | |
| 67 | 66 | System.out.println("Starting " + tr.getTestClass().getName() + '.' + tr.getName() + " [Test #" + ++test_index + "]..."); |
| 68 | 67 | } |
| 69 | 68 |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +187 −92
| @@ -17,8 +17,10 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.policies.RoundRobinPolicy; |
| 19 | 19 | import com.datastax.driver.core.policies.WhiteListPolicy; |
| 20 | +import com.google.common.base.Predicate; | |
| 20 | 21 | import com.google.common.util.concurrent.Futures; |
| 21 | 22 | import com.google.common.util.concurrent.Uninterruptibles; |
| 23 | +import com.sun.management.OperatingSystemMXBean; | |
| 22 | 24 | import io.netty.channel.EventLoopGroup; |
| 23 | 25 | import org.scassandra.Scassandra; |
| 24 | 26 | import org.scassandra.ScassandraFactory; |
| @@ -26,21 +28,36 @@ | ||
| 26 | 28 | import org.slf4j.LoggerFactory; |
| 27 | 29 | |
| 28 | 30 | import java.io.IOException; |
| 31 | +import java.lang.management.ManagementFactory; | |
| 29 | 32 | import java.math.BigDecimal; |
| 30 | 33 | import java.math.BigInteger; |
| 31 | 34 | import java.net.InetAddress; |
| 32 | 35 | import java.net.InetSocketAddress; |
| 33 | 36 | import java.net.ServerSocket; |
| 37 | +import java.net.Socket; | |
| 34 | 38 | import java.nio.ByteBuffer; |
| 35 | 39 | import java.util.*; |
| 40 | +import java.util.concurrent.Callable; | |
| 36 | 41 | import java.util.concurrent.CountDownLatch; |
| 37 | 42 | import java.util.concurrent.TimeUnit; |
| 43 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 44 | +import java.util.concurrent.locks.ReentrantLock; | |
| 38 | 45 | |
| 39 | 46 | /** |
| 40 | 47 | * A number of static fields/methods handy for tests. |
| 41 | 48 | */ |
| 42 | 49 | public abstract class TestUtils { |
| 43 | 50 | |
| 51 | + public static final String IP_PREFIX; | |
| 52 | + | |
| 53 | + static { | |
| 54 | + String ip_prefix = System.getProperty("ipprefix"); | |
| 55 | + if (ip_prefix == null || ip_prefix.isEmpty()) { | |
| 56 | + ip_prefix = "127.0.1."; | |
| 57 | + } | |
| 58 | + IP_PREFIX = ip_prefix; | |
| 59 | + } | |
| 60 | + | |
| 44 | 61 | private static final Logger logger = LoggerFactory.getLogger(TestUtils.class); |
| 45 | 62 | |
| 46 | 63 | public static final String CREATE_KEYSPACE_SIMPLE_FORMAT = "CREATE KEYSPACE %s WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %d }"; |
| @@ -56,6 +73,8 @@ | ||
| 56 | 73 | |
| 57 | 74 | public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60); |
| 58 | 75 | |
| 76 | + private static final AtomicInteger KS_COUNTER = new AtomicInteger(1); | |
| 77 | + | |
| 59 | 78 | @SuppressWarnings({"unchecked", "rawtypes"}) |
| 60 | 79 | public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) { |
| 61 | 80 | switch (type.getName()) { |
| @@ -286,114 +305,99 @@ | ||
| 286 | 305 | // This is used because there is some delay between when a node has been |
| 287 | 306 | // added through ccm and when it's actually available for querying |
| 288 | 307 | public static void waitFor(String node, Cluster cluster) { |
| 289 | - waitFor(node, cluster, TEST_BASE_NODE_WAIT, false, false); | |
| 308 | + waitFor(node, cluster, TEST_BASE_NODE_WAIT, false); | |
| 290 | 309 | } |
| 291 | 310 | |
| 292 | 311 | public static void waitFor(String node, Cluster cluster, int maxTry) { |
| 293 | - waitFor(node, cluster, maxTry, false, false); | |
| 312 | + waitFor(node, cluster, maxTry, false); | |
| 294 | 313 | } |
| 295 | 314 | |
| 296 | 315 | public static void waitForDown(String node, Cluster cluster) { |
| 297 | - waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true, false); | |
| 298 | - } | |
| 299 | - | |
| 300 | - public static void waitForDownWithWait(String node, Cluster cluster, int waitTime) { | |
| 301 | - waitForDown(node, cluster); | |
| 302 | - | |
| 303 | - // FIXME: Once stop() works, remove this line | |
| 304 | - try { | |
| 305 | - Thread.sleep(waitTime * 1000); | |
| 306 | - } catch (InterruptedException e) { | |
| 307 | - e.printStackTrace(); | |
| 308 | - } | |
| 316 | + waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true); | |
| 309 | 317 | } |
| 310 | 318 | |
| 311 | 319 | public static void waitForDown(String node, Cluster cluster, int maxTry) { |
| 312 | - waitFor(node, cluster, maxTry, true, false); | |
| 313 | - } | |
| 314 | - | |
| 315 | - public static void stopAndWait(CCMBridge.CCMCluster c, int node) { | |
| 316 | - c.cassandraCluster.stop(node); | |
| 317 | - waitForDownWithWait(CCMBridge.IP_PREFIX + node, c.cluster, 5); | |
| 320 | + waitFor(node, cluster, maxTry, true); | |
| 318 | 321 | } |
| 319 | 322 | |
| 320 | 323 | public static void waitForDecommission(String node, Cluster cluster) { |
| 321 | - waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true, true); | |
| 324 | + waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true); | |
| 322 | 325 | } |
| 323 | 326 | |
| 324 | 327 | public static void waitForDecommission(String node, Cluster cluster, int maxTry) { |
| 325 | - waitFor(node, cluster, maxTry, true, true); | |
| 328 | + waitFor(node, cluster, maxTry, true); | |
| 326 | 329 | } |
| 327 | 330 | |
| 328 | - private static void waitFor(String node, Cluster cluster, int maxTry, boolean waitForDead, boolean waitForOut) { | |
| 329 | - if (waitForDead || waitForOut) | |
| 330 | - if (waitForDead) | |
| 331 | - logger.info("Waiting for stopped node: " + node); | |
| 332 | - else if (waitForOut) | |
| 333 | - logger.info("Waiting for decommissioned node: " + node); | |
| 334 | - else | |
| 335 | - logger.info("Waiting for upcoming node: " + node); | |
| 336 | - | |
| 331 | + private static void waitFor(String node, Cluster cluster, int timeoutSeconds, boolean waitForDown) { | |
| 332 | + if (waitForDown) | |
| 333 | + logger.debug("Waiting for node to leave: {}", node); | |
| 334 | + else | |
| 335 | + logger.debug("Waiting for upcoming node: {}", node); | |
| 337 | 336 | // In the case where the we've killed the last node in the cluster, if we haven't |
| 338 | 337 | // tried doing an actual query, the driver won't realize that last node is dead until |
| 339 | 338 | // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force |
| 340 | 339 | // the detection by forcing a request. |
| 341 | - if (waitForDead || waitForOut) { | |
| 340 | + if (waitForDown) { | |
| 342 | 341 | Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null, null)); |
| 343 | 342 | } |
| 343 | + if (waitForDown) { | |
| 344 | + ConditionChecker.awaitUntil(new HostIsDownCondition(cluster, node), timeoutSeconds * 1000); | |
| 345 | + } else { | |
| 346 | + ConditionChecker.awaitUntil(new HostIsUpCondition(cluster, node), timeoutSeconds * 1000); | |
| 347 | + } | |
| 348 | + } | |
| 344 | 349 | |
| 345 | - InetAddress address; | |
| 346 | - try { | |
| 347 | - address = InetAddress.getByName(node); | |
| 348 | - } catch (Exception e) { | |
| 349 | - // That's a problem but that's not *our* problem | |
| 350 | - return; | |
| 350 | + private static class HostIsDownCondition implements Callable<Boolean> { | |
| 351 | + | |
| 352 | + private final Cluster cluster; | |
| 353 | + | |
| 354 | + private final String ip; | |
| 355 | + | |
| 356 | + public HostIsDownCondition(Cluster cluster, String ip) { | |
| 357 | + this.cluster = cluster; | |
| 358 | + this.ip = ip; | |
| 351 | 359 | } |
| 352 | 360 | |
| 353 | - Metadata metadata = cluster.getMetadata(); | |
| 354 | - for (int i = 0; i < maxTry; ++i) { | |
| 355 | - for (Host host : metadata.getAllHosts()) { | |
| 356 | - if (host.getAddress().equals(address) && testHost(host, waitForDead)) { | |
| 357 | - try { | |
| 358 | - Thread.sleep(10000); | |
| 359 | - } catch (Exception e) { | |
| 360 | - } | |
| 361 | - return; | |
| 362 | - } | |
| 363 | - } | |
| 364 | - try { | |
| 365 | - Thread.sleep(1000); | |
| 366 | - } catch (Exception e) { | |
| 367 | - } | |
| 361 | + @Override | |
| 362 | + public Boolean call() throws Exception { | |
| 363 | + final Host host = findHost(cluster, ip); | |
| 364 | + return host == null || !host.isUp(); | |
| 368 | 365 | } |
| 366 | + } | |
| 369 | 367 | |
| 370 | - for (Host host : metadata.getAllHosts()) { | |
| 371 | - if (host.getAddress().equals(address)) { | |
| 372 | - if (testHost(host, waitForDead)) { | |
| 373 | - return; | |
| 374 | - } else { | |
| 375 | - // logging it because this give use the timestamp of when this happens | |
| 376 | - logger.info(node + " is not " + (waitForDead ? "DOWN" : "UP") + " after " + maxTry + 's'); | |
| 377 | - throw new IllegalStateException(node + " is not " + (waitForDead ? "DOWN" : "UP") + " after " + maxTry + 's'); | |
| 378 | - } | |
| 379 | - } | |
| 368 | + private static class HostIsUpCondition implements Callable<Boolean> { | |
| 369 | + | |
| 370 | + private final Cluster cluster; | |
| 371 | + | |
| 372 | + private final String ip; | |
| 373 | + | |
| 374 | + public HostIsUpCondition(Cluster cluster, String ip) { | |
| 375 | + this.cluster = cluster; | |
| 376 | + this.ip = ip; | |
| 380 | 377 | } |
| 381 | 378 | |
| 382 | - if (waitForOut) { | |
| 383 | - return; | |
| 384 | - } else { | |
| 385 | - logger.info(node + " is not part of the cluster after " + maxTry + 's'); | |
| 386 | - throw new IllegalStateException(node + " is not part of the cluster after " + maxTry + 's'); | |
| 379 | + @Override | |
| 380 | + public Boolean call() throws Exception { | |
| 381 | + final Host host = findHost(cluster, ip); | |
| 382 | + return host != null && host.isUp(); | |
| 387 | 383 | } |
| 388 | 384 | } |
| 389 | 385 | |
| 390 | - private static boolean testHost(Host host, boolean testForDown) { | |
| 391 | - return testForDown ? !host.isUp() : host.isUp(); | |
| 386 | + /** | |
| 387 | + * Returns the IP of the {@code nth} host in the CCM cluster (counting from 1, i.e., | |
| 388 | + * {@code ipOfNode(1)} returns the IP of the first node. | |
| 389 | + * <p/> | |
| 390 | + * In multi-DC setups, nodes are numbered in ascending order of their datacenter number. | |
| 391 | + * E.g. with 2 DCs and 3 nodes in each DC, the first node in DC 2 is number 4. | |
| 392 | + * | |
| 393 | + * @return the IP of the {@code nth} host in the cluster. | |
| 394 | + */ | |
| 395 | + public static String ipOfNode(int n) { | |
| 396 | + return IP_PREFIX + n; | |
| 392 | 397 | } |
| 393 | 398 | |
| 394 | - | |
| 395 | 399 | public static Host findOrWaitForHost(Cluster cluster, int node, long duration, TimeUnit unit) { |
| 396 | - return findOrWaitForHost(cluster, CCMBridge.ipOfNode(node), duration, unit); | |
| 400 | + return findOrWaitForHost(cluster, ipOfNode(node), duration, unit); | |
| 397 | 401 | } |
| 398 | 402 | |
| 399 | 403 | public static Host findOrWaitForHost(final Cluster cluster, final String address, long duration, TimeUnit unit) { |
| @@ -425,7 +429,7 @@ | ||
| 425 | 429 | } |
| 426 | 430 | |
| 427 | 431 | public static Host findHost(Cluster cluster, int hostNumber) { |
| 428 | - return findHost(cluster, CCMBridge.ipOfNode(hostNumber)); | |
| 432 | + return findHost(cluster, ipOfNode(hostNumber)); | |
| 429 | 433 | } |
| 430 | 434 | |
| 431 | 435 | public static Host findHost(Cluster cluster, String address) { |
| @@ -467,29 +471,95 @@ | ||
| 467 | 471 | * 8052-8152. |
| 468 | 472 | */ |
| 469 | 473 | public static Scassandra createScassandraServer() { |
| 470 | - int binaryPort = findAvailablePort(8042); | |
| 471 | - int adminPort = findAvailablePort(8052); | |
| 472 | - return ScassandraFactory.createServer(binaryPort, adminPort); | |
| 474 | + int binaryPort = findAvailablePort(); | |
| 475 | + int adminPort = findAvailablePort(); | |
| 476 | + return ScassandraFactory.createServer(ipOfNode(1), binaryPort, ipOfNode(1), adminPort); | |
| 477 | + } | |
| 478 | + | |
| 479 | + public static String getAvailableKeyspaceName() { | |
| 480 | + return SIMPLE_KEYSPACE + "_" + KS_COUNTER.getAndIncrement(); | |
| 473 | 481 | } |
| 474 | 482 | |
| 483 | + // use ports in the ephemeral range | |
| 484 | + private static int nextPort = 50000; | |
| 485 | + | |
| 486 | + private static final ReentrantLock PORT_LOCK = new ReentrantLock(); | |
| 487 | + | |
| 475 | 488 | /** |
| 476 | - * @param startingWith The first port to try, if unused will keep trying the next port until one is found up to | |
| 477 | - * 100 subsequent ports. | |
| 489 | + * Find an available port in the ephemeral range. | |
| 490 | + * | |
| 478 | 491 | * @return A local port that is currently unused. |
| 479 | 492 | */ |
| 480 | - public static int findAvailablePort(int startingWith) { | |
| 481 | - IOException last = null; | |
| 482 | - for (int port = startingWith; port < startingWith + 100; port++) { | |
| 483 | - try { | |
| 484 | - ServerSocket s = new ServerSocket(port); | |
| 485 | - s.close(); | |
| 486 | - return port; | |
| 487 | - } catch (IOException e) { | |
| 488 | - last = e; | |
| 493 | + public static int findAvailablePort() { | |
| 494 | + PORT_LOCK.lock(); | |
| 495 | + try { | |
| 496 | + for (int i = 0; i < 3; i++) { | |
| 497 | + int port = nextPort; | |
| 498 | + ServerSocket s = null; | |
| 499 | + for (int j = 0; j < 100; j++) { | |
| 500 | + try { | |
| 501 | + s = new ServerSocket(port); | |
| 502 | + s.close(); | |
| 503 | + nextPort = port + 1; | |
| 504 | + return port; | |
| 505 | + } catch (IOException e) { | |
| 506 | + // ok | |
| 507 | + } finally { | |
| 508 | + port++; | |
| 509 | + if (s != null) { | |
| 510 | + try { | |
| 511 | + s.close(); | |
| 512 | + } catch (IOException e) { | |
| 513 | + // ok | |
| 514 | + } | |
| 515 | + } | |
| 516 | + } | |
| 517 | + } | |
| 518 | + logger.warn("Could not acquire an available port after 100 attempts, sleeping for 1 minute"); | |
| 519 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES); | |
| 489 | 520 | } |
| 521 | + throw new RuntimeException(String.format("Could not acquire an available port within range: %s-%s", nextPort, nextPort + 100)); | |
| 522 | + } finally { | |
| 523 | + PORT_LOCK.unlock(); | |
| 524 | + } | |
| 525 | + } | |
| 526 | + | |
| 527 | + private static final Predicate<InetSocketAddress> PORT_IS_UP = new Predicate<InetSocketAddress>() { | |
| 528 | + | |
| 529 | + @Override | |
| 530 | + public boolean apply(InetSocketAddress address) { | |
| 531 | + return pingPort(address.getAddress(), address.getPort()); | |
| 532 | + } | |
| 533 | + | |
| 534 | + }; | |
| 535 | + | |
| 536 | + public static void waitUntilPortIsUp(InetSocketAddress address) { | |
| 537 | + ConditionChecker.awaitUntil(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10)); | |
| 538 | + } | |
| 539 | + | |
| 540 | + public static void waitUntilPortIsDown(InetSocketAddress address) { | |
| 541 | + ConditionChecker.awaitWhile(address, PORT_IS_UP, TimeUnit.SECONDS.toMillis(10)); | |
| 542 | + } | |
| 543 | + | |
| 544 | + public static boolean pingPort(InetAddress address, int port) { | |
| 545 | + logger.debug("Trying {}:{}...", address, port); | |
| 546 | + boolean connectionSuccessful = false; | |
| 547 | + Socket socket = null; | |
| 548 | + try { | |
| 549 | + socket = new Socket(address, port); | |
| 550 | + connectionSuccessful = true; | |
| 551 | + logger.debug("Successfully connected"); | |
| 552 | + } catch (IOException e) { | |
| 553 | + logger.debug("Connection failed"); | |
| 554 | + } finally { | |
| 555 | + if (socket != null) | |
| 556 | + try { | |
| 557 | + socket.close(); | |
| 558 | + } catch (IOException e) { | |
| 559 | + logger.warn("Error closing socket to " + address); | |
| 560 | + } | |
| 490 | 561 | } |
| 491 | - // If for whatever reason a port could not be acquired throw the last encountered exception. | |
| 492 | - throw new RuntimeException("Could not acquire an available port", last); | |
| 562 | + return connectionSuccessful; | |
| 493 | 563 | } |
| 494 | 564 | |
| 495 | 565 | /** |
| @@ -509,19 +579,20 @@ | ||
| 509 | 579 | } |
| 510 | 580 | |
| 511 | 581 | /** |
| 512 | - * @return a {@Cluster} instance that connects only to the control host of the given cluster. | |
| 582 | + * @return a {@link Cluster} instance that connects only to the control host of the given cluster. | |
| 513 | 583 | */ |
| 514 | - public static Cluster buildControlCluster(Cluster cluster) { | |
| 584 | + public static Cluster buildControlCluster(Cluster cluster, CCMBridge ccm) { | |
| 515 | 585 | Host controlHost = cluster.manager.controlConnection.connectedHost(); |
| 516 | 586 | List<InetSocketAddress> singleAddress = Collections.singletonList(controlHost.getSocketAddress()); |
| 517 | 587 | return Cluster.builder() |
| 518 | 588 | .addContactPointsWithPorts(singleAddress) |
| 589 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 519 | 590 | .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress)) |
| 520 | 591 | .build(); |
| 521 | 592 | } |
| 522 | 593 | |
| 523 | 594 | /** |
| 524 | - * @return a {@QueryOptions} that disables debouncing by setting intervals to 0ms. | |
| 595 | + * @return a {@link QueryOptions} that disables debouncing by setting intervals to 0ms. | |
| 525 | 596 | */ |
| 526 | 597 | public static QueryOptions nonDebouncingQueryOptions() { |
| 527 | 598 | return new QueryOptions().setRefreshNodeIntervalMillis(0) |
| @@ -540,4 +611,28 @@ | ||
| 540 | 611 | eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly(); |
| 541 | 612 | } |
| 542 | 613 | }; |
| 614 | + | |
| 615 | + public static void executeNoFail(Runnable task, boolean logException) { | |
| 616 | + try { | |
| 617 | + task.run(); | |
| 618 | + } catch (Exception e) { | |
| 619 | + if (logException) | |
| 620 | + logger.error(e.getMessage(), e); | |
| 621 | + } | |
| 622 | + } | |
| 623 | + | |
| 624 | + public static void executeNoFail(Callable<?> task, boolean logException) { | |
| 625 | + try { | |
| 626 | + task.call(); | |
| 627 | + } catch (Exception e) { | |
| 628 | + if (logException) | |
| 629 | + logger.error(e.getMessage(), e); | |
| 630 | + } | |
| 631 | + } | |
| 632 | + | |
| 633 | + public static long getFreeMemoryMB() { | |
| 634 | + OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); | |
| 635 | + return (bean.getFreePhysicalMemorySize() + bean.getFreeSwapSpaceSize()) / 1024 / 1024; | |
| 636 | + } | |
| 637 | + | |
| 543 | 638 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +32 −69
| @@ -26,20 +26,20 @@ | ||
| 26 | 26 | import io.netty.channel.socket.SocketChannel; |
| 27 | 27 | import org.slf4j.Logger; |
| 28 | 28 | import org.slf4j.LoggerFactory; |
| 29 | -import org.testng.annotations.AfterClass; | |
| 30 | -import org.testng.annotations.BeforeClass; | |
| 31 | 29 | import org.testng.annotations.Test; |
| 32 | 30 | |
| 33 | -import java.net.InetSocketAddress; | |
| 34 | 31 | import java.util.Collection; |
| 35 | -import java.util.List; | |
| 36 | -import java.util.concurrent.*; | |
| 32 | +import java.util.concurrent.ExecutorService; | |
| 33 | +import java.util.concurrent.Executors; | |
| 34 | +import java.util.concurrent.Semaphore; | |
| 35 | +import java.util.concurrent.TimeUnit; | |
| 37 | 36 | import java.util.concurrent.atomic.AtomicBoolean; |
| 38 | 37 | import java.util.concurrent.atomic.AtomicInteger; |
| 39 | 38 | |
| 40 | 39 | import static com.datastax.driver.core.Assertions.assertThat; |
| 41 | 40 | |
| 42 | -public class TimeoutStressTest { | |
| 41 | +@CCMConfig(numberOfNodes = 3) | |
| 42 | +public class TimeoutStressTest extends CCMTestsSupport { | |
| 43 | 43 | |
| 44 | 44 | static final Logger logger = LoggerFactory.getLogger(TimeoutStressTest.class); |
| 45 | 45 | |
| @@ -56,50 +56,31 @@ | ||
| 56 | 56 | // Configured connection timeout - this may need to be tuned to the host system running the test. |
| 57 | 57 | static final int CONNECTION_TIMEOUT_IN_MS = 20; |
| 58 | 58 | |
| 59 | - // Keyspace to use. | |
| 60 | - static final String KEYSPACE = "testks"; | |
| 59 | + private static AtomicInteger executedQueries = new AtomicInteger(0); | |
| 61 | 60 | |
| 62 | - static Cluster cluster; | |
| 63 | - | |
| 64 | - static CCMBridge ccmBridge; | |
| 65 | - | |
| 66 | - static SocketChannelMonitor channelMonitor; | |
| 67 | - | |
| 68 | - static AtomicInteger executedQueries = new AtomicInteger(0); | |
| 69 | - | |
| 70 | - static List<InetSocketAddress> nodes; | |
| 71 | - | |
| 72 | - @BeforeClass(groups = "stress") | |
| 73 | - public void beforeClass() throws Exception { | |
| 74 | - ccmBridge = CCMBridge.builder("test").withNodes(3).build(); | |
| 75 | - channelMonitor = new SocketChannelMonitor(); | |
| 76 | - nodes = Lists.newArrayList( | |
| 77 | - new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042), | |
| 78 | - new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042), | |
| 79 | - new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042) | |
| 80 | - ); | |
| 61 | + private SocketChannelMonitor channelMonitor; | |
| 81 | 62 | |
| 63 | + @Override | |
| 64 | + public Cluster.Builder createClusterBuilder() { | |
| 65 | + channelMonitor = register(new SocketChannelMonitor()); | |
| 82 | 66 | PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8); |
| 83 | - | |
| 84 | - cluster = Cluster.builder() | |
| 85 | - .addContactPointsWithPorts(nodes) | |
| 67 | + return Cluster.builder() | |
| 86 | 68 | .withPoolingOptions(poolingOptions) |
| 87 | 69 | .withNettyOptions(channelMonitor.nettyOptions()) |
| 88 | - .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) | |
| 89 | - .build(); | |
| 70 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)); | |
| 90 | 71 | } |
| 91 | 72 | |
| 92 | - @AfterClass(groups = "stress") | |
| 93 | - public void afterClass() { | |
| 94 | - if (ccmBridge != null) { | |
| 95 | - ccmBridge.stop(); | |
| 96 | - } | |
| 97 | - if (channelMonitor != null) { | |
| 98 | - channelMonitor.stop(); | |
| 99 | - } | |
| 100 | - if (cluster != null) { | |
| 101 | - cluster.close(); | |
| 102 | - } | |
| 73 | + @Override | |
| 74 | + public Collection<String> createTestFixtures() { | |
| 75 | + return Lists.newArrayList( | |
| 76 | + "create table record (\n" | |
| 77 | + + " name text,\n" | |
| 78 | + + " phone text,\n" | |
| 79 | + + " value text,\n" | |
| 80 | + + " PRIMARY KEY (name, phone)\n" | |
| 81 | + + ")" | |
| 82 | + | |
| 83 | + ); | |
| 103 | 84 | } |
| 104 | 85 | |
| 105 | 86 | /** |
| @@ -127,16 +108,14 @@ | ||
| 127 | 108 | */ |
| 128 | 109 | @Test(groups = "stress") |
| 129 | 110 | public void host_state_should_be_maintained_with_timeouts() throws Exception { |
| 130 | - // Setup schema and insert records. | |
| 131 | - Session session = cluster.connect(); | |
| 132 | - setupSchema(session); | |
| 111 | + insertRecords(); | |
| 133 | 112 | session.close(); |
| 134 | 113 | |
| 135 | 114 | // Set very low timeouts. |
| 136 | 115 | cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS); |
| 137 | 116 | cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS); |
| 138 | - session = cluster.connect(); | |
| 139 | - PreparedStatement statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;"); | |
| 117 | + session = cluster.connect(keyspace); | |
| 118 | + PreparedStatement statement = session.prepare("select * from record where name=? limit 1000;"); | |
| 140 | 119 | |
| 141 | 120 | int workers = Runtime.getRuntime().availableProcessors(); |
| 142 | 121 | ExecutorService workerPool = Executors.newFixedThreadPool(workers, |
| @@ -145,7 +124,7 @@ | ||
| 145 | 124 | AtomicBoolean stopped = new AtomicBoolean(false); |
| 146 | 125 | |
| 147 | 126 | // Ensure that we never exceed MaxConnectionsPerHost * nodes + 1 control connection. |
| 148 | - int maxConnections = TestUtils.numberOfLocalCoreConnections(cluster) * nodes.size() + 1; | |
| 127 | + int maxConnections = TestUtils.numberOfLocalCoreConnections(cluster) * getInitialContactPoints().size() + 1; | |
| 149 | 128 | |
| 150 | 129 | try { |
| 151 | 130 | Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES); |
| @@ -159,7 +138,7 @@ | ||
| 159 | 138 | channelMonitor.report(); |
| 160 | 139 | // Some connections that are being closed may have had active requests which are delegated to the |
| 161 | 140 | // reaper for cleanup later. |
| 162 | - Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes); | |
| 141 | + Collection<SocketChannel> openChannels = channelMonitor.openChannels(getInitialContactPoints()); | |
| 163 | 142 | |
| 164 | 143 | // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing |
| 165 | 144 | // factor between retrieving open connections and checking the reaper. |
| @@ -182,7 +161,7 @@ | ||
| 182 | 161 | "and for the pools to recover."); |
| 183 | 162 | Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS); |
| 184 | 163 | |
| 185 | - Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes); | |
| 164 | + Collection<SocketChannel> openChannels = channelMonitor.openChannels(getInitialContactPoints()); | |
| 186 | 165 | assertThat(openChannels.size()) |
| 187 | 166 | .as("Number of open connections does not meet expected: %s", openChannels) |
| 188 | 167 | .isLessThanOrEqualTo(maxConnections); |
| @@ -194,7 +173,7 @@ | ||
| 194 | 173 | |
| 195 | 174 | session.close(); |
| 196 | 175 | |
| 197 | - openChannels = channelMonitor.openChannels(nodes); | |
| 176 | + openChannels = channelMonitor.openChannels(getInitialContactPoints()); | |
| 198 | 177 | assertThat(openChannels.size()) |
| 199 | 178 | .as("Number of open connections does not meet expected: %s", openChannels) |
| 200 | 179 | .isEqualTo(1); |
| @@ -203,23 +182,7 @@ | ||
| 203 | 182 | } |
| 204 | 183 | } |
| 205 | 184 | |
| 206 | - /** | |
| 207 | - * Creates the testks schema with a 'record' table and preloads 30k records. | |
| 208 | - */ | |
| 209 | - private static void setupSchema(Session session) throws InterruptedException, ExecutionException, TimeoutException { | |
| 210 | - logger.debug("Creating keyspace"); | |
| 211 | - session.execute("create KEYSPACE " + KEYSPACE + | |
| 212 | - " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}"); | |
| 213 | - session.execute("use " + KEYSPACE); | |
| 214 | - | |
| 215 | - logger.debug("Creating table"); | |
| 216 | - session.execute("create table record (\n" | |
| 217 | - + " name text,\n" | |
| 218 | - + " phone text,\n" | |
| 219 | - + " value text,\n" | |
| 220 | - + " PRIMARY KEY (name, phone)\n" | |
| 221 | - + ");"); | |
| 222 | - | |
| 185 | + private void insertRecords() { | |
| 223 | 186 | int records = 30000; |
| 224 | 187 | PreparedStatement insertStmt = session.prepare("insert into record (name, phone, value) values (?, ?, ?)"); |
| 225 | 188 |
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +36 −63
| @@ -23,14 +23,9 @@ | ||
| 23 | 23 | import com.google.common.base.Function; |
| 24 | 24 | import com.google.common.collect.Iterables; |
| 25 | 25 | import com.google.common.collect.Lists; |
| 26 | -import org.testng.annotations.AfterClass; | |
| 27 | -import org.testng.annotations.BeforeClass; | |
| 28 | 26 | import org.testng.annotations.Test; |
| 29 | 27 | |
| 30 | -import java.net.InetSocketAddress; | |
| 31 | -import java.util.HashSet; | |
| 32 | -import java.util.List; | |
| 33 | -import java.util.Set; | |
| 28 | +import java.util.*; | |
| 34 | 29 | |
| 35 | 30 | import static com.datastax.driver.core.Assertions.assertThat; |
| 36 | 31 | |
| @@ -40,67 +35,45 @@ | ||
| 40 | 35 | * There's normally a way to parametrize a TestNG class with @Factory and @DataProvider, |
| 41 | 36 | * but it doesn't seem to work with multiple methods. |
| 42 | 37 | */ |
| 43 | -public abstract class TokenIntegrationTest { | |
| 44 | - | |
| 45 | - List<String> schema = Lists.newArrayList( | |
| 46 | - "CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", | |
| 47 | - "CREATE KEYSPACE test2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}", | |
| 48 | - "USE test", | |
| 49 | - "CREATE TABLE foo(i int primary key)", | |
| 50 | - "INSERT INTO foo (i) VALUES (1)", | |
| 51 | - "INSERT INTO foo (i) VALUES (2)", | |
| 52 | - "INSERT INTO foo (i) VALUES (3)" | |
| 53 | - ); | |
| 54 | - | |
| 55 | - private final String ccmOptions; | |
| 38 | +@CCMConfig(numberOfNodes = 3, createKeyspace = false) | |
| 39 | +public abstract class TokenIntegrationTest extends CCMTestsSupport { | |
| 40 | + | |
| 56 | 41 | private final DataType expectedTokenType; |
| 57 | 42 | private final int numTokens; |
| 58 | 43 | private final boolean useVnodes; |
| 59 | - CCMBridge ccm; | |
| 60 | - Cluster cluster; | |
| 61 | - Session session; | |
| 62 | - | |
| 63 | - public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType) { | |
| 64 | - this(ccmOptions, expectedTokenType, false); | |
| 65 | - } | |
| 44 | + private String ks1; | |
| 45 | + private String ks2; | |
| 66 | 46 | |
| 67 | - public TokenIntegrationTest(String ccmOptions, DataType expectedTokenType, boolean useVnodes) { | |
| 47 | + public TokenIntegrationTest(DataType expectedTokenType, boolean useVnodes) { | |
| 68 | 48 | this.expectedTokenType = expectedTokenType; |
| 69 | 49 | this.numTokens = useVnodes ? 256 : 1; |
| 70 | - this.ccmOptions = useVnodes ? ccmOptions + " --vnodes" : ccmOptions; | |
| 71 | 50 | this.useVnodes = useVnodes; |
| 72 | 51 | } |
| 73 | 52 | |
| 74 | - @BeforeClass(groups = "short") | |
| 75 | - public void setup() { | |
| 76 | - ccm = CCMBridge.builder("test").withNodes(3).withStartOptions(ccmOptions).build(); | |
| 77 | - | |
| 53 | + @Override | |
| 54 | + public Cluster.Builder createClusterBuilder() { | |
| 78 | 55 | // Only connect to node 1, which makes it easier to query system tables in should_expose_tokens_per_host() |
| 79 | 56 | LoadBalancingPolicy lbp = new WhiteListPolicy(new RoundRobinPolicy(), |
| 80 | - Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(1), 9042))); | |
| 81 | - | |
| 82 | - cluster = Cluster.builder() | |
| 83 | - .addContactPoints(CCMBridge.ipOfNode(1)) | |
| 57 | + Collections.singleton(ccm.addressOfNode(1))); | |
| 58 | + return Cluster.builder() | |
| 59 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 84 | 60 | .withLoadBalancingPolicy(lbp) |
| 85 | - .withQueryOptions(new QueryOptions() | |
| 86 | - .setRefreshNodeIntervalMillis(0) | |
| 87 | - .setRefreshNodeListIntervalMillis(0) | |
| 88 | - .setRefreshSchemaIntervalMillis(0) | |
| 89 | - ) | |
| 90 | - .build(); | |
| 91 | - cluster.init(); | |
| 92 | - session = cluster.connect(); | |
| 93 | - | |
| 94 | - for (String statement : schema) | |
| 95 | - session.execute(statement); | |
| 61 | + .withQueryOptions(TestUtils.nonDebouncingQueryOptions()); | |
| 96 | 62 | } |
| 97 | 63 | |
| 98 | - @AfterClass(groups = "short", alwaysRun = true) | |
| 99 | - public void teardown() { | |
| 100 | - if (cluster != null) | |
| 101 | - cluster.close(); | |
| 102 | - if (ccm != null) | |
| 103 | - ccm.remove(); | |
| 64 | + @Override | |
| 65 | + public Collection<String> createTestFixtures() { | |
| 66 | + ks1 = TestUtils.getAvailableKeyspaceName(); | |
| 67 | + ks2 = TestUtils.getAvailableKeyspaceName(); | |
| 68 | + return Lists.newArrayList( | |
| 69 | + String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", ks1), | |
| 70 | + String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 2}", ks2), | |
| 71 | + String.format("USE %s", ks1), | |
| 72 | + "CREATE TABLE foo(i int primary key)", | |
| 73 | + "INSERT INTO foo (i) VALUES (1)", | |
| 74 | + "INSERT INTO foo (i) VALUES (2)", | |
| 75 | + "INSERT INTO foo (i) VALUES (3)" | |
| 76 | + ); | |
| 104 | 77 | } |
| 105 | 78 | |
| 106 | 79 | /** |
| @@ -120,7 +93,7 @@ | ||
| 120 | 93 | |
| 121 | 94 | // Find the replica for a given partition key |
| 122 | 95 | int testKey = 1; |
| 123 | - Set<Host> replicas = metadata.getReplicas("test", DataType.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum())); | |
| 96 | + Set<Host> replicas = metadata.getReplicas(ks1, DataType.cint().serialize(testKey, cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum())); | |
| 124 | 97 | assertThat(replicas).hasSize(1); |
| 125 | 98 | Host replica = replicas.iterator().next(); |
| 126 | 99 | |
| @@ -140,7 +113,7 @@ | ||
| 140 | 113 | .isNull(); |
| 141 | 114 | foundRange = range; |
| 142 | 115 | // That range should be managed by the replica |
| 143 | - assertThat(metadata.getReplicas("test", range)).contains(replica); | |
| 116 | + assertThat(metadata.getReplicas(ks1, range)).contains(replica); | |
| 144 | 117 | } |
| 145 | 118 | } |
| 146 | 119 | } |
| @@ -181,7 +154,7 @@ | ||
| 181 | 154 | @Test(groups = "short") |
| 182 | 155 | public void should_get_token_from_row_and_set_token_in_query() { |
| 183 | 156 | // get by index: |
| 184 | - Row row = session.execute("SELECT token(i) FROM test.foo WHERE i = 1").one(); | |
| 157 | + Row row = session.execute("SELECT token(i) FROM foo WHERE i = 1").one(); | |
| 185 | 158 | Token token = row.getToken(0); |
| 186 | 159 | assertThat(token.getType()).isEqualTo(expectedTokenType); |
| 187 | 160 | |
| @@ -189,7 +162,7 @@ | ||
| 189 | 162 | row.getPartitionKeyToken() |
| 190 | 163 | ).isEqualTo(token); |
| 191 | 164 | |
| 192 | - PreparedStatement pst = session.prepare("SELECT * FROM test.foo WHERE token(i) = ?"); | |
| 165 | + PreparedStatement pst = session.prepare("SELECT * FROM foo WHERE token(i) = ?"); | |
| 193 | 166 | row = session.execute(pst.bind(token)).one(); |
| 194 | 167 | assertThat(row.getInt(0)).isEqualTo(1); |
| 195 | 168 | |
| @@ -217,15 +190,15 @@ | ||
| 217 | 190 | @Test(groups = "short") |
| 218 | 191 | @CassandraVersion(major = 2) |
| 219 | 192 | public void should_get_token_from_row_and_set_token_in_query_with_binding_and_aliasing() { |
| 220 | - Row row = session.execute("SELECT token(i) AS t FROM test.foo WHERE i = 1").one(); | |
| 193 | + Row row = session.execute("SELECT token(i) AS t FROM foo WHERE i = 1").one(); | |
| 221 | 194 | Token token = row.getToken("t"); |
| 222 | 195 | assertThat(token.getType()).isEqualTo(expectedTokenType); |
| 223 | 196 | |
| 224 | - PreparedStatement pst = session.prepare("SELECT * FROM test.foo WHERE token(i) = :myToken"); | |
| 197 | + PreparedStatement pst = session.prepare("SELECT * FROM foo WHERE token(i) = :myToken"); | |
| 225 | 198 | row = session.execute(pst.bind().setToken("myToken", token)).one(); |
| 226 | 199 | assertThat(row.getInt(0)).isEqualTo(1); |
| 227 | 200 | |
| 228 | - row = session.execute("SELECT * FROM test.foo WHERE token(i) = ?", token).one(); | |
| 201 | + row = session.execute("SELECT * FROM foo WHERE token(i) = ?", token).one(); | |
| 229 | 202 | assertThat(row.getInt(0)).isEqualTo(1); |
| 230 | 203 | } |
| 231 | 204 | |
| @@ -241,7 +214,7 @@ | ||
| 241 | 214 | */ |
| 242 | 215 | @Test(groups = "short", expectedExceptions = InvalidTypeException.class) |
| 243 | 216 | public void should_raise_exception_when_get_token_on_non_token() { |
| 244 | - Row row = session.execute("SELECT i FROM test.foo WHERE i = 1").one(); | |
| 217 | + Row row = session.execute("SELECT i FROM foo WHERE i = 1").one(); | |
| 245 | 218 | row.getToken(0); |
| 246 | 219 | } |
| 247 | 220 | |
| @@ -263,8 +236,8 @@ | ||
| 263 | 236 | */ |
| 264 | 237 | @Test(groups = "short") |
| 265 | 238 | public void should_expose_token_ranges_per_host() { |
| 266 | - checkRangesPerHost("test", 1); | |
| 267 | - checkRangesPerHost("test2", 2); | |
| 239 | + checkRangesPerHost(ks1, 1); | |
| 240 | + checkRangesPerHost(ks2, 2); | |
| 268 | 241 | assertThat(cluster).hasValidTokenRanges(); |
| 269 | 242 | } |
| 270 | 243 |
modified driver-core/src/test/java/com/datastax/driver/core/TracingTest.java +6 −6
| @@ -28,17 +28,17 @@ | ||
| 28 | 28 | import static org.assertj.core.api.Assertions.assertThat; |
| 29 | 29 | |
| 30 | 30 | @CassandraVersion(major = 2.0) |
| 31 | -public class TracingTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 31 | +public class TracingTest extends CCMTestsSupport { | |
| 32 | + | |
| 33 | + private static final String KEY = "tracing_test"; | |
| 32 | 34 | |
| 33 | 35 | @Override |
| 34 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 35 | - return builder.withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 36 | + public Cluster.Builder createClusterBuilder() { | |
| 37 | + return Cluster.builder().withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 36 | 38 | } |
| 37 | 39 | |
| 38 | - public static final String KEY = "tracing_test"; | |
| 39 | - | |
| 40 | 40 | @Override |
| 41 | - protected Collection<String> getTableDefinitions() { | |
| 41 | + public Collection<String> createTestFixtures() { | |
| 42 | 42 | return Collections.singletonList("CREATE TABLE test (k text, v int, PRIMARY KEY (k, v))"); |
| 43 | 43 | } |
| 44 | 44 |
modified driver-core/src/test/java/com/datastax/driver/core/TupleTest.java +279 −326
| @@ -27,11 +27,11 @@ | ||
| 27 | 27 | import static org.testng.Assert.fail; |
| 28 | 28 | |
| 29 | 29 | @CassandraVersion(major = 2.1) |
| 30 | -public class TupleTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 30 | +public class TupleTest extends CCMTestsSupport { | |
| 31 | 31 | |
| 32 | 32 | @Override |
| 33 | - protected Collection<String> getTableDefinitions() { | |
| 34 | - return Arrays.asList("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)"); | |
| 33 | + public Collection<String> createTestFixtures() { | |
| 34 | + return Collections.singleton("CREATE TABLE t (k int PRIMARY KEY, v frozen<tuple<int, text, float>>)"); | |
| 35 | 35 | } |
| 36 | 36 | |
| 37 | 37 | @Test(groups = "short") |
| @@ -46,7 +46,6 @@ | ||
| 46 | 46 | assertEquals(v.getType().getComponentTypes().get(0), DataType.cint()); |
| 47 | 47 | assertEquals(v.getType().getComponentTypes().get(1), DataType.text()); |
| 48 | 48 | assertEquals(v.getType().getComponentTypes().get(2), DataType.cfloat()); |
| 49 | - | |
| 50 | 49 | assertEquals(v.getInt(0), 1); |
| 51 | 50 | assertEquals(v.getString(1), "a"); |
| 52 | 51 | assertEquals(v.getFloat(2), 1.0f); |
| @@ -56,33 +55,28 @@ | ||
| 56 | 55 | |
| 57 | 56 | @Test(groups = "short") |
| 58 | 57 | public void simpleWriteReadTest() throws Exception { |
| 59 | - try { | |
| 60 | - session.execute("USE " + keyspace); | |
| 61 | - PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)"); | |
| 62 | - PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?"); | |
| 58 | + session.execute("USE " + keyspace); | |
| 59 | + PreparedStatement ins = session.prepare("INSERT INTO t(k, v) VALUES (?, ?)"); | |
| 60 | + PreparedStatement sel = session.prepare("SELECT * FROM t WHERE k=?"); | |
| 63 | 61 | |
| 64 | - TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat()); | |
| 62 | + TupleType t = TupleType.of(DataType.cint(), DataType.text(), DataType.cfloat()); | |
| 65 | 63 | |
| 66 | - int k = 1; | |
| 67 | - TupleValue v = t.newValue(1, "a", 1.0f); | |
| 64 | + int k = 1; | |
| 65 | + TupleValue v = t.newValue(1, "a", 1.0f); | |
| 68 | 66 | |
| 69 | - session.execute(ins.bind(k, v)); | |
| 70 | - TupleValue v2 = session.execute(sel.bind(k)).one().getTupleValue("v"); | |
| 67 | + session.execute(ins.bind(k, v)); | |
| 68 | + TupleValue v2 = session.execute(sel.bind(k)).one().getTupleValue("v"); | |
| 71 | 69 | |
| 72 | - assertEquals(v2, v); | |
| 70 | + assertEquals(v2, v); | |
| 73 | 71 | |
| 74 | - // Test simple statement interpolation | |
| 75 | - k = 2; | |
| 76 | - v = t.newValue(2, "b", 2.0f); | |
| 72 | + // Test simple statement interpolation | |
| 73 | + k = 2; | |
| 74 | + v = t.newValue(2, "b", 2.0f); | |
| 77 | 75 | |
| 78 | - session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v); | |
| 79 | - v2 = session.execute(sel.bind(k)).one().getTupleValue("v"); | |
| 76 | + session.execute("INSERT INTO t(k, v) VALUES (?, ?)", k, v); | |
| 77 | + v2 = session.execute(sel.bind(k)).one().getTupleValue("v"); | |
| 80 | 78 | |
| 81 | - assertEquals(v2, v); | |
| 82 | - } catch (Exception e) { | |
| 83 | - errorOut(); | |
| 84 | - throw e; | |
| 85 | - } | |
| 79 | + assertEquals(v2, v); | |
| 86 | 80 | } |
| 87 | 81 | |
| 88 | 82 | /** |
| @@ -93,65 +87,61 @@ | ||
| 93 | 87 | */ |
| 94 | 88 | @Test(groups = "short") |
| 95 | 89 | public void tupleTypeTest() throws Exception { |
| 90 | + session.execute("CREATE KEYSPACE test_tuple_type " + | |
| 91 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 92 | + session.execute("USE test_tuple_type"); | |
| 93 | + session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)"); | |
| 94 | + | |
| 95 | + TupleType t = TupleType.of(DataType.ascii(), DataType.cint(), DataType.cboolean()); | |
| 96 | + | |
| 97 | + // test non-prepared statement | |
| 98 | + TupleValue complete = t.newValue("foo", 123, true); | |
| 99 | + session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete); | |
| 100 | + TupleValue r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); | |
| 101 | + assertEquals(r, complete); | |
| 102 | + | |
| 103 | + // test incomplete tuples | |
| 96 | 104 | try { |
| 97 | - session.execute("CREATE KEYSPACE test_tuple_type " + | |
| 98 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 99 | - session.execute("USE test_tuple_type"); | |
| 100 | - session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<tuple<ascii, int, boolean>>)"); | |
| 101 | - | |
| 102 | - TupleType t = TupleType.of(DataType.ascii(), DataType.cint(), DataType.cboolean()); | |
| 103 | - | |
| 104 | - // test non-prepared statement | |
| 105 | - TupleValue complete = t.newValue("foo", 123, true); | |
| 106 | - session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", complete); | |
| 107 | - TupleValue r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); | |
| 108 | - assertEquals(r, complete); | |
| 109 | - | |
| 110 | - // test incomplete tuples | |
| 111 | - try { | |
| 112 | - TupleValue partial = t.newValue("bar", 456); | |
| 113 | - fail(); | |
| 114 | - } catch (IllegalArgumentException e) { | |
| 115 | - } | |
| 116 | - | |
| 117 | - // test incomplete tuples with new TupleType | |
| 118 | - TupleType t1 = TupleType.of(DataType.ascii(), DataType.cint()); | |
| 119 | - TupleValue partial = t1.newValue("bar", 456); | |
| 120 | - TupleValue partionResult = t.newValue("bar", 456, null); | |
| 121 | - session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial); | |
| 122 | - r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); | |
| 123 | - assertEquals(r, partionResult); | |
| 124 | - | |
| 125 | - // test single value tuples | |
| 126 | - try { | |
| 127 | - TupleValue subpartial = t.newValue("zoo"); | |
| 128 | - fail(); | |
| 129 | - } catch (IllegalArgumentException e) { | |
| 130 | - } | |
| 105 | + t.newValue("bar", 456); | |
| 106 | + fail(); | |
| 107 | + } catch (IllegalArgumentException e) { | |
| 108 | + //ok | |
| 109 | + } | |
| 131 | 110 | |
| 132 | - // test single value tuples with new TupleType | |
| 133 | - TupleType t2 = TupleType.of(DataType.ascii()); | |
| 134 | - TupleValue subpartial = t2.newValue("zoo"); | |
| 135 | - TupleValue subpartialResult = t.newValue("zoo", null, null); | |
| 136 | - session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial); | |
| 137 | - r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); | |
| 138 | - assertEquals(r, subpartialResult); | |
| 139 | - | |
| 140 | - // test prepared statements | |
| 141 | - PreparedStatement prepared = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 142 | - session.execute(prepared.bind(3, complete)); | |
| 143 | - session.execute(prepared.bind(4, partial)); | |
| 144 | - session.execute(prepared.bind(5, subpartial)); | |
| 145 | - | |
| 146 | - prepared = session.prepare("SELECT b FROM mytable WHERE a=?"); | |
| 147 | - assertEquals(session.execute(prepared.bind(3)).one().getTupleValue("b"), complete); | |
| 148 | - assertEquals(session.execute(prepared.bind(4)).one().getTupleValue("b"), partionResult); | |
| 149 | - assertEquals(session.execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult); | |
| 150 | - | |
| 151 | - } catch (Exception e) { | |
| 152 | - errorOut(); | |
| 153 | - throw e; | |
| 111 | + // test incomplete tuples with new TupleType | |
| 112 | + TupleType t1 = TupleType.of(DataType.ascii(), DataType.cint()); | |
| 113 | + TupleValue partial = t1.newValue("bar", 456); | |
| 114 | + TupleValue partionResult = t.newValue("bar", 456, null); | |
| 115 | + session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", partial); | |
| 116 | + r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); | |
| 117 | + assertEquals(r, partionResult); | |
| 118 | + | |
| 119 | + // test single value tuples | |
| 120 | + try { | |
| 121 | + t.newValue("zoo"); | |
| 122 | + fail(); | |
| 123 | + } catch (IllegalArgumentException e) { | |
| 124 | + //ok | |
| 154 | 125 | } |
| 126 | + | |
| 127 | + // test single value tuples with new TupleType | |
| 128 | + TupleType t2 = TupleType.of(DataType.ascii()); | |
| 129 | + TupleValue subpartial = t2.newValue("zoo"); | |
| 130 | + TupleValue subpartialResult = t.newValue("zoo", null, null); | |
| 131 | + session.execute("INSERT INTO mytable (a, b) VALUES (0, ?)", subpartial); | |
| 132 | + r = session.execute("SELECT b FROM mytable WHERE a=0").one().getTupleValue("b"); | |
| 133 | + assertEquals(r, subpartialResult); | |
| 134 | + | |
| 135 | + // test prepared statements | |
| 136 | + PreparedStatement prepared = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 137 | + session.execute(prepared.bind(3, complete)); | |
| 138 | + session.execute(prepared.bind(4, partial)); | |
| 139 | + session.execute(prepared.bind(5, subpartial)); | |
| 140 | + | |
| 141 | + prepared = session.prepare("SELECT b FROM mytable WHERE a=?"); | |
| 142 | + assertEquals(session.execute(prepared.bind(3)).one().getTupleValue("b"), complete); | |
| 143 | + assertEquals(session.execute(prepared.bind(4)).one().getTupleValue("b"), partionResult); | |
| 144 | + assertEquals(session.execute(prepared.bind(5)).one().getTupleValue("b"), subpartialResult); | |
| 155 | 145 | } |
| 156 | 146 | |
| 157 | 147 | /** |
| @@ -163,47 +153,41 @@ | ||
| 163 | 153 | */ |
| 164 | 154 | @Test(groups = "short") |
| 165 | 155 | public void tupleTestTypeVaryingLengths() throws Exception { |
| 166 | - try { | |
| 167 | - session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " + | |
| 168 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 169 | - session.execute("USE test_tuple_type_varying_lengths"); | |
| 170 | - | |
| 171 | - // programmatically create the table with tuples of said sizes | |
| 172 | - int[] lengths = {1, 2, 3, 384}; | |
| 173 | - ArrayList<String> valueSchema = new ArrayList<String>(); | |
| 174 | - for (int i : lengths) { | |
| 175 | - ArrayList<String> ints = new ArrayList<String>(); | |
| 176 | - for (int j = 0; j < i; ++j) { | |
| 177 | - ints.add("int"); | |
| 178 | - } | |
| 179 | - valueSchema.add(String.format(" v_%d frozen<tuple<%s>>", i, Joiner.on(',').join(ints))); | |
| 156 | + session.execute("CREATE KEYSPACE test_tuple_type_varying_lengths " + | |
| 157 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 158 | + session.execute("USE test_tuple_type_varying_lengths"); | |
| 159 | + | |
| 160 | + // programmatically create the table with tuples of said sizes | |
| 161 | + int[] lengths = {1, 2, 3, 384}; | |
| 162 | + ArrayList<String> valueSchema = new ArrayList<String>(); | |
| 163 | + for (int i : lengths) { | |
| 164 | + ArrayList<String> ints = new ArrayList<String>(); | |
| 165 | + for (int j = 0; j < i; ++j) { | |
| 166 | + ints.add("int"); | |
| 180 | 167 | } |
| 181 | - session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema))); | |
| 182 | - | |
| 183 | - // insert tuples into same key using different columns | |
| 184 | - // and verify the results | |
| 185 | - for (int i : lengths) { | |
| 186 | - // create tuple | |
| 187 | - ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 188 | - ArrayList<Integer> values = new ArrayList<Integer>(); | |
| 189 | - for (int j = 0; j < i; ++j) { | |
| 190 | - dataTypes.add(DataType.cint()); | |
| 191 | - values.add(j); | |
| 192 | - } | |
| 193 | - TupleType t = new TupleType(dataTypes); | |
| 194 | - TupleValue createdTuple = t.newValue(values.toArray()); | |
| 195 | - | |
| 196 | - // write tuple | |
| 197 | - session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); | |
| 198 | - | |
| 199 | - // read tuple | |
| 200 | - TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i)); | |
| 201 | - assertEquals(r, createdTuple); | |
| 168 | + valueSchema.add(String.format(" v_%d frozen<tuple<%s>>", i, Joiner.on(',').join(ints))); | |
| 169 | + } | |
| 170 | + session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(valueSchema))); | |
| 171 | + | |
| 172 | + // insert tuples into same key using different columns | |
| 173 | + // and verify the results | |
| 174 | + for (int i : lengths) { | |
| 175 | + // create tuple | |
| 176 | + ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 177 | + ArrayList<Integer> values = new ArrayList<Integer>(); | |
| 178 | + for (int j = 0; j < i; ++j) { | |
| 179 | + dataTypes.add(DataType.cint()); | |
| 180 | + values.add(j); | |
| 202 | 181 | } |
| 203 | - | |
| 204 | - } catch (Exception e) { | |
| 205 | - errorOut(); | |
| 206 | - throw e; | |
| 182 | + TupleType t = new TupleType(dataTypes); | |
| 183 | + TupleValue createdTuple = t.newValue(values.toArray()); | |
| 184 | + | |
| 185 | + // write tuple | |
| 186 | + session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); | |
| 187 | + | |
| 188 | + // read tuple | |
| 189 | + TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)).one().getTupleValue(String.format("v_%s", i)); | |
| 190 | + assertEquals(r, createdTuple); | |
| 207 | 191 | } |
| 208 | 192 | } |
| 209 | 193 | |
| @@ -217,59 +201,52 @@ | ||
| 217 | 201 | public void tupleSubtypesTest() throws Exception { |
| 218 | 202 | |
| 219 | 203 | List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet()); |
| 204 | + session.execute("CREATE KEYSPACE test_tuple_subtypes " + | |
| 205 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 206 | + session.execute("USE test_tuple_subtypes"); | |
| 207 | + | |
| 208 | + // programmatically create the table with a tuple of all datatypes | |
| 209 | + session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES))); | |
| 210 | + | |
| 211 | + // insert tuples into same key using different columns | |
| 212 | + // and verify the results | |
| 213 | + int i = 1; | |
| 214 | + for (DataType ignored : DATA_TYPE_PRIMITIVES) { | |
| 215 | + // create tuples to be written and ensure they match with the expected response | |
| 216 | + // responses have trailing None values for every element that has not been written | |
| 217 | + ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 218 | + ArrayList<DataType> completeDataTypes = new ArrayList<DataType>(); | |
| 219 | + ArrayList<Object> createdValues = new ArrayList<Object>(); | |
| 220 | + ArrayList<Object> completeValues = new ArrayList<Object>(); | |
| 221 | + | |
| 222 | + // create written portion of the arrays | |
| 223 | + for (int j = 0; j < i; ++j) { | |
| 224 | + dataTypes.add(DATA_TYPE_PRIMITIVES.get(j)); | |
| 225 | + completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j)); | |
| 226 | + createdValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j))); | |
| 227 | + completeValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j))); | |
| 228 | + } | |
| 220 | 229 | |
| 221 | - try { | |
| 222 | - session.execute("CREATE KEYSPACE test_tuple_subtypes " + | |
| 223 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 224 | - session.execute("USE test_tuple_subtypes"); | |
| 225 | - | |
| 226 | - // programmatically create the table with a tuple of all datatypes | |
| 227 | - session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<tuple<%s>>)", Joiner.on(',').join(DATA_TYPE_PRIMITIVES))); | |
| 228 | - | |
| 229 | - // insert tuples into same key using different columns | |
| 230 | - // and verify the results | |
| 231 | - int i = 1; | |
| 232 | - for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 233 | - // create tuples to be written and ensure they match with the expected response | |
| 234 | - // responses have trailing None values for every element that has not been written | |
| 235 | - ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 236 | - ArrayList<DataType> completeDataTypes = new ArrayList<DataType>(); | |
| 237 | - ArrayList<Object> createdValues = new ArrayList<Object>(); | |
| 238 | - ArrayList<Object> completeValues = new ArrayList<Object>(); | |
| 239 | - | |
| 240 | - // create written portion of the arrays | |
| 241 | - for (int j = 0; j < i; ++j) { | |
| 242 | - dataTypes.add(DATA_TYPE_PRIMITIVES.get(j)); | |
| 243 | - completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(j)); | |
| 244 | - createdValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j))); | |
| 245 | - completeValues.add(PrimitiveTypeSamples.ALL.get(DATA_TYPE_PRIMITIVES.get(j))); | |
| 246 | - } | |
| 247 | - | |
| 248 | - // complete portion of the arrays needed for trailing nulls | |
| 249 | - for (int j = 0; j < DATA_TYPE_PRIMITIVES.size() - i; ++j) { | |
| 250 | - completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(i + j)); | |
| 251 | - completeValues.add(null); | |
| 252 | - } | |
| 253 | - | |
| 254 | - // actually create the tuples | |
| 255 | - TupleType t = new TupleType(dataTypes); | |
| 256 | - TupleType t2 = new TupleType(completeDataTypes); | |
| 257 | - TupleValue createdTuple = t.newValue(createdValues.toArray()); | |
| 258 | - TupleValue completeTuple = t2.newValue(completeValues.toArray()); | |
| 259 | - | |
| 260 | - // write tuple | |
| 261 | - session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple); | |
| 262 | - | |
| 263 | - // read tuple | |
| 264 | - TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v"); | |
| 265 | - | |
| 266 | - assertEquals(r, completeTuple); | |
| 267 | - ++i; | |
| 230 | + // complete portion of the arrays needed for trailing nulls | |
| 231 | + for (int j = 0; j < DATA_TYPE_PRIMITIVES.size() - i; ++j) { | |
| 232 | + completeDataTypes.add(DATA_TYPE_PRIMITIVES.get(i + j)); | |
| 233 | + completeValues.add(null); | |
| 268 | 234 | } |
| 269 | 235 | |
| 270 | - } catch (Exception e) { | |
| 271 | - errorOut(); | |
| 272 | - throw e; | |
| 236 | + // actually create the tuples | |
| 237 | + TupleType t = new TupleType(dataTypes); | |
| 238 | + TupleType t2 = new TupleType(completeDataTypes); | |
| 239 | + TupleValue createdTuple = t.newValue(createdValues.toArray()); | |
| 240 | + TupleValue completeTuple = t2.newValue(completeValues.toArray()); | |
| 241 | + | |
| 242 | + // write tuple | |
| 243 | + session.execute(String.format("INSERT INTO mytable (k, v) VALUES (%s, ?)", i), createdTuple); | |
| 244 | + | |
| 245 | + // read tuple | |
| 246 | + TupleValue r = session.execute("SELECT v FROM mytable WHERE k=?", i).one().getTupleValue("v"); | |
| 247 | + | |
| 248 | + assertEquals(r, completeTuple); | |
| 249 | + ++i; | |
| 273 | 250 | } |
| 274 | 251 | } |
| 275 | 252 | |
| @@ -283,116 +260,107 @@ | ||
| 283 | 260 | public void tupleNonPrimitiveSubTypesTest() throws Exception { |
| 284 | 261 | |
| 285 | 262 | List<DataType> DATA_TYPE_PRIMITIVES = Lists.newArrayList(PrimitiveTypeSamples.ALL.keySet()); |
| 263 | + session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " + | |
| 264 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 265 | + session.execute("USE test_tuple_non_primitive_subtypes"); | |
| 266 | + | |
| 267 | + ArrayList<String> values = new ArrayList<String>(); | |
| 268 | + | |
| 269 | + //create list values | |
| 270 | + for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 271 | + values.add(String.format("v_%s frozen<tuple<list<%s>>>", values.size(), datatype)); | |
| 272 | + } | |
| 286 | 273 | |
| 287 | - try { | |
| 288 | - session.execute("CREATE KEYSPACE test_tuple_non_primitive_subtypes " + | |
| 289 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 290 | - session.execute("USE test_tuple_non_primitive_subtypes"); | |
| 291 | - | |
| 292 | - ArrayList<String> values = new ArrayList<String>(); | |
| 293 | - | |
| 294 | - //create list values | |
| 295 | - for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 296 | - values.add(String.format("v_%s frozen<tuple<list<%s>>>", values.size(), datatype)); | |
| 297 | - } | |
| 298 | - | |
| 299 | - // create set values | |
| 300 | - for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 301 | - values.add(String.format("v_%s frozen<tuple<set<%s>>>", values.size(), datatype)); | |
| 302 | - } | |
| 274 | + // create set values | |
| 275 | + for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 276 | + values.add(String.format("v_%s frozen<tuple<set<%s>>>", values.size(), datatype)); | |
| 277 | + } | |
| 303 | 278 | |
| 304 | - // create map values | |
| 305 | - for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 306 | - values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), datatype, datatype)); | |
| 307 | - } | |
| 279 | + // create map values | |
| 280 | + for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 281 | + values.add(String.format("v_%s frozen<tuple<map<%s, %s>>>", values.size(), datatype, datatype)); | |
| 282 | + } | |
| 308 | 283 | |
| 309 | - // create table | |
| 310 | - session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values))); | |
| 284 | + // create table | |
| 285 | + session.execute(String.format("CREATE TABLE mytable (k int PRIMARY KEY, %s)", Joiner.on(',').join(values))); | |
| 311 | 286 | |
| 312 | 287 | |
| 313 | - int i = 0; | |
| 314 | - // test tuple<list<datatype>> | |
| 315 | - for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 316 | - // create tuple | |
| 317 | - ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 318 | - ArrayList<Object> createdValues = new ArrayList<Object>(); | |
| 288 | + int i = 0; | |
| 289 | + // test tuple<list<datatype>> | |
| 290 | + for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 291 | + // create tuple | |
| 292 | + ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 293 | + ArrayList<Object> createdValues = new ArrayList<Object>(); | |
| 319 | 294 | |
| 320 | - dataTypes.add(DataType.list(datatype)); | |
| 321 | - createdValues.add(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype))); | |
| 295 | + dataTypes.add(DataType.list(datatype)); | |
| 296 | + createdValues.add(Collections.singletonList(PrimitiveTypeSamples.ALL.get(datatype))); | |
| 322 | 297 | |
| 323 | - TupleType t = new TupleType(dataTypes); | |
| 324 | - TupleValue createdTuple = t.newValue(createdValues.toArray()); | |
| 298 | + TupleType t = new TupleType(dataTypes); | |
| 299 | + TupleValue createdTuple = t.newValue(createdValues.toArray()); | |
| 325 | 300 | |
| 326 | - // write tuple | |
| 327 | - session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); | |
| 301 | + // write tuple | |
| 302 | + session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); | |
| 328 | 303 | |
| 329 | - // read tuple | |
| 330 | - TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) | |
| 331 | - .one().getTupleValue(String.format("v_%s", i)); | |
| 304 | + // read tuple | |
| 305 | + TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) | |
| 306 | + .one().getTupleValue(String.format("v_%s", i)); | |
| 332 | 307 | |
| 333 | - assertEquals(r, createdTuple); | |
| 334 | - ++i; | |
| 335 | - } | |
| 308 | + assertEquals(r, createdTuple); | |
| 309 | + ++i; | |
| 310 | + } | |
| 336 | 311 | |
| 337 | - // test tuple<set<datatype>> | |
| 338 | - for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 339 | - // create tuple | |
| 340 | - ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 341 | - ArrayList<Object> createdValues = new ArrayList<Object>(); | |
| 312 | + // test tuple<set<datatype>> | |
| 313 | + for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 314 | + // create tuple | |
| 315 | + ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 316 | + ArrayList<Object> createdValues = new ArrayList<Object>(); | |
| 342 | 317 | |
| 343 | - dataTypes.add(DataType.set(datatype)); | |
| 344 | - createdValues.add(new HashSet<Object>(Arrays.asList(PrimitiveTypeSamples.ALL.get(datatype)))); | |
| 318 | + dataTypes.add(DataType.set(datatype)); | |
| 319 | + createdValues.add(new HashSet<Object>(Collections.singletonList(PrimitiveTypeSamples.ALL.get(datatype)))); | |
| 345 | 320 | |
| 346 | - TupleType t = new TupleType(dataTypes); | |
| 347 | - TupleValue createdTuple = t.newValue(createdValues.toArray()); | |
| 321 | + TupleType t = new TupleType(dataTypes); | |
| 322 | + TupleValue createdTuple = t.newValue(createdValues.toArray()); | |
| 348 | 323 | |
| 349 | - // write tuple | |
| 350 | - session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); | |
| 324 | + // write tuple | |
| 325 | + session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); | |
| 351 | 326 | |
| 352 | - // read tuple | |
| 353 | - TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) | |
| 354 | - .one().getTupleValue(String.format("v_%s", i)); | |
| 327 | + // read tuple | |
| 328 | + TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) | |
| 329 | + .one().getTupleValue(String.format("v_%s", i)); | |
| 355 | 330 | |
| 356 | - assertEquals(r, createdTuple); | |
| 357 | - ++i; | |
| 358 | - } | |
| 331 | + assertEquals(r, createdTuple); | |
| 332 | + ++i; | |
| 333 | + } | |
| 359 | 334 | |
| 360 | - // test tuple<map<datatype, datatype>> | |
| 361 | - for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 362 | - // create tuple | |
| 363 | - ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 364 | - ArrayList<Object> createdValues = new ArrayList<Object>(); | |
| 335 | + // test tuple<map<datatype, datatype>> | |
| 336 | + for (DataType datatype : DATA_TYPE_PRIMITIVES) { | |
| 337 | + // create tuple | |
| 338 | + ArrayList<DataType> dataTypes = new ArrayList<DataType>(); | |
| 339 | + ArrayList<Object> createdValues = new ArrayList<Object>(); | |
| 365 | 340 | |
| 366 | - HashMap<Object, Object> hm = new HashMap<Object, Object>(); | |
| 367 | - hm.put(PrimitiveTypeSamples.ALL.get(datatype), PrimitiveTypeSamples.ALL.get(datatype)); | |
| 341 | + HashMap<Object, Object> hm = new HashMap<Object, Object>(); | |
| 342 | + hm.put(PrimitiveTypeSamples.ALL.get(datatype), PrimitiveTypeSamples.ALL.get(datatype)); | |
| 368 | 343 | |
| 369 | - dataTypes.add(DataType.map(datatype, datatype)); | |
| 370 | - createdValues.add(hm); | |
| 344 | + dataTypes.add(DataType.map(datatype, datatype)); | |
| 345 | + createdValues.add(hm); | |
| 371 | 346 | |
| 372 | - TupleType t = new TupleType(dataTypes); | |
| 373 | - TupleValue createdTuple = t.newValue(createdValues.toArray()); | |
| 347 | + TupleType t = new TupleType(dataTypes); | |
| 348 | + TupleValue createdTuple = t.newValue(createdValues.toArray()); | |
| 374 | 349 | |
| 375 | - // write tuple | |
| 376 | - session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); | |
| 350 | + // write tuple | |
| 351 | + session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (0, ?)", i), createdTuple); | |
| 377 | 352 | |
| 378 | - // read tuple | |
| 379 | - TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) | |
| 380 | - .one().getTupleValue(String.format("v_%s", i)); | |
| 353 | + // read tuple | |
| 354 | + TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=0", i)) | |
| 355 | + .one().getTupleValue(String.format("v_%s", i)); | |
| 381 | 356 | |
| 382 | - assertEquals(r, createdTuple); | |
| 383 | - ++i; | |
| 384 | - } | |
| 385 | - } catch (Exception e) { | |
| 386 | - errorOut(); | |
| 387 | - throw e; | |
| 357 | + assertEquals(r, createdTuple); | |
| 358 | + ++i; | |
| 388 | 359 | } |
| 389 | 360 | } |
| 390 | 361 | |
| 391 | 362 | /** |
| 392 | 363 | * Helper method for creating nested tuple schema |
| 393 | - * | |
| 394 | - * @param depth | |
| 395 | - * @return | |
| 396 | 364 | */ |
| 397 | 365 | private String nestedTuplesSchemaHelper(int depth) { |
| 398 | 366 | if (depth == 0) |
| @@ -403,9 +371,6 @@ | ||
| 403 | 371 | |
| 404 | 372 | /** |
| 405 | 373 | * Helper method for creating nested tuples |
| 406 | - * | |
| 407 | - * @param depth | |
| 408 | - * @return | |
| 409 | 374 | */ |
| 410 | 375 | private TupleValue nestedTuplesCreatorHelper(int depth) { |
| 411 | 376 | if (depth == 1) { |
| @@ -426,39 +391,33 @@ | ||
| 426 | 391 | */ |
| 427 | 392 | @Test(groups = "short") |
| 428 | 393 | public void nestedTuplesTest() throws Exception { |
| 429 | - | |
| 430 | - try { | |
| 431 | - session.execute("CREATE KEYSPACE test_nested_tuples " + | |
| 432 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 433 | - session.execute("USE test_nested_tuples"); | |
| 434 | - | |
| 435 | - // create a table with multiple sizes of nested tuples | |
| 436 | - session.execute(String.format("CREATE TABLE mytable (" + | |
| 437 | - "k int PRIMARY KEY, " + | |
| 438 | - "v_1 %s, " + | |
| 439 | - "v_2 %s, " + | |
| 440 | - "v_3 %s, " + | |
| 441 | - "v_128 %s)", nestedTuplesSchemaHelper(1), | |
| 442 | - nestedTuplesSchemaHelper(2), | |
| 443 | - nestedTuplesSchemaHelper(3), | |
| 444 | - nestedTuplesSchemaHelper(128))); | |
| 445 | - | |
| 446 | - for (int i : Arrays.asList(1, 2, 3, 128)) { | |
| 447 | - // create tuple | |
| 448 | - TupleValue createdTuple = nestedTuplesCreatorHelper(i); | |
| 449 | - | |
| 450 | - // write tuple | |
| 451 | - session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple); | |
| 452 | - | |
| 453 | - // verify tuple was written and read correctly | |
| 454 | - TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i) | |
| 455 | - .one().getTupleValue(String.format("v_%s", i)); | |
| 456 | - | |
| 457 | - assertEquals(r, createdTuple); | |
| 458 | - } | |
| 459 | - } catch (Exception e) { | |
| 460 | - errorOut(); | |
| 461 | - throw e; | |
| 394 | + session.execute("CREATE KEYSPACE test_nested_tuples " + | |
| 395 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 396 | + session.execute("USE test_nested_tuples"); | |
| 397 | + | |
| 398 | + // create a table with multiple sizes of nested tuples | |
| 399 | + session.execute(String.format("CREATE TABLE mytable (" + | |
| 400 | + "k int PRIMARY KEY, " + | |
| 401 | + "v_1 %s, " + | |
| 402 | + "v_2 %s, " + | |
| 403 | + "v_3 %s, " + | |
| 404 | + "v_32 %s)", nestedTuplesSchemaHelper(1), | |
| 405 | + nestedTuplesSchemaHelper(2), | |
| 406 | + nestedTuplesSchemaHelper(3), | |
| 407 | + nestedTuplesSchemaHelper(32))); | |
| 408 | + | |
| 409 | + for (int i : Arrays.asList(1, 2, 3, 32)) { | |
| 410 | + // create tuple | |
| 411 | + TupleValue createdTuple = nestedTuplesCreatorHelper(i); | |
| 412 | + | |
| 413 | + // write tuple | |
| 414 | + session.execute(String.format("INSERT INTO mytable (k, v_%s) VALUES (?, ?)", i), i, createdTuple); | |
| 415 | + | |
| 416 | + // verify tuple was written and read correctly | |
| 417 | + TupleValue r = session.execute(String.format("SELECT v_%s FROM mytable WHERE k=?", i), i) | |
| 418 | + .one().getTupleValue(String.format("v_%s", i)); | |
| 419 | + | |
| 420 | + assertEquals(r, createdTuple); | |
| 462 | 421 | } |
| 463 | 422 | } |
| 464 | 423 | |
| @@ -470,55 +429,49 @@ | ||
| 470 | 429 | */ |
| 471 | 430 | @Test(groups = "short") |
| 472 | 431 | public void testTuplesWithNulls() throws Exception { |
| 473 | - try { | |
| 474 | - // create keyspace | |
| 475 | - session.execute("CREATE KEYSPACE testTuplesWithNulls " + | |
| 476 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 477 | - session.execute("USE testTuplesWithNulls"); | |
| 432 | + // create keyspace | |
| 433 | + session.execute("CREATE KEYSPACE testTuplesWithNulls " + | |
| 434 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 435 | + session.execute("USE testTuplesWithNulls"); | |
| 478 | 436 | |
| 479 | - // create UDT | |
| 480 | - session.execute("CREATE TYPE user (a text, b frozen<tuple<text, int, uuid, blob>>)"); | |
| 481 | - session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)"); | |
| 437 | + // create UDT | |
| 438 | + session.execute("CREATE TYPE user (a text, b frozen<tuple<text, int, uuid, blob>>)"); | |
| 439 | + session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)"); | |
| 482 | 440 | |
| 483 | - // insert UDT data | |
| 484 | - UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user"); | |
| 485 | - UDTValue userType = userTypeDef.newValue(); | |
| 441 | + // insert UDT data | |
| 442 | + UserType userTypeDef = cluster.getMetadata().getKeyspace("testTuplesWithNulls").getUserType("user"); | |
| 443 | + UDTValue userType = userTypeDef.newValue(); | |
| 486 | 444 | |
| 487 | - TupleType t = TupleType.of(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob()); | |
| 488 | - TupleValue v = t.newValue(null, null, null, null); | |
| 489 | - userType.setTupleValue("b", v); | |
| 445 | + TupleType t = TupleType.of(DataType.text(), DataType.cint(), DataType.uuid(), DataType.blob()); | |
| 446 | + TupleValue v = t.newValue(null, null, null, null); | |
| 447 | + userType.setTupleValue("b", v); | |
| 490 | 448 | |
| 491 | - PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 492 | - session.execute(ins.bind(0, userType)); | |
| 449 | + PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 450 | + session.execute(ins.bind(0, userType)); | |
| 493 | 451 | |
| 494 | - // retrieve and verify data | |
| 495 | - ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 496 | - List<Row> rows = rs.all(); | |
| 497 | - assertEquals(1, rows.size()); | |
| 452 | + // retrieve and verify data | |
| 453 | + ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 454 | + List<Row> rows = rs.all(); | |
| 455 | + assertEquals(1, rows.size()); | |
| 498 | 456 | |
| 499 | - Row row = rows.get(0); | |
| 457 | + Row row = rows.get(0); | |
| 500 | 458 | |
| 501 | - assertEquals(row.getInt("a"), 0); | |
| 502 | - assertEquals(row.getUDTValue("b"), userType); | |
| 459 | + assertEquals(row.getInt("a"), 0); | |
| 460 | + assertEquals(row.getUDTValue("b"), userType); | |
| 503 | 461 | |
| 504 | - // test empty strings | |
| 505 | - v = t.newValue("", null, null, ByteBuffer.allocate(0)); | |
| 506 | - userType.setTupleValue("b", v); | |
| 507 | - session.execute(ins.bind(0, userType)); | |
| 462 | + // test empty strings | |
| 463 | + v = t.newValue("", null, null, ByteBuffer.allocate(0)); | |
| 464 | + userType.setTupleValue("b", v); | |
| 465 | + session.execute(ins.bind(0, userType)); | |
| 508 | 466 | |
| 509 | - // retrieve and verify data | |
| 510 | - rs = session.execute("SELECT * FROM mytable"); | |
| 511 | - rows = rs.all(); | |
| 512 | - assertEquals(1, rows.size()); | |
| 467 | + // retrieve and verify data | |
| 468 | + rs = session.execute("SELECT * FROM mytable"); | |
| 469 | + rows = rs.all(); | |
| 470 | + assertEquals(1, rows.size()); | |
| 513 | 471 | |
| 514 | - row = rows.get(0); | |
| 472 | + row = rows.get(0); | |
| 515 | 473 | |
| 516 | - assertEquals(row.getInt("a"), 0); | |
| 517 | - assertEquals(row.getUDTValue("b"), userType); | |
| 518 | - | |
| 519 | - } catch (Exception e) { | |
| 520 | - errorOut(); | |
| 521 | - throw e; | |
| 522 | - } | |
| 474 | + assertEquals(row.getInt("a"), 0); | |
| 475 | + assertEquals(row.getUDTValue("b"), userType); | |
| 523 | 476 | } |
| 524 | 477 | } |
modified driver-core/src/test/java/com/datastax/driver/core/UserTypesTest.java +333 −394
| @@ -34,19 +34,17 @@ | ||
| 34 | 34 | import static org.testng.Assert.assertNotEquals; |
| 35 | 35 | |
| 36 | 36 | @CassandraVersion(major = 2.1) |
| 37 | -public class UserTypesTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 37 | +public class UserTypesTest extends CCMTestsSupport { | |
| 38 | 38 | |
| 39 | 39 | private final static List<DataType> DATA_TYPE_PRIMITIVES = new ArrayList<DataType>(DataType.allPrimitiveTypes()); |
| 40 | 40 | private final static List<DataType.Name> DATA_TYPE_NON_PRIMITIVE_NAMES = |
| 41 | 41 | new ArrayList<DataType.Name>(EnumSet.of(DataType.Name.LIST, DataType.Name.SET, DataType.Name.MAP, DataType.Name.TUPLE)); |
| 42 | 42 | |
| 43 | 43 | @Override |
| 44 | - protected Collection<String> getTableDefinitions() { | |
| 44 | + public Collection<String> createTestFixtures() { | |
| 45 | 45 | String type1 = "CREATE TYPE phone (alias text, number text)"; |
| 46 | 46 | String type2 = "CREATE TYPE address (street text, \"ZIP\" int, phones set<frozen<phone>>)"; |
| 47 | - | |
| 48 | 47 | String table = "CREATE TABLE user (id int PRIMARY KEY, addr frozen<address>)"; |
| 49 | - | |
| 50 | 48 | return Arrays.asList(type1, type2, table); |
| 51 | 49 | } |
| 52 | 50 | |
| @@ -58,30 +56,23 @@ | ||
| 58 | 56 | @Test(groups = "short") |
| 59 | 57 | public void simpleWriteReadTest() throws Exception { |
| 60 | 58 | int userId = 0; |
| 59 | + PreparedStatement ins = session.prepare("INSERT INTO user(id, addr) VALUES (?, ?)"); | |
| 60 | + PreparedStatement sel = session.prepare("SELECT * FROM user WHERE id=?"); | |
| 61 | 61 | |
| 62 | - try { | |
| 63 | - session.execute("USE " + keyspace); | |
| 64 | - PreparedStatement ins = session.prepare("INSERT INTO user(id, addr) VALUES (?, ?)"); | |
| 65 | - PreparedStatement sel = session.prepare("SELECT * FROM user WHERE id=?"); | |
| 66 | - | |
| 67 | - UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address"); | |
| 68 | - UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone"); | |
| 62 | + UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address"); | |
| 63 | + UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone"); | |
| 69 | 64 | |
| 70 | - UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790"); | |
| 71 | - UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251"); | |
| 65 | + UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790"); | |
| 66 | + UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251"); | |
| 72 | 67 | |
| 73 | - UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2)); | |
| 68 | + UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2)); | |
| 74 | 69 | |
| 75 | - session.execute(ins.bind(userId, addr)); | |
| 70 | + session.execute(ins.bind(userId, addr)); | |
| 76 | 71 | |
| 77 | - Row r = session.execute(sel.bind(userId)).one(); | |
| 72 | + Row r = session.execute(sel.bind(userId)).one(); | |
| 78 | 73 | |
| 79 | - assertEquals(r.getInt("id"), 0); | |
| 80 | - assertEquals(r.getUDTValue("addr"), addr); | |
| 81 | - } catch (Exception e) { | |
| 82 | - errorOut(); | |
| 83 | - throw e; | |
| 84 | - } | |
| 74 | + assertEquals(r.getInt("id"), 0); | |
| 75 | + assertEquals(r.getUDTValue("addr"), addr); | |
| 85 | 76 | } |
| 86 | 77 | |
| 87 | 78 | /** |
| @@ -92,27 +83,20 @@ | ||
| 92 | 83 | @Test(groups = "short") |
| 93 | 84 | public void simpleUnpreparedWriteReadTest() throws Exception { |
| 94 | 85 | int userId = 1; |
| 86 | + UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address"); | |
| 87 | + UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone"); | |
| 95 | 88 | |
| 96 | - try { | |
| 97 | - session.execute("USE " + keyspace); | |
| 98 | - UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address"); | |
| 99 | - UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone"); | |
| 89 | + UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790"); | |
| 90 | + UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251"); | |
| 100 | 91 | |
| 101 | - UDTValue phone1 = phoneDef.newValue().setString("alias", "home").setString("number", "0123548790"); | |
| 102 | - UDTValue phone2 = phoneDef.newValue().setString("alias", "work").setString("number", "0698265251"); | |
| 92 | + UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2)); | |
| 103 | 93 | |
| 104 | - UDTValue addr = addrDef.newValue().setString("street", "1600 Pennsylvania Ave NW").setInt(quote("ZIP"), 20500).setSet("phones", ImmutableSet.of(phone1, phone2)); | |
| 94 | + session.execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr); | |
| 105 | 95 | |
| 106 | - session.execute("INSERT INTO user(id, addr) VALUES (?, ?)", userId, addr); | |
| 96 | + Row r = session.execute("SELECT * FROM user WHERE id=?", userId).one(); | |
| 107 | 97 | |
| 108 | - Row r = session.execute("SELECT * FROM user WHERE id=?", userId).one(); | |
| 109 | - | |
| 110 | - assertEquals(r.getInt("id"), 1); | |
| 111 | - assertEquals(r.getUDTValue("addr"), addr); | |
| 112 | - } catch (Exception e) { | |
| 113 | - errorOut(); | |
| 114 | - throw e; | |
| 115 | - } | |
| 98 | + assertEquals(r.getInt("id"), 1); | |
| 99 | + assertEquals(r.getUDTValue("addr"), addr); | |
| 116 | 100 | } |
| 117 | 101 | |
| 118 | 102 | /** |
| @@ -122,41 +106,33 @@ | ||
| 122 | 106 | */ |
| 123 | 107 | @Test(groups = "short") |
| 124 | 108 | public void nonExistingTypesTest() throws Exception { |
| 125 | - try { | |
| 126 | - session.execute("USE " + keyspace); | |
| 127 | - | |
| 128 | - UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address1"); | |
| 129 | - UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone1"); | |
| 130 | - assertEquals(addrDef, null); | |
| 131 | - assertEquals(phoneDef, null); | |
| 132 | - | |
| 133 | - addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address"); | |
| 134 | - phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone"); | |
| 135 | - assertNotEquals(addrDef, null); | |
| 136 | - assertNotEquals(phoneDef, null); | |
| 137 | - | |
| 138 | - // create keyspace | |
| 139 | - String nonExistingKeyspace = keyspace + "_nonEx"; | |
| 140 | - session.execute("CREATE KEYSPACE " + nonExistingKeyspace + " " + | |
| 141 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 142 | - session.execute("USE " + nonExistingKeyspace); | |
| 143 | - | |
| 144 | - addrDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("address"); | |
| 145 | - phoneDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone"); | |
| 146 | - assertEquals(addrDef, null); | |
| 147 | - assertEquals(phoneDef, null); | |
| 148 | - | |
| 149 | - session.execute("USE " + keyspace); | |
| 150 | - | |
| 151 | - addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address"); | |
| 152 | - phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone"); | |
| 153 | - assertNotEquals(addrDef, null); | |
| 154 | - assertNotEquals(phoneDef, null); | |
| 155 | - | |
| 156 | - } catch (Exception e) { | |
| 157 | - errorOut(); | |
| 158 | - throw e; | |
| 159 | - } | |
| 109 | + UserType addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address1"); | |
| 110 | + UserType phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone1"); | |
| 111 | + assertEquals(addrDef, null); | |
| 112 | + assertEquals(phoneDef, null); | |
| 113 | + | |
| 114 | + addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address"); | |
| 115 | + phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone"); | |
| 116 | + assertNotEquals(addrDef, null); | |
| 117 | + assertNotEquals(phoneDef, null); | |
| 118 | + | |
| 119 | + // create keyspace | |
| 120 | + String nonExistingKeyspace = keyspace + "_nonEx"; | |
| 121 | + session.execute("CREATE KEYSPACE " + nonExistingKeyspace + " " + | |
| 122 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 123 | + session.execute("USE " + nonExistingKeyspace); | |
| 124 | + | |
| 125 | + addrDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("address"); | |
| 126 | + phoneDef = cluster.getMetadata().getKeyspace(nonExistingKeyspace).getUserType("phone"); | |
| 127 | + assertEquals(addrDef, null); | |
| 128 | + assertEquals(phoneDef, null); | |
| 129 | + | |
| 130 | + session.execute("USE " + keyspace); | |
| 131 | + | |
| 132 | + addrDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("address"); | |
| 133 | + phoneDef = cluster.getMetadata().getKeyspace(keyspace).getUserType("phone"); | |
| 134 | + assertNotEquals(addrDef, null); | |
| 135 | + assertNotEquals(phoneDef, null); | |
| 160 | 136 | } |
| 161 | 137 | |
| 162 | 138 | /** |
| @@ -168,48 +144,42 @@ | ||
| 168 | 144 | @Test(groups = "short") |
| 169 | 145 | public void udtSizesTest() throws Exception { |
| 170 | 146 | int MAX_TEST_LENGTH = 1024; |
| 171 | - | |
| 172 | - try { | |
| 173 | - // create keyspace | |
| 174 | - session.execute("CREATE KEYSPACE test_udt_sizes " + | |
| 175 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 176 | - session.execute("USE test_udt_sizes"); | |
| 177 | - | |
| 178 | - // create the seed udt | |
| 179 | - StringBuilder sb = new StringBuilder(); | |
| 180 | - for (int i = 0; i < MAX_TEST_LENGTH; ++i) { | |
| 181 | - sb.append(String.format("v_%s int", i)); | |
| 182 | - | |
| 183 | - if (i + 1 < MAX_TEST_LENGTH) | |
| 184 | - sb.append(","); | |
| 147 | + // create keyspace | |
| 148 | + session.execute("CREATE KEYSPACE test_udt_sizes " + | |
| 149 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 150 | + session.execute("USE test_udt_sizes"); | |
| 151 | + | |
| 152 | + // create the seed udt | |
| 153 | + StringBuilder sb = new StringBuilder(); | |
| 154 | + for (int i = 0; i < MAX_TEST_LENGTH; ++i) { | |
| 155 | + sb.append(String.format("v_%s int", i)); | |
| 156 | + | |
| 157 | + if (i + 1 < MAX_TEST_LENGTH) | |
| 158 | + sb.append(","); | |
| 159 | + } | |
| 160 | + session.execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString())); | |
| 161 | + | |
| 162 | + // create a table with multiple sizes of udts | |
| 163 | + session.execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)"); | |
| 164 | + | |
| 165 | + // hold onto the UserType for future use | |
| 166 | + UserType udtDef = cluster.getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt"); | |
| 167 | + | |
| 168 | + // verify inserts and reads | |
| 169 | + for (int i : Arrays.asList(0, 1, 2, 3, MAX_TEST_LENGTH)) { | |
| 170 | + // create udt | |
| 171 | + UDTValue createdUDT = udtDef.newValue(); | |
| 172 | + for (int j = 0; j < i; ++j) { | |
| 173 | + createdUDT.setInt(j, j); | |
| 185 | 174 | } |
| 186 | - session.execute(String.format("CREATE TYPE lengthy_udt (%s)", sb.toString())); | |
| 187 | - | |
| 188 | - // create a table with multiple sizes of udts | |
| 189 | - session.execute("CREATE TABLE mytable (k int PRIMARY KEY, v frozen<lengthy_udt>)"); | |
| 190 | - | |
| 191 | - // hold onto the UserType for future use | |
| 192 | - UserType udtDef = cluster.getMetadata().getKeyspace("test_udt_sizes").getUserType("lengthy_udt"); | |
| 193 | - | |
| 194 | - // verify inserts and reads | |
| 195 | - for (int i : Arrays.asList(0, 1, 2, 3, MAX_TEST_LENGTH)) { | |
| 196 | - // create udt | |
| 197 | - UDTValue createdUDT = udtDef.newValue(); | |
| 198 | - for (int j = 0; j < i; ++j) { | |
| 199 | - createdUDT.setInt(j, j); | |
| 200 | - } | |
| 201 | 175 | |
| 202 | - // write udt | |
| 203 | - session.execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT); | |
| 176 | + // write udt | |
| 177 | + session.execute("INSERT INTO mytable (k, v) VALUES (0, ?)", createdUDT); | |
| 204 | 178 | |
| 205 | - // verify udt was written and read correctly | |
| 206 | - UDTValue r = session.execute("SELECT v FROM mytable WHERE k=0") | |
| 207 | - .one().getUDTValue("v"); | |
| 208 | - assertEquals(r.toString(), createdUDT.toString()); | |
| 209 | - } | |
| 210 | - } catch (Exception e) { | |
| 211 | - errorOut(); | |
| 212 | - throw e; | |
| 179 | + // verify udt was written and read correctly | |
| 180 | + UDTValue r = session.execute("SELECT v FROM mytable WHERE k=0") | |
| 181 | + .one().getUDTValue("v"); | |
| 182 | + assertEquals(r.toString(), createdUDT.toString()); | |
| 213 | 183 | } |
| 214 | 184 | } |
| 215 | 185 | |
| @@ -221,98 +191,92 @@ | ||
| 221 | 191 | */ |
| 222 | 192 | @Test(groups = "short") |
| 223 | 193 | public void testPrimitiveDatatypes() throws Exception { |
| 224 | - try { | |
| 225 | - // create keyspace | |
| 226 | - session.execute("CREATE KEYSPACE testPrimitiveDatatypes " + | |
| 227 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 228 | - session.execute("USE testPrimitiveDatatypes"); | |
| 229 | - | |
| 230 | - // create UDT | |
| 231 | - List<String> alpha_type_list = new ArrayList<String>(); | |
| 232 | - int startIndex = (int) 'a'; | |
| 233 | - for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) { | |
| 234 | - alpha_type_list.add(String.format("%s %s", Character.toString((char) (startIndex + i)), | |
| 235 | - DATA_TYPE_PRIMITIVES.get(i).getName())); | |
| 236 | - } | |
| 237 | - | |
| 238 | - session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list))); | |
| 239 | - session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)"); | |
| 240 | - | |
| 241 | - // insert UDT data | |
| 242 | - UserType alldatatypesDef = cluster.getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes"); | |
| 243 | - UDTValue alldatatypes = alldatatypesDef.newValue(); | |
| 244 | - | |
| 245 | - for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) { | |
| 246 | - DataType dataType = DATA_TYPE_PRIMITIVES.get(i); | |
| 247 | - String index = Character.toString((char) (startIndex + i)); | |
| 248 | - Object sampleData = PrimitiveTypeSamples.ALL.get(dataType); | |
| 194 | + // create keyspace | |
| 195 | + session.execute("CREATE KEYSPACE testPrimitiveDatatypes " + | |
| 196 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 197 | + session.execute("USE testPrimitiveDatatypes"); | |
| 198 | + | |
| 199 | + // create UDT | |
| 200 | + List<String> alpha_type_list = new ArrayList<String>(); | |
| 201 | + int startIndex = (int) 'a'; | |
| 202 | + for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) { | |
| 203 | + alpha_type_list.add(String.format("%s %s", Character.toString((char) (startIndex + i)), | |
| 204 | + DATA_TYPE_PRIMITIVES.get(i).getName())); | |
| 205 | + } | |
| 249 | 206 | |
| 250 | - switch (dataType.getName()) { | |
| 251 | - case ASCII: | |
| 252 | - alldatatypes.setString(index, (String) sampleData); | |
| 253 | - break; | |
| 254 | - case BIGINT: | |
| 255 | - alldatatypes.setLong(index, ((Long) sampleData).longValue()); | |
| 256 | - break; | |
| 257 | - case BLOB: | |
| 258 | - alldatatypes.setBytes(index, (ByteBuffer) sampleData); | |
| 259 | - break; | |
| 260 | - case BOOLEAN: | |
| 261 | - alldatatypes.setBool(index, ((Boolean) sampleData).booleanValue()); | |
| 262 | - break; | |
| 263 | - case DECIMAL: | |
| 264 | - alldatatypes.setDecimal(index, (BigDecimal) sampleData); | |
| 265 | - break; | |
| 266 | - case DOUBLE: | |
| 267 | - alldatatypes.setDouble(index, ((Double) sampleData).doubleValue()); | |
| 268 | - break; | |
| 269 | - case FLOAT: | |
| 270 | - alldatatypes.setFloat(index, ((Float) sampleData).floatValue()); | |
| 271 | - break; | |
| 272 | - case INET: | |
| 273 | - alldatatypes.setInet(index, (InetAddress) sampleData); | |
| 274 | - break; | |
| 275 | - case INT: | |
| 276 | - alldatatypes.setInt(index, ((Integer) sampleData).intValue()); | |
| 277 | - break; | |
| 278 | - case TEXT: | |
| 279 | - alldatatypes.setString(index, (String) sampleData); | |
| 280 | - break; | |
| 281 | - case TIMESTAMP: | |
| 282 | - alldatatypes.setDate(index, ((Date) sampleData)); | |
| 283 | - break; | |
| 284 | - case TIMEUUID: | |
| 285 | - alldatatypes.setUUID(index, (UUID) sampleData); | |
| 286 | - break; | |
| 287 | - case UUID: | |
| 288 | - alldatatypes.setUUID(index, (UUID) sampleData); | |
| 289 | - break; | |
| 290 | - case VARCHAR: | |
| 291 | - alldatatypes.setString(index, (String) sampleData); | |
| 292 | - break; | |
| 293 | - case VARINT: | |
| 294 | - alldatatypes.setVarint(index, (BigInteger) sampleData); | |
| 295 | - break; | |
| 296 | - } | |
| 207 | + session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list))); | |
| 208 | + session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)"); | |
| 209 | + | |
| 210 | + // insert UDT data | |
| 211 | + UserType alldatatypesDef = cluster.getMetadata().getKeyspace("testPrimitiveDatatypes").getUserType("alldatatypes"); | |
| 212 | + UDTValue alldatatypes = alldatatypesDef.newValue(); | |
| 213 | + | |
| 214 | + for (int i = 0; i < DATA_TYPE_PRIMITIVES.size(); i++) { | |
| 215 | + DataType dataType = DATA_TYPE_PRIMITIVES.get(i); | |
| 216 | + String index = Character.toString((char) (startIndex + i)); | |
| 217 | + Object sampleData = PrimitiveTypeSamples.ALL.get(dataType); | |
| 218 | + | |
| 219 | + switch (dataType.getName()) { | |
| 220 | + case ASCII: | |
| 221 | + alldatatypes.setString(index, (String) sampleData); | |
| 222 | + break; | |
| 223 | + case BIGINT: | |
| 224 | + alldatatypes.setLong(index, (Long) sampleData); | |
| 225 | + break; | |
| 226 | + case BLOB: | |
| 227 | + alldatatypes.setBytes(index, (ByteBuffer) sampleData); | |
| 228 | + break; | |
| 229 | + case BOOLEAN: | |
| 230 | + alldatatypes.setBool(index, (Boolean) sampleData); | |
| 231 | + break; | |
| 232 | + case DECIMAL: | |
| 233 | + alldatatypes.setDecimal(index, (BigDecimal) sampleData); | |
| 234 | + break; | |
| 235 | + case DOUBLE: | |
| 236 | + alldatatypes.setDouble(index, (Double) sampleData); | |
| 237 | + break; | |
| 238 | + case FLOAT: | |
| 239 | + alldatatypes.setFloat(index, (Float) sampleData); | |
| 240 | + break; | |
| 241 | + case INET: | |
| 242 | + alldatatypes.setInet(index, (InetAddress) sampleData); | |
| 243 | + break; | |
| 244 | + case INT: | |
| 245 | + alldatatypes.setInt(index, (Integer) sampleData); | |
| 246 | + break; | |
| 247 | + case TEXT: | |
| 248 | + alldatatypes.setString(index, (String) sampleData); | |
| 249 | + break; | |
| 250 | + case TIMESTAMP: | |
| 251 | + alldatatypes.setDate(index, ((Date) sampleData)); | |
| 252 | + break; | |
| 253 | + case TIMEUUID: | |
| 254 | + alldatatypes.setUUID(index, (UUID) sampleData); | |
| 255 | + break; | |
| 256 | + case UUID: | |
| 257 | + alldatatypes.setUUID(index, (UUID) sampleData); | |
| 258 | + break; | |
| 259 | + case VARCHAR: | |
| 260 | + alldatatypes.setString(index, (String) sampleData); | |
| 261 | + break; | |
| 262 | + case VARINT: | |
| 263 | + alldatatypes.setVarint(index, (BigInteger) sampleData); | |
| 264 | + break; | |
| 297 | 265 | } |
| 266 | + } | |
| 298 | 267 | |
| 299 | - PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 300 | - session.execute(ins.bind(0, alldatatypes)); | |
| 301 | - | |
| 302 | - // retrieve and verify data | |
| 303 | - ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 304 | - List<Row> rows = rs.all(); | |
| 305 | - assertEquals(1, rows.size()); | |
| 268 | + PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 269 | + session.execute(ins.bind(0, alldatatypes)); | |
| 306 | 270 | |
| 307 | - Row row = rows.get(0); | |
| 271 | + // retrieve and verify data | |
| 272 | + ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 273 | + List<Row> rows = rs.all(); | |
| 274 | + assertEquals(1, rows.size()); | |
| 308 | 275 | |
| 309 | - assertEquals(row.getInt("a"), 0); | |
| 310 | - assertEquals(row.getUDTValue("b"), alldatatypes); | |
| 276 | + Row row = rows.get(0); | |
| 311 | 277 | |
| 312 | - } catch (Exception e) { | |
| 313 | - errorOut(); | |
| 314 | - throw e; | |
| 315 | - } | |
| 278 | + assertEquals(row.getInt("a"), 0); | |
| 279 | + assertEquals(row.getUDTValue("b"), alldatatypes); | |
| 316 | 280 | } |
| 317 | 281 | |
| 318 | 282 | /** |
| @@ -323,83 +287,77 @@ | ||
| 323 | 287 | */ |
| 324 | 288 | @Test(groups = "short") |
| 325 | 289 | public void testNonPrimitiveDatatypes() throws Exception { |
| 326 | - try { | |
| 327 | - // create keyspace | |
| 328 | - session.execute("CREATE KEYSPACE test_nonprimitive_datatypes " + | |
| 329 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 330 | - session.execute("USE test_nonprimitive_datatypes"); | |
| 331 | - | |
| 332 | - // counters are not allowed inside collections | |
| 333 | - DATA_TYPE_PRIMITIVES.remove(DataType.counter()); | |
| 334 | - | |
| 335 | - // create UDT | |
| 336 | - List<String> alpha_type_list = new ArrayList<String>(); | |
| 337 | - int startIndex = (int) 'a'; | |
| 338 | - for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++) | |
| 339 | - for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) { | |
| 340 | - String typeString; | |
| 341 | - if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) { | |
| 342 | - typeString = (String.format("%s_%s %s<%s, %s>", Character.toString((char) (startIndex + i)), | |
| 343 | - Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i), | |
| 344 | - DATA_TYPE_PRIMITIVES.get(j).getName(), DATA_TYPE_PRIMITIVES.get(j).getName())); | |
| 345 | - } else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) { | |
| 346 | - typeString = (String.format("%s_%s frozen<%s<%s>>", Character.toString((char) (startIndex + i)), | |
| 347 | - Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i), | |
| 348 | - DATA_TYPE_PRIMITIVES.get(j).getName())); | |
| 349 | - } else { | |
| 350 | - typeString = (String.format("%s_%s %s<%s>", Character.toString((char) (startIndex + i)), | |
| 351 | - Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i), | |
| 352 | - DATA_TYPE_PRIMITIVES.get(j).getName())); | |
| 353 | - } | |
| 354 | - alpha_type_list.add(typeString); | |
| 290 | + // create keyspace | |
| 291 | + session.execute("CREATE KEYSPACE test_nonprimitive_datatypes " + | |
| 292 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 293 | + session.execute("USE test_nonprimitive_datatypes"); | |
| 294 | + | |
| 295 | + // counters are not allowed inside collections | |
| 296 | + DATA_TYPE_PRIMITIVES.remove(DataType.counter()); | |
| 297 | + | |
| 298 | + // create UDT | |
| 299 | + List<String> alpha_type_list = new ArrayList<String>(); | |
| 300 | + int startIndex = (int) 'a'; | |
| 301 | + for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++) | |
| 302 | + for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) { | |
| 303 | + String typeString; | |
| 304 | + if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.MAP) { | |
| 305 | + typeString = (String.format("%s_%s %s<%s, %s>", Character.toString((char) (startIndex + i)), | |
| 306 | + Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i), | |
| 307 | + DATA_TYPE_PRIMITIVES.get(j).getName(), DATA_TYPE_PRIMITIVES.get(j).getName())); | |
| 308 | + } else if (DATA_TYPE_NON_PRIMITIVE_NAMES.get(i) == DataType.Name.TUPLE) { | |
| 309 | + typeString = (String.format("%s_%s frozen<%s<%s>>", Character.toString((char) (startIndex + i)), | |
| 310 | + Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i), | |
| 311 | + DATA_TYPE_PRIMITIVES.get(j).getName())); | |
| 312 | + } else { | |
| 313 | + typeString = (String.format("%s_%s %s<%s>", Character.toString((char) (startIndex + i)), | |
| 314 | + Character.toString((char) (startIndex + j)), DATA_TYPE_NON_PRIMITIVE_NAMES.get(i), | |
| 315 | + DATA_TYPE_PRIMITIVES.get(j).getName())); | |
| 355 | 316 | } |
| 317 | + alpha_type_list.add(typeString); | |
| 318 | + } | |
| 356 | 319 | |
| 357 | - session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list))); | |
| 358 | - session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)"); | |
| 359 | - | |
| 360 | - // insert UDT data | |
| 361 | - UserType alldatatypesDef = cluster.getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes"); | |
| 362 | - UDTValue alldatatypes = alldatatypesDef.newValue(); | |
| 363 | - | |
| 364 | - for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++) | |
| 365 | - for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) { | |
| 366 | - DataType.Name name = DATA_TYPE_NON_PRIMITIVE_NAMES.get(i); | |
| 367 | - DataType dataType = DATA_TYPE_PRIMITIVES.get(j); | |
| 368 | - | |
| 369 | - String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j)); | |
| 370 | - Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType); | |
| 371 | - switch (name) { | |
| 372 | - case LIST: | |
| 373 | - alldatatypes.setList(index, Lists.newArrayList(sampleElement)); | |
| 374 | - break; | |
| 375 | - case SET: | |
| 376 | - alldatatypes.setSet(index, Sets.newHashSet(sampleElement)); | |
| 377 | - break; | |
| 378 | - case MAP: | |
| 379 | - alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement)); | |
| 380 | - break; | |
| 381 | - case TUPLE: | |
| 382 | - alldatatypes.setTupleValue(index, TupleType.of(dataType).newValue(sampleElement)); | |
| 383 | - } | |
| 320 | + session.execute(String.format("CREATE TYPE alldatatypes (%s)", Joiner.on(',').join(alpha_type_list))); | |
| 321 | + session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<alldatatypes>)"); | |
| 322 | + | |
| 323 | + // insert UDT data | |
| 324 | + UserType alldatatypesDef = cluster.getMetadata().getKeyspace("test_nonprimitive_datatypes").getUserType("alldatatypes"); | |
| 325 | + UDTValue alldatatypes = alldatatypesDef.newValue(); | |
| 326 | + | |
| 327 | + for (int i = 0; i < DATA_TYPE_NON_PRIMITIVE_NAMES.size(); i++) | |
| 328 | + for (int j = 0; j < DATA_TYPE_PRIMITIVES.size(); j++) { | |
| 329 | + DataType.Name name = DATA_TYPE_NON_PRIMITIVE_NAMES.get(i); | |
| 330 | + DataType dataType = DATA_TYPE_PRIMITIVES.get(j); | |
| 331 | + | |
| 332 | + String index = Character.toString((char) (startIndex + i)) + "_" + Character.toString((char) (startIndex + j)); | |
| 333 | + Object sampleElement = PrimitiveTypeSamples.ALL.get(dataType); | |
| 334 | + switch (name) { | |
| 335 | + case LIST: | |
| 336 | + alldatatypes.setList(index, Lists.newArrayList(sampleElement)); | |
| 337 | + break; | |
| 338 | + case SET: | |
| 339 | + alldatatypes.setSet(index, Sets.newHashSet(sampleElement)); | |
| 340 | + break; | |
| 341 | + case MAP: | |
| 342 | + alldatatypes.setMap(index, ImmutableMap.of(sampleElement, sampleElement)); | |
| 343 | + break; | |
| 344 | + case TUPLE: | |
| 345 | + alldatatypes.setTupleValue(index, TupleType.of(dataType).newValue(sampleElement)); | |
| 384 | 346 | } |
| 347 | + } | |
| 385 | 348 | |
| 386 | - PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 387 | - session.execute(ins.bind(0, alldatatypes)); | |
| 388 | - | |
| 389 | - // retrieve and verify data | |
| 390 | - ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 391 | - List<Row> rows = rs.all(); | |
| 392 | - assertEquals(1, rows.size()); | |
| 349 | + PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 350 | + session.execute(ins.bind(0, alldatatypes)); | |
| 393 | 351 | |
| 394 | - Row row = rows.get(0); | |
| 352 | + // retrieve and verify data | |
| 353 | + ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 354 | + List<Row> rows = rs.all(); | |
| 355 | + assertEquals(1, rows.size()); | |
| 395 | 356 | |
| 396 | - assertEquals(row.getInt("a"), 0); | |
| 397 | - assertEquals(row.getUDTValue("b"), alldatatypes); | |
| 357 | + Row row = rows.get(0); | |
| 398 | 358 | |
| 399 | - } catch (Exception e) { | |
| 400 | - errorOut(); | |
| 401 | - throw e; | |
| 402 | - } | |
| 359 | + assertEquals(row.getInt("a"), 0); | |
| 360 | + assertEquals(row.getUDTValue("b"), alldatatypes); | |
| 403 | 361 | } |
| 404 | 362 | |
| 405 | 363 | /** |
| @@ -411,60 +369,53 @@ | ||
| 411 | 369 | @Test(groups = "short") |
| 412 | 370 | public void udtNestedTest() throws Exception { |
| 413 | 371 | final int MAX_NESTING_DEPTH = 4; |
| 372 | + // create keyspace | |
| 373 | + session.execute("CREATE KEYSPACE udtNestedTest " + | |
| 374 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 375 | + session.execute("USE udtNestedTest"); | |
| 376 | + | |
| 377 | + // create UDT | |
| 378 | + session.execute("CREATE TYPE depth_0 (age int, name text)"); | |
| 379 | + | |
| 380 | + for (int i = 1; i <= MAX_NESTING_DEPTH; i++) { | |
| 381 | + session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1))); | |
| 382 | + } | |
| 414 | 383 | |
| 415 | - try { | |
| 416 | - // create keyspace | |
| 417 | - session.execute("CREATE KEYSPACE udtNestedTest " + | |
| 418 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 419 | - session.execute("USE udtNestedTest"); | |
| 420 | - | |
| 421 | - // create UDT | |
| 422 | - session.execute("CREATE TYPE depth_0 (age int, name text)"); | |
| 423 | - | |
| 424 | - for (int i = 1; i <= MAX_NESTING_DEPTH; i++) { | |
| 425 | - session.execute(String.format("CREATE TYPE depth_%s (value frozen<depth_%s>)", String.valueOf(i), String.valueOf(i - 1))); | |
| 426 | - } | |
| 427 | - | |
| 428 | - session.execute(String.format("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<depth_0>, c frozen<depth_1>, d frozen<depth_2>, e frozen<depth_3>," + | |
| 429 | - "f frozen<depth_%s>)", MAX_NESTING_DEPTH)); | |
| 430 | - | |
| 431 | - // insert UDT data | |
| 432 | - UserType depthZeroDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0"); | |
| 433 | - UDTValue depthZero = depthZeroDef.newValue().setInt("age", 42).setString("name", "Bob"); | |
| 384 | + session.execute(String.format("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<depth_0>, c frozen<depth_1>, d frozen<depth_2>, e frozen<depth_3>," + | |
| 385 | + "f frozen<depth_%s>)", MAX_NESTING_DEPTH)); | |
| 434 | 386 | |
| 435 | - UserType depthOneDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1"); | |
| 436 | - UDTValue depthOne = depthOneDef.newValue().setUDTValue("value", depthZero); | |
| 387 | + // insert UDT data | |
| 388 | + UserType depthZeroDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_0"); | |
| 389 | + UDTValue depthZero = depthZeroDef.newValue().setInt("age", 42).setString("name", "Bob"); | |
| 437 | 390 | |
| 438 | - UserType depthTwoDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2"); | |
| 439 | - UDTValue depthTwo = depthTwoDef.newValue().setUDTValue("value", depthOne); | |
| 391 | + UserType depthOneDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_1"); | |
| 392 | + UDTValue depthOne = depthOneDef.newValue().setUDTValue("value", depthZero); | |
| 440 | 393 | |
| 441 | - UserType depthThreeDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3"); | |
| 442 | - UDTValue depthThree = depthThreeDef.newValue().setUDTValue("value", depthTwo); | |
| 394 | + UserType depthTwoDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_2"); | |
| 395 | + UDTValue depthTwo = depthTwoDef.newValue().setUDTValue("value", depthOne); | |
| 443 | 396 | |
| 444 | - UserType depthFourDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4"); | |
| 445 | - UDTValue depthFour = depthFourDef.newValue().setUDTValue("value", depthThree); | |
| 397 | + UserType depthThreeDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_3"); | |
| 398 | + UDTValue depthThree = depthThreeDef.newValue().setUDTValue("value", depthTwo); | |
| 446 | 399 | |
| 447 | - PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b, c, d, e, f) VALUES (?, ?, ?, ?, ?, ?)"); | |
| 448 | - session.execute(ins.bind(0, depthZero, depthOne, depthTwo, depthThree, depthFour)); | |
| 400 | + UserType depthFourDef = cluster.getMetadata().getKeyspace("udtNestedTest").getUserType("depth_4"); | |
| 401 | + UDTValue depthFour = depthFourDef.newValue().setUDTValue("value", depthThree); | |
| 449 | 402 | |
| 450 | - // retrieve and verify data | |
| 451 | - ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 452 | - List<Row> rows = rs.all(); | |
| 453 | - assertEquals(1, rows.size()); | |
| 403 | + PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b, c, d, e, f) VALUES (?, ?, ?, ?, ?, ?)"); | |
| 404 | + session.execute(ins.bind(0, depthZero, depthOne, depthTwo, depthThree, depthFour)); | |
| 454 | 405 | |
| 455 | - Row row = rows.get(0); | |
| 406 | + // retrieve and verify data | |
| 407 | + ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 408 | + List<Row> rows = rs.all(); | |
| 409 | + assertEquals(1, rows.size()); | |
| 456 | 410 | |
| 457 | - assertEquals(row.getInt("a"), 0); | |
| 458 | - assertEquals(row.getUDTValue("b"), depthZero); | |
| 459 | - assertEquals(row.getUDTValue("c"), depthOne); | |
| 460 | - assertEquals(row.getUDTValue("d"), depthTwo); | |
| 461 | - assertEquals(row.getUDTValue("e"), depthThree); | |
| 462 | - assertEquals(row.getUDTValue("f"), depthFour); | |
| 411 | + Row row = rows.get(0); | |
| 463 | 412 | |
| 464 | - } catch (Exception e) { | |
| 465 | - errorOut(); | |
| 466 | - throw e; | |
| 467 | - } | |
| 413 | + assertEquals(row.getInt("a"), 0); | |
| 414 | + assertEquals(row.getUDTValue("b"), depthZero); | |
| 415 | + assertEquals(row.getUDTValue("c"), depthOne); | |
| 416 | + assertEquals(row.getUDTValue("d"), depthTwo); | |
| 417 | + assertEquals(row.getUDTValue("e"), depthThree); | |
| 418 | + assertEquals(row.getUDTValue("f"), depthFour); | |
| 468 | 419 | } |
| 469 | 420 | |
| 470 | 421 | /** |
| @@ -475,51 +426,45 @@ | ||
| 475 | 426 | */ |
| 476 | 427 | @Test(groups = "short") |
| 477 | 428 | public void testUdtsWithNulls() throws Exception { |
| 478 | - try { | |
| 479 | - // create keyspace | |
| 480 | - session.execute("CREATE KEYSPACE testUdtsWithNulls " + | |
| 481 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 482 | - session.execute("USE testUdtsWithNulls"); | |
| 483 | - | |
| 484 | - // create UDT | |
| 485 | - session.execute("CREATE TYPE user (a text, b int, c uuid, d blob)"); | |
| 486 | - session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)"); | |
| 429 | + // create keyspace | |
| 430 | + session.execute("CREATE KEYSPACE testUdtsWithNulls " + | |
| 431 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 432 | + session.execute("USE testUdtsWithNulls"); | |
| 487 | 433 | |
| 488 | - // insert UDT data | |
| 489 | - UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user"); | |
| 490 | - UDTValue userType = userTypeDef.newValue().setString("a", null).setInt("b", 0).setUUID("c", null).setBytes("d", null); | |
| 434 | + // create UDT | |
| 435 | + session.execute("CREATE TYPE user (a text, b int, c uuid, d blob)"); | |
| 436 | + session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)"); | |
| 491 | 437 | |
| 492 | - PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 493 | - session.execute(ins.bind(0, userType)); | |
| 438 | + // insert UDT data | |
| 439 | + UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithNulls").getUserType("user"); | |
| 440 | + UDTValue userType = userTypeDef.newValue().setString("a", null).setInt("b", 0).setUUID("c", null).setBytes("d", null); | |
| 494 | 441 | |
| 495 | - // retrieve and verify data | |
| 496 | - ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 497 | - List<Row> rows = rs.all(); | |
| 498 | - assertEquals(1, rows.size()); | |
| 442 | + PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) VALUES (?, ?)"); | |
| 443 | + session.execute(ins.bind(0, userType)); | |
| 499 | 444 | |
| 500 | - Row row = rows.get(0); | |
| 445 | + // retrieve and verify data | |
| 446 | + ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 447 | + List<Row> rows = rs.all(); | |
| 448 | + assertEquals(1, rows.size()); | |
| 501 | 449 | |
| 502 | - assertEquals(row.getInt("a"), 0); | |
| 503 | - assertEquals(row.getUDTValue("b"), userType); | |
| 450 | + Row row = rows.get(0); | |
| 504 | 451 | |
| 505 | - // test empty strings | |
| 506 | - userType = userTypeDef.newValue().setString("a", "").setInt("b", 0).setUUID("c", null).setBytes("d", ByteBuffer.allocate(0)); | |
| 507 | - session.execute(ins.bind(0, userType)); | |
| 452 | + assertEquals(row.getInt("a"), 0); | |
| 453 | + assertEquals(row.getUDTValue("b"), userType); | |
| 508 | 454 | |
| 509 | - // retrieve and verify data | |
| 510 | - rs = session.execute("SELECT * FROM mytable"); | |
| 511 | - rows = rs.all(); | |
| 512 | - assertEquals(1, rows.size()); | |
| 455 | + // test empty strings | |
| 456 | + userType = userTypeDef.newValue().setString("a", "").setInt("b", 0).setUUID("c", null).setBytes("d", ByteBuffer.allocate(0)); | |
| 457 | + session.execute(ins.bind(0, userType)); | |
| 513 | 458 | |
| 514 | - row = rows.get(0); | |
| 459 | + // retrieve and verify data | |
| 460 | + rs = session.execute("SELECT * FROM mytable"); | |
| 461 | + rows = rs.all(); | |
| 462 | + assertEquals(1, rows.size()); | |
| 515 | 463 | |
| 516 | - assertEquals(row.getInt("a"), 0); | |
| 517 | - assertEquals(row.getUDTValue("b"), userType); | |
| 464 | + row = rows.get(0); | |
| 518 | 465 | |
| 519 | - } catch (Exception e) { | |
| 520 | - errorOut(); | |
| 521 | - throw e; | |
| 522 | - } | |
| 466 | + assertEquals(row.getInt("a"), 0); | |
| 467 | + assertEquals(row.getUDTValue("b"), userType); | |
| 523 | 468 | } |
| 524 | 469 | |
| 525 | 470 | /** |
| @@ -529,52 +474,46 @@ | ||
| 529 | 474 | */ |
| 530 | 475 | @Test(groups = "short") |
| 531 | 476 | public void testUdtsWithCollectionNulls() throws Exception { |
| 532 | - try { | |
| 533 | - // create keyspace | |
| 534 | - session.execute("CREATE KEYSPACE testUdtsWithCollectionNulls " + | |
| 535 | - "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 536 | - session.execute("USE testUdtsWithCollectionNulls"); | |
| 537 | - | |
| 538 | - // create UDT | |
| 539 | - session.execute("CREATE TYPE user (a List<text>, b Set<text>, c Map<text, text>, d frozen<Tuple<text>>)"); | |
| 540 | - session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)"); | |
| 541 | - | |
| 542 | - // insert null UDT data | |
| 543 | - PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) " + | |
| 544 | - "VALUES (0, { a: ?, b: ?, c: ?, d: ? })"); | |
| 545 | - session.execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null)); | |
| 546 | - | |
| 547 | - // retrieve and verify data | |
| 548 | - ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 549 | - List<Row> rows = rs.all(); | |
| 550 | - assertEquals(1, rows.size()); | |
| 551 | - | |
| 552 | - Row row = rows.get(0); | |
| 553 | - assertEquals(row.getInt("a"), 0); | |
| 554 | - | |
| 555 | - UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user"); | |
| 556 | - UDTValue userType = userTypeDef.newValue().setList("a", null).setSet("b", null).setMap("c", null).setTupleValue("d", null); | |
| 557 | - assertEquals(row.getUDTValue("b"), userType); | |
| 558 | - | |
| 559 | - // test missing UDT args | |
| 560 | - ins = session.prepare("INSERT INTO mytable (a, b) " + | |
| 561 | - "VALUES (1, { a: ? })"); | |
| 562 | - session.execute(ins.bind().setList(0, new ArrayList<Object>())); | |
| 563 | - | |
| 564 | - // retrieve and verify data | |
| 565 | - rs = session.execute("SELECT * FROM mytable"); | |
| 566 | - rows = rs.all(); | |
| 567 | - assertEquals(2, rows.size()); | |
| 568 | - | |
| 569 | - row = rows.get(0); | |
| 570 | - assertEquals(row.getInt("a"), 1); | |
| 571 | - | |
| 572 | - userType = userTypeDef.newValue().setList(0, new ArrayList<Object>()); | |
| 573 | - assertEquals(row.getUDTValue("b"), userType); | |
| 574 | - | |
| 575 | - } catch (Exception e) { | |
| 576 | - errorOut(); | |
| 577 | - throw e; | |
| 578 | - } | |
| 477 | + // create keyspace | |
| 478 | + session.execute("CREATE KEYSPACE testUdtsWithCollectionNulls " + | |
| 479 | + "WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor': '1'}"); | |
| 480 | + session.execute("USE testUdtsWithCollectionNulls"); | |
| 481 | + | |
| 482 | + // create UDT | |
| 483 | + session.execute("CREATE TYPE user (a List<text>, b Set<text>, c Map<text, text>, d frozen<Tuple<text>>)"); | |
| 484 | + session.execute("CREATE TABLE mytable (a int PRIMARY KEY, b frozen<user>)"); | |
| 485 | + | |
| 486 | + // insert null UDT data | |
| 487 | + PreparedStatement ins = session.prepare("INSERT INTO mytable (a, b) " + | |
| 488 | + "VALUES (0, { a: ?, b: ?, c: ?, d: ? })"); | |
| 489 | + session.execute(ins.bind().setList(0, null).setSet(1, null).setMap(2, null).setTupleValue(3, null)); | |
| 490 | + | |
| 491 | + // retrieve and verify data | |
| 492 | + ResultSet rs = session.execute("SELECT * FROM mytable"); | |
| 493 | + List<Row> rows = rs.all(); | |
| 494 | + assertEquals(1, rows.size()); | |
| 495 | + | |
| 496 | + Row row = rows.get(0); | |
| 497 | + assertEquals(row.getInt("a"), 0); | |
| 498 | + | |
| 499 | + UserType userTypeDef = cluster.getMetadata().getKeyspace("testUdtsWithCollectionNulls").getUserType("user"); | |
| 500 | + UDTValue userType = userTypeDef.newValue().setList("a", null).setSet("b", null).setMap("c", null).setTupleValue("d", null); | |
| 501 | + assertEquals(row.getUDTValue("b"), userType); | |
| 502 | + | |
| 503 | + // test missing UDT args | |
| 504 | + ins = session.prepare("INSERT INTO mytable (a, b) " + | |
| 505 | + "VALUES (1, { a: ? })"); | |
| 506 | + session.execute(ins.bind().setList(0, new ArrayList<Object>())); | |
| 507 | + | |
| 508 | + // retrieve and verify data | |
| 509 | + rs = session.execute("SELECT * FROM mytable"); | |
| 510 | + rows = rs.all(); | |
| 511 | + assertEquals(2, rows.size()); | |
| 512 | + | |
| 513 | + row = rows.get(0); | |
| 514 | + assertEquals(row.getInt("a"), 1); | |
| 515 | + | |
| 516 | + userType = userTypeDef.newValue().setList(0, new ArrayList<Object>()); | |
| 517 | + assertEquals(row.getUDTValue("b"), userType); | |
| 579 | 518 | } |
| 580 | 519 | } |
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java +4 −3
| @@ -48,7 +48,8 @@ | ||
| 48 | 48 | @BeforeMethod(groups = "short") |
| 49 | 49 | public void beforeMethod() { |
| 50 | 50 | cluster = Cluster.builder() |
| 51 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 51 | + .addContactPointsWithPorts(scassandras.address(1)) | |
| 52 | + .withAddressTranslater(scassandras.addressTranslator()) | |
| 52 | 53 | .withRetryPolicy(FallthroughRetryPolicy.INSTANCE) |
| 53 | 54 | .build(); |
| 54 | 55 | session = cluster.connect(); |
| @@ -129,7 +130,7 @@ | ||
| 129 | 130 | return session.execute("mock query"); |
| 130 | 131 | } |
| 131 | 132 | |
| 132 | - @AfterMethod(groups = "short") | |
| 133 | + @AfterMethod(groups = "short", alwaysRun = true) | |
| 133 | 134 | public void afterMethod() { |
| 134 | 135 | for (Scassandra node : scassandras.nodes()) { |
| 135 | 136 | node.primingClient().clearAllPrimes(); |
| @@ -138,7 +139,7 @@ | ||
| 138 | 139 | cluster.close(); |
| 139 | 140 | } |
| 140 | 141 | |
| 141 | - @AfterClass(groups = "short") | |
| 142 | + @AfterClass(groups = "short", alwaysRun = true) | |
| 142 | 143 | public void afterClass() { |
| 143 | 144 | if (scassandras != null) |
| 144 | 145 | scassandras.stop(); |
modified driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java +40 −50
| @@ -15,16 +15,14 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.Cluster; |
| 20 | 20 | import com.datastax.driver.core.TestUtils; |
| 21 | 21 | import com.datastax.driver.core.WriteType; |
| 22 | 22 | import org.testng.annotations.Test; |
| 23 | 23 | |
| 24 | -import java.net.InetAddress; | |
| 25 | 24 | import java.net.InetSocketAddress; |
| 26 | 25 | |
| 27 | -import static com.datastax.driver.core.CCMBridge.ipOfNode; | |
| 28 | 26 | import static com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM; |
| 29 | 27 | import static org.assertj.core.api.Assertions.assertThat; |
| 30 | 28 | import static org.testng.Assert.assertEquals; |
| @@ -33,7 +31,7 @@ | ||
| 33 | 31 | /** |
| 34 | 32 | * Tests Exception classes with separate clusters per test, when applicable |
| 35 | 33 | */ |
| 36 | -public class ExceptionsTest { | |
| 34 | +public class ExceptionsTest extends CCMTestsSupport { | |
| 37 | 35 | |
| 38 | 36 | private InetSocketAddress address1 = new InetSocketAddress("127.0.0.1", 9042); |
| 39 | 37 | private InetSocketAddress address2 = new InetSocketAddress("127.0.0.2", 9042); |
| @@ -45,53 +43,45 @@ | ||
| 45 | 43 | */ |
| 46 | 44 | @Test(groups = "short") |
| 47 | 45 | public void alreadyExistsException() throws Throwable { |
| 48 | - Cluster.Builder builder = Cluster.builder(); | |
| 49 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); | |
| 46 | + String keyspace = "TestKeyspace"; | |
| 47 | + String table = "TestTable"; | |
| 48 | + | |
| 49 | + String[] cqlCommands = new String[]{ | |
| 50 | + String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1), | |
| 51 | + "USE " + keyspace, | |
| 52 | + String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table) | |
| 53 | + }; | |
| 54 | + | |
| 55 | + // Create the schema once | |
| 56 | + session.execute(cqlCommands[0]); | |
| 57 | + session.execute(cqlCommands[1]); | |
| 58 | + session.execute(cqlCommands[2]); | |
| 59 | + | |
| 60 | + // Try creating the keyspace again | |
| 50 | 61 | try { |
| 51 | - String keyspace = "TestKeyspace"; | |
| 52 | - String table = "TestTable"; | |
| 53 | - | |
| 54 | - String[] cqlCommands = new String[]{ | |
| 55 | - String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1), | |
| 56 | - "USE " + keyspace, | |
| 57 | - String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table) | |
| 58 | - }; | |
| 59 | - | |
| 60 | - // Create the schema once | |
| 61 | - c.session.execute(cqlCommands[0]); | |
| 62 | - c.session.execute(cqlCommands[1]); | |
| 63 | - c.session.execute(cqlCommands[2]); | |
| 64 | - | |
| 65 | - // Try creating the keyspace again | |
| 66 | - try { | |
| 67 | - c.session.execute(cqlCommands[0]); | |
| 68 | - } catch (AlreadyExistsException e) { | |
| 69 | - String expected = String.format("Keyspace %s already exists", keyspace.toLowerCase()); | |
| 70 | - assertEquals(e.getMessage(), expected); | |
| 71 | - assertEquals(e.getKeyspace(), keyspace.toLowerCase()); | |
| 72 | - assertEquals(e.getTable(), null); | |
| 73 | - assertEquals(e.wasTableCreation(), false); | |
| 74 | - assertEquals(e.getHost(), InetAddress.getByName(ipOfNode(1))); | |
| 75 | - assertEquals(e.getAddress(), new InetSocketAddress(ipOfNode(1), 9042)); | |
| 76 | - } | |
| 77 | - | |
| 78 | - c.session.execute(cqlCommands[1]); | |
| 79 | - | |
| 80 | - // Try creating the table again | |
| 81 | - try { | |
| 82 | - c.session.execute(cqlCommands[2]); | |
| 83 | - } catch (AlreadyExistsException e) { | |
| 84 | - // is released | |
| 85 | - assertEquals(e.getKeyspace(), keyspace.toLowerCase()); | |
| 86 | - assertEquals(e.getTable(), table.toLowerCase()); | |
| 87 | - assertEquals(e.wasTableCreation(), true); | |
| 88 | - assertEquals(e.getHost(), InetAddress.getByName(ipOfNode(1))); | |
| 89 | - assertEquals(e.getAddress(), new InetSocketAddress(ipOfNode(1), 9042)); | |
| 90 | - } | |
| 91 | - } catch (Throwable e) { | |
| 92 | - throw e; | |
| 93 | - } finally { | |
| 94 | - c.discard(); | |
| 62 | + session.execute(cqlCommands[0]); | |
| 63 | + } catch (AlreadyExistsException e) { | |
| 64 | + String expected = String.format("Keyspace %s already exists", keyspace.toLowerCase()); | |
| 65 | + assertEquals(e.getMessage(), expected); | |
| 66 | + assertEquals(e.getKeyspace(), keyspace.toLowerCase()); | |
| 67 | + assertEquals(e.getTable(), null); | |
| 68 | + assertEquals(e.wasTableCreation(), false); | |
| 69 | + assertEquals(e.getHost(), getHostAddress(1).getAddress()); | |
| 70 | + assertEquals(e.getAddress(), getHostAddress(1)); | |
| 71 | + } | |
| 72 | + | |
| 73 | + session.execute(cqlCommands[1]); | |
| 74 | + | |
| 75 | + // Try creating the table again | |
| 76 | + try { | |
| 77 | + session.execute(cqlCommands[2]); | |
| 78 | + } catch (AlreadyExistsException e) { | |
| 79 | + // is released | |
| 80 | + assertEquals(e.getKeyspace(), keyspace.toLowerCase()); | |
| 81 | + assertEquals(e.getTable(), table.toLowerCase()); | |
| 82 | + assertEquals(e.wasTableCreation(), true); | |
| 83 | + assertEquals(e.getHost(), getHostAddress(1).getAddress()); | |
| 84 | + assertEquals(e.getAddress(), getHostAddress(1)); | |
| 95 | 85 | } |
| 96 | 86 | } |
| 97 | 87 |
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +3 −2
| @@ -61,7 +61,8 @@ | ||
| 61 | 61 | scassandras.init(); |
| 62 | 62 | |
| 63 | 63 | cluster = Cluster.builder() |
| 64 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 64 | + .addContactPointsWithPorts(scassandras.address(1)) | |
| 65 | + .withAddressTranslater(scassandras.addressTranslator()) | |
| 65 | 66 | .withRetryPolicy(retryPolicy) |
| 66 | 67 | .withLoadBalancingPolicy(new SortingLoadBalancingPolicy()) |
| 67 | 68 | .withNettyOptions(nonQuietClusterCloseOptions) |
| @@ -128,7 +129,7 @@ | ||
| 128 | 129 | assertThat(scassandras.node(hostNumber).activityClient().retrieveQueries()).hasSize(times); |
| 129 | 130 | } |
| 130 | 131 | |
| 131 | - @AfterMethod(groups = "short") | |
| 132 | + @AfterMethod(groups = "short", alwaysRun = true) | |
| 132 | 133 | public void afterMethod() { |
| 133 | 134 | if (cluster != null) |
| 134 | 135 | cluster.close(); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/CloseableLoadBalancingPolicyTest.java +17 −15
| @@ -15,32 +15,34 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.policies; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMConfig; | |
| 19 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 20 | import com.datastax.driver.core.Cluster; |
| 20 | 21 | import org.testng.annotations.Test; |
| 21 | 22 | |
| 22 | 23 | import static org.assertj.core.api.Assertions.assertThat; |
| 23 | 24 | |
| 24 | -public class CloseableLoadBalancingPolicyTest { | |
| 25 | +@CCMConfig(createSession = false) | |
| 26 | +public class CloseableLoadBalancingPolicyTest extends CCMTestsSupport { | |
| 27 | + | |
| 28 | + private CloseMonitoringPolicy policy; | |
| 29 | + | |
| 25 | 30 | @Test(groups = "short") |
| 26 | 31 | public void should_be_invoked_at_shutdown() { |
| 27 | - CloseMonitoringPolicy policy = new CloseMonitoringPolicy(Policies.defaultLoadBalancingPolicy()); | |
| 28 | - CCMBridge ccm = null; | |
| 29 | - Cluster cluster = null; | |
| 30 | 32 | try { |
| 31 | - ccm = CCMBridge.builder("test").withNodes(1).build(); | |
| 32 | - cluster = Cluster.builder() | |
| 33 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 34 | - .withLoadBalancingPolicy(policy) | |
| 35 | - .build(); | |
| 36 | 33 | cluster.connect(); |
| 34 | + cluster.close(); | |
| 37 | 35 | } finally { |
| 38 | - if (cluster != null) | |
| 39 | - cluster.close(); | |
| 40 | - if (ccm != null) | |
| 41 | - ccm.remove(); | |
| 36 | + assertThat(policy.wasClosed).isTrue(); | |
| 42 | 37 | } |
| 43 | - assertThat(policy.wasClosed).isTrue(); | |
| 38 | + } | |
| 39 | + | |
| 40 | + @Override | |
| 41 | + public Cluster.Builder createClusterBuilder() { | |
| 42 | + policy = new CloseMonitoringPolicy(Policies.defaultLoadBalancingPolicy()); | |
| 43 | + return Cluster.builder() | |
| 44 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 45 | + .withLoadBalancingPolicy(policy); | |
| 44 | 46 | } |
| 45 | 47 | |
| 46 | 48 | static class CloseMonitoringPolicy extends DelegatingLoadBalancingPolicy { |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +26 −13
| @@ -41,6 +41,7 @@ | ||
| 41 | 41 | public class DCAwareRoundRobinPolicyTest { |
| 42 | 42 | |
| 43 | 43 | Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class); |
| 44 | + Level originalLevel; | |
| 44 | 45 | MemoryAppender logs; |
| 45 | 46 | QueryTracker queryTracker; |
| 46 | 47 | |
| @@ -50,15 +51,16 @@ | ||
| 50 | 51 | @BeforeMethod(groups = "short") |
| 51 | 52 | public void setUp() { |
| 52 | 53 | initMocks(this); |
| 54 | + originalLevel = policyLogger.getLevel(); | |
| 53 | 55 | policyLogger.setLevel(Level.WARN); |
| 54 | 56 | logs = new MemoryAppender(); |
| 55 | 57 | policyLogger.addAppender(logs); |
| 56 | 58 | queryTracker = new QueryTracker(); |
| 57 | 59 | } |
| 58 | 60 | |
| 59 | - @AfterMethod(groups = "short") | |
| 61 | + @AfterMethod(groups = "short", alwaysRun = true) | |
| 60 | 62 | public void tearDown() { |
| 61 | - policyLogger.setLevel(null); | |
| 63 | + policyLogger.setLevel(originalLevel); | |
| 62 | 64 | policyLogger.removeAppender(logs); |
| 63 | 65 | } |
| 64 | 66 | |
| @@ -79,7 +81,8 @@ | ||
| 79 | 81 | // given: a 10 node 2 DC cluster. |
| 80 | 82 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build(); |
| 81 | 83 | Cluster cluster = builder() |
| 82 | - .addContactPoint(sCluster.address(1, 1)) | |
| 84 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 85 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 83 | 86 | .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build()) |
| 84 | 87 | .build(); |
| 85 | 88 | try { |
| @@ -111,7 +114,8 @@ | ||
| 111 | 114 | // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts. |
| 112 | 115 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build(); |
| 113 | 116 | Cluster cluster = builder() |
| 114 | - .addContactPoint(sCluster.address(1, 1)) | |
| 117 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 118 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 115 | 119 | .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).withUsedHostsPerRemoteDc(2).build()) |
| 116 | 120 | .build(); |
| 117 | 121 | |
| @@ -153,7 +157,8 @@ | ||
| 153 | 157 | // given: a 10 node 2 DC cluster with DC policy with 2 remote hosts. |
| 154 | 158 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5, 5).build(); |
| 155 | 159 | Cluster cluster = builder() |
| 156 | - .addContactPoint(sCluster.address(1, 1)) | |
| 160 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 161 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 157 | 162 | .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build()) |
| 158 | 163 | .build(); |
| 159 | 164 | |
| @@ -196,7 +201,8 @@ | ||
| 196 | 201 | // a local consistency level. |
| 197 | 202 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); |
| 198 | 203 | Cluster cluster = builder() |
| 199 | - .addContactPoint(sCluster.address(1, 1)) | |
| 204 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 205 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 200 | 206 | .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build()) |
| 201 | 207 | .build(); |
| 202 | 208 | |
| @@ -241,7 +247,8 @@ | ||
| 241 | 247 | // a local consistency level. |
| 242 | 248 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); |
| 243 | 249 | Cluster cluster = builder() |
| 244 | - .addContactPoint(sCluster.address(1, 1)) | |
| 250 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 251 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 245 | 252 | .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder() |
| 246 | 253 | .allowRemoteDCsForLocalConsistencyLevel() |
| 247 | 254 | .withUsedHostsPerRemoteDc(2).build()) |
| @@ -286,7 +293,8 @@ | ||
| 286 | 293 | DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(), |
| 287 | 294 | Lists.newArrayList(datacenter(2))); |
| 288 | 295 | Cluster cluster = builder() |
| 289 | - .addContactPoint(sCluster.address(1, 1)) | |
| 296 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 297 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 290 | 298 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 291 | 299 | .build(); |
| 292 | 300 | |
| @@ -339,7 +347,8 @@ | ||
| 339 | 347 | DCAwareRoundRobinPolicy.builder().withUsedHostsPerRemoteDc(2).build(), |
| 340 | 348 | Lists.newArrayList(datacenter(1), datacenter(2))); |
| 341 | 349 | Cluster cluster = builder() |
| 342 | - .addContactPoint(sCluster.address(1, 1)) | |
| 350 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 351 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 343 | 352 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 344 | 353 | .build(); |
| 345 | 354 | |
| @@ -390,7 +399,8 @@ | ||
| 390 | 399 | DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build()); |
| 391 | 400 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); |
| 392 | 401 | Cluster cluster = builder() |
| 393 | - .addContactPoint(sCluster.address(1, 1)) | |
| 402 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 403 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 394 | 404 | .withLoadBalancingPolicy(policy) |
| 395 | 405 | .build(); |
| 396 | 406 | |
| @@ -429,7 +439,8 @@ | ||
| 429 | 439 | DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build()); |
| 430 | 440 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); |
| 431 | 441 | Cluster cluster = builder() |
| 432 | - .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1)) | |
| 442 | + .addContactPointsWithPorts(sCluster.address(1, 1), sCluster.address(2, 1)) | |
| 443 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 433 | 444 | .withLoadBalancingPolicy(policy) |
| 434 | 445 | .build(); |
| 435 | 446 | |
| @@ -467,7 +478,8 @@ | ||
| 467 | 478 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); |
| 468 | 479 | DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(1)).build()); |
| 469 | 480 | Cluster cluster = builder() |
| 470 | - .addContactPoints(sCluster.address(1, 1)) | |
| 481 | + .addContactPointsWithPorts(sCluster.address(1, 1)) | |
| 482 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 471 | 483 | .withLoadBalancingPolicy(policy) |
| 472 | 484 | .build(); |
| 473 | 485 | |
| @@ -506,7 +518,8 @@ | ||
| 506 | 518 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); |
| 507 | 519 | DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().withLocalDc(datacenter(3)).build()); |
| 508 | 520 | Cluster cluster = builder() |
| 509 | - .addContactPoints(sCluster.address(1, 1), sCluster.address(2, 1)) | |
| 521 | + .addContactPointsWithPorts(sCluster.address(1, 1), sCluster.address(2, 1)) | |
| 522 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 510 | 523 | .withLoadBalancingPolicy(policy) |
| 511 | 524 | .build(); |
| 512 | 525 |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +2 −2
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.policies; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 19 | 18 | import com.datastax.driver.core.Cluster; |
| 20 | 19 | import com.datastax.driver.core.Metrics; |
| 21 | 20 | import com.datastax.driver.core.Session; |
| @@ -107,7 +106,8 @@ | ||
| 107 | 106 | Collections.singletonList(host1.getSocketAddress())); |
| 108 | 107 | |
| 109 | 108 | Cluster whiteListedCluster = Cluster.builder() |
| 110 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 109 | + .addContactPointsWithPorts(scassandras.address(1)) | |
| 110 | + .withAddressTranslater(scassandras.addressTranslator()) | |
| 111 | 111 | .withRetryPolicy(retryPolicy) |
| 112 | 112 | .withLoadBalancingPolicy(firstHostOnlyPolicy) |
| 113 | 113 | .build(); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +47 −44
| @@ -17,11 +17,15 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | 19 | import com.google.common.base.Objects; |
| 20 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 20 | 21 | import org.mockito.Mockito; |
| 21 | 22 | import org.mockito.verification.VerificationMode; |
| 22 | 23 | import org.testng.annotations.Test; |
| 23 | 24 | |
| 25 | +import java.util.concurrent.TimeUnit; | |
| 26 | + | |
| 24 | 27 | import static com.datastax.driver.core.ConsistencyLevel.*; |
| 28 | +import static com.datastax.driver.core.TestUtils.ipOfNode; | |
| 25 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 26 | 30 | import static org.mockito.Matchers.any; |
| 27 | 31 | import static org.mockito.Matchers.anyInt; |
| @@ -33,59 +37,58 @@ | ||
| 33 | 37 | * receivedResponses in primed responses. |
| 34 | 38 | * If that becomes possible in the future, we could refactor this test. |
| 35 | 39 | */ |
| 36 | -public class DowngradingConsistencyRetryPolicyIntegrationTest { | |
| 40 | +@CCMConfig(dirtiesContext = true, createCluster = false, numberOfNodes = 3) | |
| 41 | +public class DowngradingConsistencyRetryPolicyIntegrationTest extends CCMTestsSupport { | |
| 37 | 42 | |
| 38 | 43 | @Test(groups = "long") |
| 39 | 44 | public void should_downgrade_if_not_enough_replicas_for_requested_CL() { |
| 40 | - CCMBridge ccm = null; | |
| 41 | - Cluster cluster = null; | |
| 42 | - try { | |
| 43 | - // 3-node cluster, keyspace with RF = 3 | |
| 44 | - ccm = CCMBridge.builder(this.getClass().getName()).withNodes(3).build(); | |
| 45 | - cluster = Cluster.builder() | |
| 46 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 47 | - .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE)) | |
| 48 | - .build(); | |
| 49 | - Session session = cluster.connect(); | |
| 50 | - | |
| 51 | - session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}"); | |
| 52 | - session.execute("CREATE TABLE test.foo(k int primary key)"); | |
| 53 | - session.execute("INSERT INTO test.foo(k) VALUES (0)"); | |
| 54 | - | |
| 55 | - // All replicas up: should achieve all levels without downgrading | |
| 56 | - checkAchievedConsistency(ALL, ALL, session); | |
| 57 | - checkAchievedConsistency(QUORUM, QUORUM, session); | |
| 58 | - checkAchievedConsistency(ONE, ONE, session); | |
| 59 | - | |
| 60 | - ccm.stop(1); | |
| 61 | - ccm.waitForDown(1); | |
| 62 | - // Two replicas remaining: should downgrade to 2 when CL > 2 | |
| 63 | - checkAchievedConsistency(ALL, TWO, session); | |
| 64 | - checkAchievedConsistency(QUORUM, QUORUM, session); // since RF = 3, quorum is still achievable with two nodes | |
| 65 | - checkAchievedConsistency(TWO, TWO, session); | |
| 66 | - checkAchievedConsistency(ONE, ONE, session); | |
| 67 | - | |
| 68 | - ccm.stop(2); | |
| 69 | - ccm.waitForDown(2); | |
| 70 | - // One replica remaining: should downgrade to 1 when CL > 1 | |
| 71 | - checkAchievedConsistency(ALL, ONE, session); | |
| 72 | - checkAchievedConsistency(QUORUM, ONE, session); | |
| 73 | - checkAchievedConsistency(TWO, ONE, session); | |
| 74 | - checkAchievedConsistency(ONE, ONE, session); | |
| 75 | - | |
| 76 | - } finally { | |
| 77 | - if (cluster != null) | |
| 78 | - cluster.close(); | |
| 79 | - if (ccm != null) | |
| 80 | - ccm.remove(); | |
| 81 | - } | |
| 45 | + Cluster cluster = register(Cluster.builder() | |
| 46 | + .addContactPointsWithPorts(getHostAddress(1)) | |
| 47 | + .withAddressTranslater(getAddressTranslator()) | |
| 48 | + .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE)) | |
| 49 | + .build()); | |
| 50 | + Session session = cluster.connect(); | |
| 51 | + | |
| 52 | + String ks = TestUtils.getAvailableKeyspaceName(); | |
| 53 | + session.execute(String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}", ks)); | |
| 54 | + // tests fail randomly here with InvalidQueryException: Keyspace 'xxx' does not exist | |
| 55 | + Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); | |
| 56 | + session.execute(String.format("USE %s", ks)); | |
| 57 | + session.execute("CREATE TABLE foo(k int primary key)"); | |
| 58 | + session.execute("INSERT INTO foo(k) VALUES (0)"); | |
| 59 | + | |
| 60 | + // All replicas up: should achieve all levels without downgrading | |
| 61 | + checkAchievedConsistency(ALL, ALL, session); | |
| 62 | + checkAchievedConsistency(QUORUM, QUORUM, session); | |
| 63 | + checkAchievedConsistency(ONE, ONE, session); | |
| 64 | + | |
| 65 | + stopAndWait(1, cluster); | |
| 66 | + // Two replicas remaining: should downgrade to 2 when CL > 2 | |
| 67 | + checkAchievedConsistency(ALL, TWO, session); | |
| 68 | + checkAchievedConsistency(QUORUM, QUORUM, session); // since RF = 3, quorum is still achievable with two nodes | |
| 69 | + checkAchievedConsistency(TWO, TWO, session); | |
| 70 | + checkAchievedConsistency(ONE, ONE, session); | |
| 71 | + | |
| 72 | + stopAndWait(2, cluster); | |
| 73 | + // One replica remaining: should downgrade to 1 when CL > 1 | |
| 74 | + checkAchievedConsistency(ALL, ONE, session); | |
| 75 | + checkAchievedConsistency(QUORUM, ONE, session); | |
| 76 | + checkAchievedConsistency(TWO, ONE, session); | |
| 77 | + checkAchievedConsistency(ONE, ONE, session); | |
| 78 | + | |
| 79 | + } | |
| 80 | + | |
| 81 | + private void stopAndWait(int node, Cluster cluster) { | |
| 82 | + ccm.stop(node); | |
| 83 | + ccm.waitForDown(node);// this uses port ping | |
| 84 | + TestUtils.waitForDown(ipOfNode(node), cluster, 10); // this uses UP/DOWN events | |
| 82 | 85 | } |
| 83 | 86 | |
| 84 | 87 | private void checkAchievedConsistency(ConsistencyLevel requested, ConsistencyLevel expected, Session session) { |
| 85 | 88 | RetryPolicy retryPolicy = session.getCluster().getConfiguration().getPolicies().getRetryPolicy(); |
| 86 | 89 | Mockito.reset(retryPolicy); |
| 87 | 90 | |
| 88 | - Statement s = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0") | |
| 91 | + Statement s = new SimpleStatement("SELECT * FROM foo WHERE k = 0") | |
| 89 | 92 | .setConsistencyLevel(requested); |
| 90 | 93 | |
| 91 | 94 | ResultSet rs = session.execute(s); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/RoundRobinPolicyTest.java +10 −5
| @@ -30,18 +30,20 @@ | ||
| 30 | 30 | Logger policyLogger = Logger.getLogger(RoundRobinPolicy.class); |
| 31 | 31 | MemoryAppender logs; |
| 32 | 32 | QueryTracker queryTracker; |
| 33 | + Level originalLevel; | |
| 33 | 34 | |
| 34 | 35 | @BeforeMethod(groups = "short") |
| 35 | 36 | public void setUp() { |
| 36 | 37 | queryTracker = new QueryTracker(); |
| 38 | + originalLevel = policyLogger.getLevel(); | |
| 37 | 39 | policyLogger.setLevel(Level.WARN); |
| 38 | 40 | logs = new MemoryAppender(); |
| 39 | 41 | policyLogger.addAppender(logs); |
| 40 | 42 | } |
| 41 | 43 | |
| 42 | - @AfterMethod(groups = "short") | |
| 44 | + @AfterMethod(groups = "short", alwaysRun = true) | |
| 43 | 45 | public void tearDown() { |
| 44 | - policyLogger.setLevel(null); | |
| 46 | + policyLogger.setLevel(originalLevel); | |
| 45 | 47 | policyLogger.removeAppender(logs); |
| 46 | 48 | } |
| 47 | 49 | |
| @@ -57,7 +59,8 @@ | ||
| 57 | 59 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build(); |
| 58 | 60 | |
| 59 | 61 | Cluster cluster = Cluster.builder() |
| 60 | - .addContactPoint(sCluster.address(1)) | |
| 62 | + .addContactPointsWithPorts(sCluster.address(1)) | |
| 63 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 61 | 64 | .withLoadBalancingPolicy(new RoundRobinPolicy()) |
| 62 | 65 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 63 | 66 | .build(); |
| @@ -92,7 +95,8 @@ | ||
| 92 | 95 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2, 2, 2, 2).build(); |
| 93 | 96 | |
| 94 | 97 | Cluster cluster = Cluster.builder() |
| 95 | - .addContactPoint(sCluster.address(1)) | |
| 98 | + .addContactPointsWithPorts(sCluster.address(1)) | |
| 99 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 96 | 100 | .withLoadBalancingPolicy(new RoundRobinPolicy()) |
| 97 | 101 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 98 | 102 | .build(); |
| @@ -130,7 +134,8 @@ | ||
| 130 | 134 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(1, 1).build(); |
| 131 | 135 | |
| 132 | 136 | Cluster cluster = Cluster.builder() |
| 133 | - .addContactPoint(sCluster.address(1)) | |
| 137 | + .addContactPointsWithPorts(sCluster.address(1)) | |
| 138 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 134 | 139 | .withLoadBalancingPolicy(new RoundRobinPolicy()) |
| 135 | 140 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 136 | 141 | .build(); |
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +15 −6
| @@ -69,7 +69,9 @@ | ||
| 69 | 69 | loadBalancingPolicy = new TokenAwarePolicy(new RoundRobinPolicy(), shuffleReplicas); |
| 70 | 70 | } |
| 71 | 71 | |
| 72 | - Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1)) | |
| 72 | + Cluster cluster = Cluster.builder() | |
| 73 | + .addContactPointsWithPorts(sCluster.address(1)) | |
| 74 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 73 | 75 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 74 | 76 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 75 | 77 | .build(); |
| @@ -134,7 +136,9 @@ | ||
| 134 | 136 | .withNodes(3) |
| 135 | 137 | .withSimpleKeyspace("keyspace", 1) |
| 136 | 138 | .build(); |
| 137 | - Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(1)) | |
| 139 | + Cluster cluster = Cluster.builder() | |
| 140 | + .addContactPointsWithPorts(sCluster.address(1)) | |
| 141 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 138 | 142 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 139 | 143 | .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) |
| 140 | 144 | .build(); |
| @@ -177,7 +181,9 @@ | ||
| 177 | 181 | .withNodes(3, 3) |
| 178 | 182 | .withNetworkTopologyKeyspace("keyspace", ImmutableMap.of(1, 1, 2, 1)) |
| 179 | 183 | .build(); |
| 180 | - Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2, 1)) | |
| 184 | + Cluster cluster = Cluster.builder() | |
| 185 | + .addContactPointsWithPorts(sCluster.address(1)) | |
| 186 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 181 | 187 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 182 | 188 | .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder() |
| 183 | 189 | .withLocalDc(ScassandraCluster.datacenter(2)) |
| @@ -223,7 +229,9 @@ | ||
| 223 | 229 | .withNodes(4) |
| 224 | 230 | .withSimpleKeyspace("keyspace", 2) |
| 225 | 231 | .build(); |
| 226 | - Cluster cluster = Cluster.builder().addContactPoints(sCluster.address(2)) | |
| 232 | + Cluster cluster = Cluster.builder() | |
| 233 | + .addContactPointsWithPorts(sCluster.address(2)) | |
| 234 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 227 | 235 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 228 | 236 | // Don't shuffle replicas just to keep test deterministic. |
| 229 | 237 | .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false)) |
| @@ -309,11 +317,12 @@ | ||
| 309 | 317 | @Test(groups = "long") |
| 310 | 318 | public void should_properly_generate_and_use_routing_key_for_composite_partition_key() { |
| 311 | 319 | // given: a 3 node cluster with a keyspace with RF 1. |
| 312 | - CCMBridge ccm = CCMBridge.builder("TokenAwarePolicyTest").withNodes(3).notStarted().build(); | |
| 320 | + CCMBridge ccm = CCMBridge.builder().withNodes(3).notStarted().build(); | |
| 313 | 321 | |
| 314 | 322 | Cluster cluster = Cluster.builder() |
| 315 | 323 | .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) |
| 316 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 324 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 325 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 317 | 326 | .build(); |
| 318 | 327 | |
| 319 | 328 | try { |
modified driver-core/src/test/java/com/datastax/driver/core/policies/WhiteListPolicyTest.java +5 −8
| @@ -21,7 +21,6 @@ | ||
| 21 | 21 | import org.testng.annotations.BeforeMethod; |
| 22 | 22 | import org.testng.annotations.Test; |
| 23 | 23 | |
| 24 | -import java.net.InetAddress; | |
| 25 | 24 | import java.net.InetSocketAddress; |
| 26 | 25 | import java.util.List; |
| 27 | 26 | |
| @@ -51,12 +50,11 @@ | ||
| 51 | 50 | public void should_only_query_hosts_in_white_list() throws Exception { |
| 52 | 51 | // given: a 5 node cluster with a WhiteListPolicy targeting nodes 3 and 5. |
| 53 | 52 | ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(5).build(); |
| 54 | - List<InetSocketAddress> whiteList = Lists.newArrayList( | |
| 55 | - new InetSocketAddress(InetAddress.getByName(sCluster.address(3)), 9042), | |
| 56 | - new InetSocketAddress(InetAddress.getByName(sCluster.address(5)), 9042)); | |
| 53 | + List<InetSocketAddress> whiteList = Lists.newArrayList(sCluster.address(3), sCluster.address(5)); | |
| 57 | 54 | |
| 58 | 55 | Cluster cluster = Cluster.builder() |
| 59 | - .addContactPoint(sCluster.address(5)) | |
| 56 | + .addContactPointsWithPorts(sCluster.address(5)) | |
| 57 | + .withAddressTranslater(sCluster.addressTranslator()) | |
| 60 | 58 | .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList)) |
| 61 | 59 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 62 | 60 | .build(); |
| @@ -108,10 +106,9 @@ | ||
| 108 | 106 | |
| 109 | 107 | // when: using a Cluster instance with none of the contact points in the declared |
| 110 | 108 | // WhiteListPolicy. |
| 111 | - List<InetSocketAddress> whiteList = Lists.newArrayList( | |
| 112 | - new InetSocketAddress(InetAddress.getByName(sCluster.address(2)), 9042)); | |
| 109 | + List<InetSocketAddress> whiteList = Lists.newArrayList(sCluster.address(2)); | |
| 113 | 110 | Cluster cluster = Cluster.builder() |
| 114 | - .addContactPoint(sCluster.address(3)) | |
| 111 | + .addContactPointsWithPorts(sCluster.address(3)) | |
| 115 | 112 | .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList)) |
| 116 | 113 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 117 | 114 | .build(); |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilder21ExecutionTest.java +3 −3
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.PreparedStatement; |
| 20 | 20 | import com.datastax.driver.core.ResultSet; |
| 21 | 21 | import com.datastax.driver.core.Row; |
| @@ -29,10 +29,10 @@ | ||
| 29 | 29 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 30 | 30 | |
| 31 | 31 | @CassandraVersion(major = 2.1) |
| 32 | -public class QueryBuilder21ExecutionTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 32 | +public class QueryBuilder21ExecutionTest extends CCMTestsSupport { | |
| 33 | 33 | |
| 34 | 34 | @Override |
| 35 | - protected Collection<String> getTableDefinitions() { | |
| 35 | + public Collection<String> createTestFixtures() { | |
| 36 | 36 | // Taken from http://www.datastax.com/dev/blog/cql-in-2-1 |
| 37 | 37 | return Arrays.asList( |
| 38 | 38 | "CREATE TABLE products (id int PRIMARY KEY, description text, price int, categories set<text>, buyers list<int>, features_keys map<text, text>, features_values map<text, text>)", |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +2 −2
| @@ -25,12 +25,12 @@ | ||
| 25 | 25 | import static org.assertj.core.data.MapEntry.entry; |
| 26 | 26 | import static org.testng.Assert.*; |
| 27 | 27 | |
| 28 | -public class QueryBuilderExecutionTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 28 | +public class QueryBuilderExecutionTest extends CCMTestsSupport { | |
| 29 | 29 | |
| 30 | 30 | private static final String TABLE1 = "test1"; |
| 31 | 31 | |
| 32 | 32 | @Override |
| 33 | - protected Collection<String> getTableDefinitions() { | |
| 33 | + public Collection<String> createTestFixtures() { | |
| 34 | 34 | return Arrays.asList( |
| 35 | 35 | String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, TABLE1), |
| 36 | 36 | "CREATE TABLE dateTest (t timestamp PRIMARY KEY)", |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +3 −11
| @@ -27,26 +27,18 @@ | ||
| 27 | 27 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 28 | 28 | import static org.testng.Assert.*; |
| 29 | 29 | |
| 30 | -public class QueryBuilderITest extends CCMBridge.PerClassSingleNodeCluster { | |
| 30 | +@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing") | |
| 31 | +public class QueryBuilderITest extends CCMTestsSupport { | |
| 31 | 32 | |
| 32 | 33 | private static final String TABLE_TEXT = "test_text"; |
| 33 | 34 | private static final String TABLE_INT = "test_int"; |
| 34 | 35 | |
| 35 | 36 | @Override |
| 36 | - protected Collection<String> getTableDefinitions() { | |
| 37 | + public Collection<String> createTestFixtures() { | |
| 37 | 38 | return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT), |
| 38 | 39 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 39 | 40 | } |
| 40 | 41 | |
| 41 | - @Override | |
| 42 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 43 | - return builder.withQueryOptions(new QueryOptions() | |
| 44 | - .setRefreshNodeIntervalMillis(0) | |
| 45 | - .setRefreshNodeListIntervalMillis(0) | |
| 46 | - .setRefreshSchemaIntervalMillis(0) | |
| 47 | - ); | |
| 48 | - } | |
| 49 | - | |
| 50 | 42 | @Test(groups = "short") |
| 51 | 43 | public void remainingDeleteTests() throws Exception { |
| 52 | 44 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +3 −12
| @@ -26,26 +26,18 @@ | ||
| 26 | 26 | import static org.testng.Assert.assertEquals; |
| 27 | 27 | import static org.testng.Assert.assertNotNull; |
| 28 | 28 | |
| 29 | -public class QueryBuilderRoutingKeyTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 29 | +@CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing") | |
| 30 | +public class QueryBuilderRoutingKeyTest extends CCMTestsSupport { | |
| 30 | 31 | |
| 31 | 32 | private static final String TABLE_TEXT = "test_text"; |
| 32 | 33 | private static final String TABLE_INT = "test_int"; |
| 33 | 34 | |
| 34 | 35 | @Override |
| 35 | - protected Collection<String> getTableDefinitions() { | |
| 36 | + public Collection<String> createTestFixtures() { | |
| 36 | 37 | return Arrays.asList(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT), |
| 37 | 38 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 38 | 39 | } |
| 39 | 40 | |
| 40 | - @Override | |
| 41 | - protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 42 | - return builder.withQueryOptions(new QueryOptions() | |
| 43 | - .setRefreshNodeIntervalMillis(0) | |
| 44 | - .setRefreshNodeListIntervalMillis(0) | |
| 45 | - .setRefreshSchemaIntervalMillis(0) | |
| 46 | - ); | |
| 47 | - } | |
| 48 | - | |
| 49 | 41 | @Test(groups = "short") |
| 50 | 42 | public void textRoutingKeyTest() throws Exception { |
| 51 | 43 | |
| @@ -99,7 +91,6 @@ | ||
| 99 | 91 | |
| 100 | 92 | String batch_query; |
| 101 | 93 | Statement batch; |
| 102 | - ResultSet rs; | |
| 103 | 94 | |
| 104 | 95 | query = select().from(table).where(eq("k", 42)); |
| 105 | 96 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTupleExecutionTest.java +2 −9
| @@ -15,15 +15,13 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.TupleType; |
| 20 | 20 | import com.datastax.driver.core.TupleValue; |
| 21 | 21 | import com.datastax.driver.core.utils.CassandraVersion; |
| 22 | 22 | import com.google.common.collect.ImmutableList; |
| 23 | 23 | import org.testng.annotations.Test; |
| 24 | 24 | |
| 25 | -import java.util.Collection; | |
| 26 | -import java.util.Collections; | |
| 27 | 25 | import java.util.List; |
| 28 | 26 | |
| 29 | 27 | import static com.datastax.driver.core.DataType.cint; |
| @@ -32,12 +30,7 @@ | ||
| 32 | 30 | import static org.testng.Assert.assertEquals; |
| 33 | 31 | |
| 34 | 32 | @CassandraVersion(major = 2.1, minor = 3) |
| 35 | -public class QueryBuilderTupleExecutionTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 36 | - | |
| 37 | - @Override | |
| 38 | - protected Collection<String> getTableDefinitions() { | |
| 39 | - return Collections.emptyList(); | |
| 40 | - } | |
| 33 | +public class QueryBuilderTupleExecutionTest extends CCMTestsSupport { | |
| 41 | 34 | |
| 42 | 35 | @Test(groups = "short") |
| 43 | 36 | public void should_handle_tuple() throws Exception { |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderUDTExecutionTest.java +2 −2
| @@ -32,10 +32,10 @@ | ||
| 32 | 32 | import static org.testng.Assert.assertEquals; |
| 33 | 33 | |
| 34 | 34 | @CassandraVersion(major = 2.1, minor = 3) |
| 35 | -public class QueryBuilderUDTExecutionTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 35 | +public class QueryBuilderUDTExecutionTest extends CCMTestsSupport { | |
| 36 | 36 | |
| 37 | 37 | @Override |
| 38 | - protected Collection<String> getTableDefinitions() { | |
| 38 | + public Collection<String> createTestFixtures() { | |
| 39 | 39 | return Arrays.asList("CREATE TYPE udt (i int, a inet)", |
| 40 | 40 | "CREATE TABLE udtTest(k int PRIMARY KEY, t frozen<udt>, l list<frozen<udt>>, m map<int, frozen<udt>>)"); |
| 41 | 41 | } |
modified driver-core/src/test/java/com/datastax/driver/core/schemabuilder/SchemaBuilderIT.java +5 −12
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.schemabuilder; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.DataType; |
| 20 | 20 | import com.datastax.driver.core.ResultSet; |
| 21 | 21 | import com.datastax.driver.core.Row; |
| @@ -23,20 +23,13 @@ | ||
| 23 | 23 | import com.datastax.driver.core.utils.CassandraVersion; |
| 24 | 24 | import org.testng.annotations.Test; |
| 25 | 25 | |
| 26 | -import java.util.ArrayList; | |
| 27 | -import java.util.Collection; | |
| 28 | 26 | import java.util.Iterator; |
| 29 | 27 | |
| 30 | 28 | import static com.datastax.driver.core.schemabuilder.SchemaBuilder.*; |
| 31 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 32 | 30 | import static org.assertj.core.api.Assertions.fail; |
| 33 | 31 | |
| 34 | -public class SchemaBuilderIT extends CCMBridge.PerClassSingleNodeCluster { | |
| 35 | - | |
| 36 | - @Override | |
| 37 | - protected Collection<String> getTableDefinitions() { | |
| 38 | - return new ArrayList<String>(); | |
| 39 | - } | |
| 32 | +public class SchemaBuilderIT extends CCMTestsSupport { | |
| 40 | 33 | |
| 41 | 34 | @Test(groups = "short") |
| 42 | 35 | @CassandraVersion(major = 2.1, minor = 2) |
| @@ -297,16 +290,16 @@ | ||
| 297 | 290 | ); |
| 298 | 291 | |
| 299 | 292 | // Verify that the PK index and the secondary indexes both exist |
| 300 | - assertThat(numberOfIndexedColumns("ks", "dropindex")).isEqualTo(1); | |
| 293 | + assertThat(numberOfIndexedColumns()).isEqualTo(1); | |
| 301 | 294 | |
| 302 | 295 | // Delete the index |
| 303 | 296 | session.execute(SchemaBuilder.dropIndex("ks", "ks_index")); |
| 304 | 297 | |
| 305 | 298 | // Verify that only the PK index exists |
| 306 | - assertThat(numberOfIndexedColumns("ks", "dropindex")).isEqualTo(0); | |
| 299 | + assertThat(numberOfIndexedColumns()).isEqualTo(0); | |
| 307 | 300 | } |
| 308 | 301 | |
| 309 | - private int numberOfIndexedColumns(String keyspace, String table) { | |
| 302 | + private int numberOfIndexedColumns() { | |
| 310 | 303 | ResultSet columns = session.execute( |
| 311 | 304 | "SELECT * " |
| 312 | 305 | + "FROM system.schema_columns " |
modified driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +15 −8
| @@ -27,11 +27,10 @@ | ||
| 27 | 27 | import org.slf4j.Logger; |
| 28 | 28 | import org.slf4j.LoggerFactory; |
| 29 | 29 | |
| 30 | +import java.io.Closeable; | |
| 31 | +import java.io.IOException; | |
| 30 | 32 | import java.net.InetSocketAddress; |
| 31 | -import java.util.Collection; | |
| 32 | -import java.util.Collections; | |
| 33 | -import java.util.Comparator; | |
| 34 | -import java.util.List; | |
| 33 | +import java.util.*; | |
| 35 | 34 | import java.util.concurrent.Executors; |
| 36 | 35 | import java.util.concurrent.ScheduledExecutorService; |
| 37 | 36 | import java.util.concurrent.TimeUnit; |
| @@ -41,7 +40,7 @@ | ||
| 41 | 40 | * Utility that observes {@link SocketChannel}s. Helpful for ensuring that Sockets are actually closed |
| 42 | 41 | * when they should be. Utilizes {@link NettyOptions} to monitor created {@link SocketChannel}s. |
| 43 | 42 | */ |
| 44 | -public class SocketChannelMonitor implements Runnable { | |
| 43 | +public class SocketChannelMonitor implements Runnable, Closeable { | |
| 45 | 44 | |
| 46 | 45 | private static final Logger logger = LoggerFactory.getLogger(SocketChannelMonitor.class); |
| 47 | 46 | |
| @@ -76,11 +75,17 @@ | ||
| 76 | 75 | } |
| 77 | 76 | } |
| 78 | 77 | |
| 78 | + @Override | |
| 79 | + public void close() throws IOException { | |
| 80 | + stop(); | |
| 81 | + } | |
| 82 | + | |
| 79 | 83 | public void stop() { |
| 80 | 84 | executor.shutdown(); |
| 81 | 85 | try { |
| 82 | 86 | executor.awaitTermination(1, TimeUnit.SECONDS); |
| 83 | 87 | } catch (InterruptedException e) { |
| 88 | + // ok | |
| 84 | 89 | } |
| 85 | 90 | } |
| 86 | 91 | |
| @@ -152,11 +157,14 @@ | ||
| 152 | 157 | // Should not be null as these are filtered previously in matchingChannels. |
| 153 | 158 | assert t0 != null && t0.remoteAddress() != null; |
| 154 | 159 | assert t1 != null && t1.remoteAddress() != null; |
| 155 | - ; | |
| 156 | 160 | return t0.remoteAddress().toString().compareTo(t1.remoteAddress().toString()); |
| 157 | 161 | } |
| 158 | 162 | }; |
| 159 | 163 | |
| 164 | + public Collection<SocketChannel> openChannels(InetSocketAddress... addresses) { | |
| 165 | + return openChannels(Arrays.asList(addresses)); | |
| 166 | + } | |
| 167 | + | |
| 160 | 168 | /** |
| 161 | 169 | * @param addresses The addresses to include. |
| 162 | 170 | * @return Open channels matching the given socket addresses. |
| @@ -168,9 +176,7 @@ | ||
| 168 | 176 | return input.isOpen() && input.remoteAddress() != null && addresses.contains(input.remoteAddress()); |
| 169 | 177 | } |
| 170 | 178 | })); |
| 171 | - | |
| 172 | 179 | Collections.sort(channels, BY_REMOTE_ADDRESS); |
| 173 | - | |
| 174 | 180 | return channels; |
| 175 | 181 | } |
| 176 | 182 | |
| @@ -181,4 +187,5 @@ | ||
| 181 | 187 | public Iterable<SocketChannel> matchingChannels(final Predicate<SocketChannel> channelFilter) { |
| 182 | 188 | return Iterables.filter(Lists.newArrayList(channels), Predicates.and(Predicates.notNull(), channelFilter)); |
| 183 | 189 | } |
| 190 | + | |
| 184 | 191 | } |
modified driver-core/src/test/resources/log4j.properties +26 −1
| @@ -20,10 +20,35 @@ | ||
| 20 | 20 | # Adjust Scassandra's log level |
| 21 | 21 | # (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both) |
| 22 | 22 | log4j.logger.org.scassandra=ERROR |
| 23 | +# Useful loggers when debugging Scassandra tests | |
| 24 | +#log4j.logger.org.scassandra.cql=ERROR | |
| 25 | +#log4j.logger.org.scassandra.server.cqlmessages=ERROR | |
| 26 | +#log4j.logger.org.scassandra.server.priming=ERROR | |
| 27 | +#log4j.logger.org.scassandra.server.priming.ActivityLog=ERROR | |
| 28 | +#log4j.logger.org.scassandra.server.priming.PrimingServerHttpService=ERROR | |
| 29 | +#log4j.logger.org.scassandra.server.priming.query.PrimeQueryStore=ERROR | |
| 30 | +#log4j.logger.org.scassandra.http.client=ERROR | |
| 31 | + | |
| 32 | +# These loggers can be quite verbose | |
| 33 | +log4j.logger.com.datastax.driver.core.Cluster=ERROR | |
| 34 | +log4j.logger.com.datastax.driver.core.policies.DCAwareRoundRobinPolicy=ERROR | |
| 35 | + | |
| 36 | +# Useful loggers when debugging core functionality | |
| 37 | +#log4j.logger.com.datastax.driver.core.ControlConnection=ERROR | |
| 38 | +#log4j.logger.com.datastax.driver.core.HostConnectionPool=ERROR | |
| 39 | +#log4j.logger.com.datastax.driver.core.Host.STATES=ERROR | |
| 40 | +#log4j.logger.com.datastax.driver.core.Connection=ERROR | |
| 41 | + | |
| 42 | +# Adjust log levels for CCM tests | |
| 43 | +#log4j.logger.com.datastax.driver.core.CCMTestsSupport=DEBUG | |
| 44 | +#log4j.logger.com.datastax.driver.core.CCMBridge=DEBUG | |
| 23 | 45 | |
| 24 | 46 | # A1 is set to be a ConsoleAppender. |
| 25 | 47 | log4j.appender.A1=org.apache.log4j.ConsoleAppender |
| 26 | 48 | |
| 27 | 49 | # A1 uses PatternLayout. |
| 28 | 50 | log4j.appender.A1.layout=org.apache.log4j.PatternLayout |
| 29 | -log4j.appender.A1.layout.ConversionPattern=\ %-6r [%t] %-5p %c %x - %m%n | |
| 51 | +log4j.appender.A1.layout.ConversionPattern=\ %-6r [%t] %-5p %c %x- %m%n | |
| 52 | +# less verbose layout | |
| 53 | +#log4j.appender.A1.layout.ConversionPattern=%-5p%x %m%n | |
| 54 | + |
modified driver-core/src/test/resources/reference.conf +1 −1
| @@ -2,4 +2,4 @@ | ||
| 2 | 2 | # (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both) |
| 3 | 3 | akka { |
| 4 | 4 | loglevel = "ERROR" |
| 5 | -} | |
| No newline at the end of the file | ||
| 5 | +} |
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/CCMBridgeListener.java +1 −1
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | |
| 34 | 34 | @Override |
| 35 | 35 | public void onStart(ITestContext context) { |
| 36 | - ccm = CCMBridge.builder("test").withNodes(1).build(); | |
| 36 | + ccm = CCMBridge.builder().withNodes(1).withBinaryPort(9042).build(); | |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | 39 | @Override |
modified driver-examples/osgi/src/test/java/com/datastax/driver/osgi/MailboxServiceIT.java +3 −2
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.osgi; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.TestUtils; | |
| 19 | 19 | import com.datastax.driver.osgi.api.MailboxException; |
| 20 | 20 | import com.datastax.driver.osgi.api.MailboxMessage; |
| 21 | 21 | import com.datastax.driver.osgi.api.MailboxService; |
| @@ -79,8 +79,9 @@ | ||
| 79 | 79 | @Override |
| 80 | 80 | public Option[] getOptions() { |
| 81 | 81 | return options( |
| 82 | - systemProperty("cassandra.contactpoints").value(CCMBridge.IP_PREFIX + 1), | |
| 82 | + systemProperty("cassandra.contactpoints").value(TestUtils.IP_PREFIX + 1), | |
| 83 | 83 | bundle("reference:file:target/classes"), |
| 84 | + bootDelegationPackages("javax.security.*"), | |
| 84 | 85 | mavenBundle("com.codahale.metrics", "metrics-core", "3.0.2"), |
| 85 | 86 | mavenBundle("org.slf4j", "slf4j-api", "1.7.5"), |
| 86 | 87 | mavenBundle("org.slf4j", "slf4j-simple", "1.7.5").noStart(), |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorParamsTest.java +4 −4
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.ResultSet; |
| 20 | 20 | import com.datastax.driver.core.Row; |
| 21 | 21 | import com.datastax.driver.core.utils.CassandraVersion; |
| @@ -27,9 +27,9 @@ | ||
| 27 | 27 | |
| 28 | 28 | import static org.assertj.core.api.Assertions.assertThat; |
| 29 | 29 | |
| 30 | -public class MapperAccessorParamsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 30 | +public class MapperAccessorParamsTest extends CCMTestsSupport { | |
| 31 | 31 | @Override |
| 32 | - protected Collection<String> getTableDefinitions() { | |
| 32 | + public Collection<String> createTestFixtures() { | |
| 33 | 33 | return Lists.newArrayList( |
| 34 | 34 | "CREATE TABLE user ( key int primary key, gender int, home_phone text, work_phone text)", |
| 35 | 35 | "CREATE INDEX on user(gender)", |
| @@ -246,4 +246,4 @@ | ||
| 246 | 246 | this.gender = val; |
| 247 | 247 | } |
| 248 | 248 | } |
| 249 | -} | |
| No newline at the end of the file | ||
| 249 | +} |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAccessorTest.java +4 −3
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.ResultSet; |
| 20 | 20 | import com.datastax.driver.core.Row; |
| 21 | 21 | import com.datastax.driver.core.utils.CassandraVersion; |
| @@ -29,10 +29,10 @@ | ||
| 29 | 29 | |
| 30 | 30 | import static org.assertj.core.api.Assertions.assertThat; |
| 31 | 31 | |
| 32 | -public class MapperAccessorTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 32 | +public class MapperAccessorTest extends CCMTestsSupport { | |
| 33 | 33 | |
| 34 | 34 | @Override |
| 35 | - protected Collection<String> getTableDefinitions() { | |
| 35 | + public Collection<String> createTestFixtures() { | |
| 36 | 36 | return Lists.newArrayList("CREATE TABLE foo (k int primary key, v text)"); |
| 37 | 37 | } |
| 38 | 38 | |
| @@ -87,6 +87,7 @@ | ||
| 87 | 87 | assertThat(row.getString("v")).isEqualTo("bar"); |
| 88 | 88 | } |
| 89 | 89 | |
| 90 | + @SuppressWarnings("unused") | |
| 90 | 91 | @Accessor |
| 91 | 92 | public interface SystemAccessor { |
| 92 | 93 | @Query("select release_version from system.local") |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperCompositeKeyTest.java +8 −6
| @@ -15,24 +15,26 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.mapping.annotations.ClusteringColumn; |
| 20 | 20 | import com.datastax.driver.mapping.annotations.PartitionKey; |
| 21 | 21 | import com.datastax.driver.mapping.annotations.Table; |
| 22 | 22 | import org.testng.annotations.Test; |
| 23 | 23 | |
| 24 | -import java.util.Arrays; | |
| 25 | 24 | import java.util.Collection; |
| 25 | +import java.util.Collections; | |
| 26 | 26 | |
| 27 | 27 | /** |
| 28 | 28 | * Tests for the mapper with composite partition keys and multiple clustering columns. |
| 29 | 29 | */ |
| 30 | -public class MapperCompositeKeyTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 31 | - | |
| 32 | - protected Collection<String> getTableDefinitions() { | |
| 33 | - return Arrays.asList("CREATE TABLE test_table (pk1 int, pk2 int, cc1 int, cc2 int, PRIMARY KEY ((pk1, pk2), cc1, cc2))"); | |
| 30 | +public class MapperCompositeKeyTest extends CCMTestsSupport { | |
| 31 | + | |
| 32 | + @Override | |
| 33 | + public Collection<String> createTestFixtures() { | |
| 34 | + return Collections.singletonList("CREATE TABLE test_table (pk1 int, pk2 int, cc1 int, cc2 int, PRIMARY KEY ((pk1, pk2), cc1, cc2))"); | |
| 34 | 35 | } |
| 35 | 36 | |
| 37 | + @SuppressWarnings("unused") | |
| 36 | 38 | @Table(keyspace = "ks", name = "test_table") |
| 37 | 39 | public static class TestTable { |
| 38 | 40 | @PartitionKey(0) |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperComputedFieldsTest.java +2 −2
| @@ -35,10 +35,10 @@ | ||
| 35 | 35 | * annotation to map computed fields. |
| 36 | 36 | */ |
| 37 | 37 | @SuppressWarnings("unused") |
| 38 | -public class MapperComputedFieldsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 38 | +public class MapperComputedFieldsTest extends CCMTestsSupport { | |
| 39 | 39 | |
| 40 | 40 | @Override |
| 41 | - protected Collection<String> getTableDefinitions() { | |
| 41 | + public Collection<String> createTestFixtures() { | |
| 42 | 42 | return Lists.newArrayList( |
| 43 | 43 | "CREATE TABLE user (login text primary key, name text)", |
| 44 | 44 | "INSERT INTO user (login, name) VALUES ('testlogin', 'test name')"); |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperDefaultKeyspaceTest.java +9 −6
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.Session; |
| 20 | 20 | import com.datastax.driver.core.utils.CassandraVersion; |
| 21 | 21 | import com.datastax.driver.core.utils.UUIDs; |
| @@ -34,12 +34,15 @@ | ||
| 34 | 34 | * Tests usage of mapping annotations without specifying a keyspace. |
| 35 | 35 | */ |
| 36 | 36 | @CassandraVersion(major = 2.1) |
| 37 | -public class MapperDefaultKeyspaceTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 37 | +@SuppressWarnings("unused") | |
| 38 | +public class MapperDefaultKeyspaceTest extends CCMTestsSupport { | |
| 38 | 39 | |
| 39 | 40 | private static final String KEYSPACE = "mapper_default_keyspace_test_ks"; |
| 40 | 41 | |
| 41 | - protected Collection<String> getTableDefinitions() { | |
| 42 | - return Arrays.asList("CREATE TABLE groups (group_id uuid PRIMARY KEY, name text)", | |
| 42 | + @Override | |
| 43 | + public Collection<String> createTestFixtures() { | |
| 44 | + return Arrays.asList( | |
| 45 | + "CREATE TABLE groups (group_id uuid PRIMARY KEY, name text)", | |
| 43 | 46 | "CREATE TYPE IF NOT EXISTS group_name (name text)"); |
| 44 | 47 | } |
| 45 | 48 | |
| @@ -157,7 +160,7 @@ | ||
| 157 | 160 | if (other == null || other.getClass() != this.getClass()) |
| 158 | 161 | return false; |
| 159 | 162 | |
| 160 | - Group that = (Group) other; | |
| 163 | + Group2 that = (Group2) other; | |
| 161 | 164 | return Objects.equal(groupId, that.groupId) |
| 162 | 165 | && Objects.equal(name, that.name); |
| 163 | 166 | } |
| @@ -195,7 +198,7 @@ | ||
| 195 | 198 | public boolean equals(Object other) { |
| 196 | 199 | if (other instanceof GroupName) { |
| 197 | 200 | GroupName that = (GroupName) other; |
| 198 | - return this.name == that.name; | |
| 201 | + return this.name.equals(that.name); | |
| 199 | 202 | } |
| 200 | 203 | return false; |
| 201 | 204 | } |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperEnumTest.java +4 −3
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.mapping.annotations.Enumerated; |
| 20 | 20 | import com.datastax.driver.mapping.annotations.PartitionKey; |
| 21 | 21 | import com.datastax.driver.mapping.annotations.Table; |
| @@ -29,10 +29,11 @@ | ||
| 29 | 29 | /** |
| 30 | 30 | * Covers handling of enum fields by the mapper. |
| 31 | 31 | */ |
| 32 | -public class MapperEnumTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 32 | +@SuppressWarnings("unused") | |
| 33 | +public class MapperEnumTest extends CCMTestsSupport { | |
| 33 | 34 | |
| 34 | 35 | @Override |
| 35 | - protected Collection<String> getTableDefinitions() { | |
| 36 | + public Collection<String> createTestFixtures() { | |
| 36 | 37 | return Lists.newArrayList("CREATE TABLE asOrdinal (k int primary key, v int)", |
| 37 | 38 | "CREATE TABLE asString (k int primary key, v text)"); |
| 38 | 39 | } |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperInvalidCollectionTypesTest.java +6 −3
| @@ -15,15 +15,18 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.mapping.annotations.PartitionKey; |
| 20 | 20 | import com.datastax.driver.mapping.annotations.Table; |
| 21 | 21 | import org.testng.annotations.Test; |
| 22 | 22 | |
| 23 | 23 | import java.util.*; |
| 24 | 24 | |
| 25 | -public class MapperInvalidCollectionTypesTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 26 | - protected Collection<String> getTableDefinitions() { | |
| 25 | +@SuppressWarnings("unused") | |
| 26 | +public class MapperInvalidCollectionTypesTest extends CCMTestsSupport { | |
| 27 | + | |
| 28 | + @Override | |
| 29 | + public Collection<String> createTestFixtures() { | |
| 27 | 30 | return Arrays.asList( |
| 28 | 31 | "CREATE TABLE table_list (id int PRIMARY KEY, l list<int>)", |
| 29 | 32 | "CREATE TABLE table_set (id int PRIMARY KEY, s set<int>)", |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperNestedCollectionsTest.java +6 −9
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.ResultSet; |
| 20 | 20 | import com.datastax.driver.core.utils.CassandraVersion; |
| 21 | 21 | import com.datastax.driver.mapping.annotations.*; |
| @@ -29,10 +29,11 @@ | ||
| 29 | 29 | import static com.datastax.driver.core.Assertions.assertThat; |
| 30 | 30 | |
| 31 | 31 | @CassandraVersion(major = 2.1, minor = 3) |
| 32 | -public class MapperNestedCollectionsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 32 | +@SuppressWarnings("unused") | |
| 33 | +public class MapperNestedCollectionsTest extends CCMTestsSupport { | |
| 33 | 34 | |
| 34 | 35 | @Override |
| 35 | - protected Collection<String> getTableDefinitions() { | |
| 36 | + public Collection<String> createTestFixtures() { | |
| 36 | 37 | return Lists.newArrayList( |
| 37 | 38 | "CREATE TYPE testType(i int, ls list<frozen<set<int>>>)", |
| 38 | 39 | "CREATE TABLE testTable (k int primary key, " |
| @@ -130,12 +131,8 @@ | ||
| 130 | 131 | |
| 131 | 132 | TestType testType = (TestType) o; |
| 132 | 133 | |
| 133 | - if (i != testType.i) | |
| 134 | - return false; | |
| 135 | - if (!ls.equals(testType.ls)) | |
| 136 | - return false; | |
| 134 | + return i == testType.i && ls.equals(testType.ls); | |
| 137 | 135 | |
| 138 | - return true; | |
| 139 | 136 | } |
| 140 | 137 | |
| 141 | 138 | @Override |
| @@ -183,7 +180,7 @@ | ||
| 183 | 180 | } |
| 184 | 181 | |
| 185 | 182 | @Accessor |
| 186 | - public static interface TestAccessor { | |
| 183 | + public interface TestAccessor { | |
| 187 | 184 | @Query("UPDATE testTable SET m1 = :m1 WHERE k = :k") |
| 188 | 185 | ResultSet setM1(@Param("k") int k, @Param("m1") Map<String, Map<Integer, Integer>> m1); |
| 189 | 186 |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperOptionTest.java +3 −2
| @@ -35,13 +35,14 @@ | ||
| 35 | 35 | import static org.assertj.core.api.Assertions.assertThat; |
| 36 | 36 | import static org.assertj.core.api.Assertions.fail; |
| 37 | 37 | |
| 38 | -public class MapperOptionTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 38 | +@SuppressWarnings("unused") | |
| 39 | +public class MapperOptionTest extends CCMTestsSupport { | |
| 39 | 40 | |
| 40 | 41 | ProtocolVersion protocolVersion; |
| 41 | 42 | Mapper<User> mapper; |
| 42 | 43 | |
| 43 | 44 | @Override |
| 44 | - protected Collection<String> getTableDefinitions() { | |
| 45 | + public Collection<String> createTestFixtures() { | |
| 45 | 46 | return Lists.newArrayList("CREATE TABLE user (key int primary key, v text)"); |
| 46 | 47 | } |
| 47 | 48 |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperPrimitiveTypesTest.java +5 −5
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.utils.Bytes; |
| 20 | 20 | import com.datastax.driver.core.utils.UUIDs; |
| 21 | 21 | import com.datastax.driver.mapping.annotations.PartitionKey; |
| @@ -26,8 +26,8 @@ | ||
| 26 | 26 | import java.math.BigInteger; |
| 27 | 27 | import java.net.InetAddress; |
| 28 | 28 | import java.nio.ByteBuffer; |
| 29 | -import java.util.Arrays; | |
| 30 | 29 | import java.util.Collection; |
| 30 | +import java.util.Collections; | |
| 31 | 31 | import java.util.Date; |
| 32 | 32 | import java.util.UUID; |
| 33 | 33 | |
| @@ -36,10 +36,10 @@ | ||
| 36 | 36 | /** |
| 37 | 37 | * Tests the mapping of all primitive types as Java fields. |
| 38 | 38 | */ |
| 39 | -public class MapperPrimitiveTypesTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 39 | +public class MapperPrimitiveTypesTest extends CCMTestsSupport { | |
| 40 | 40 | |
| 41 | - protected Collection<String> getTableDefinitions() { | |
| 42 | - return Arrays.asList("CREATE TABLE primitiveTypes (" | |
| 41 | + public Collection<String> createTestFixtures() { | |
| 42 | + return Collections.singletonList("CREATE TABLE primitiveTypes (" | |
| 43 | 43 | + "byteBufferCol blob primary key," |
| 44 | 44 | + "intCol int, intWrapperCol int," |
| 45 | 45 | + "longCol bigint, longWrapperCol bigint," |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperSaveNullFieldsTest.java +4 −3
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.BoundStatement; |
| 19 | -import com.datastax.driver.core.CCMBridge; | |
| 19 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 20 | 20 | import com.datastax.driver.mapping.Mapper.Option; |
| 21 | 21 | import com.datastax.driver.mapping.annotations.PartitionKey; |
| 22 | 22 | import com.datastax.driver.mapping.annotations.Table; |
| @@ -28,12 +28,13 @@ | ||
| 28 | 28 | |
| 29 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 30 | 30 | |
| 31 | -public class MapperSaveNullFieldsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 31 | +@SuppressWarnings("unused") | |
| 32 | +public class MapperSaveNullFieldsTest extends CCMTestsSupport { | |
| 32 | 33 | |
| 33 | 34 | Mapper<User> mapper; |
| 34 | 35 | |
| 35 | 36 | @Override |
| 36 | - protected Collection<String> getTableDefinitions() { | |
| 37 | + public Collection<String> createTestFixtures() { | |
| 37 | 38 | return Lists.newArrayList("CREATE TABLE user (login text primary key, name text, phone text)"); |
| 38 | 39 | } |
| 39 | 40 |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +10 −8
| @@ -33,9 +33,11 @@ | ||
| 33 | 33 | /** |
| 34 | 34 | * Basic tests for the mapping module. |
| 35 | 35 | */ |
| 36 | -public class MapperTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 37 | - | |
| 38 | - protected Collection<String> getTableDefinitions() { | |
| 36 | +@SuppressWarnings("unused") | |
| 37 | +public class MapperTest extends CCMTestsSupport { | |
| 38 | + | |
| 39 | + @Override | |
| 40 | + public Collection<String> createTestFixtures() { | |
| 39 | 41 | // We'll allow to generate those create statement from the annotated entities later, but it's currently |
| 40 | 42 | // a TODO |
| 41 | 43 | return Arrays.asList("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)", |
| @@ -267,24 +269,24 @@ | ||
| 267 | 269 | // harcoded arg0, arg1, .... A big annoying, and apparently Java 8 will fix that |
| 268 | 270 | // somehow, but well, not a huge deal. |
| 269 | 271 | @Query("SELECT * FROM posts WHERE user_id=:userId AND post_id=:postId") |
| 270 | - public Post getOne(@Param("userId") UUID userId, | |
| 271 | - @Param("postId") UUID postId); | |
| 272 | + Post getOne(@Param("userId") UUID userId, | |
| 273 | + @Param("postId") UUID postId); | |
| 272 | 274 | |
| 273 | 275 | // Note that the following method will be asynchronous (it will use executeAsync |
| 274 | 276 | // underneath) because it's return type is a ListenableFuture. Similarly, we know |
| 275 | 277 | // that we need to map the result to the Post entity thanks to the return type. |
| 276 | 278 | @Query("SELECT * FROM posts WHERE user_id=?") |
| 277 | 279 | @QueryParameters(consistency = "QUORUM") |
| 278 | - public ListenableFuture<Result<Post>> getAllAsync(UUID userId); | |
| 280 | + ListenableFuture<Result<Post>> getAllAsync(UUID userId); | |
| 279 | 281 | |
| 280 | 282 | // The method above actually query stuff, but if a method is declared to return |
| 281 | 283 | // a Statement, it will not execute anything, but just return you the BoundStatement |
| 282 | 284 | // ready for execution. That way, you can batch stuff for instance (see usage below). |
| 283 | 285 | @Query("UPDATE posts SET content=? WHERE user_id=? AND post_id=?") |
| 284 | - public Statement updateContentQuery(String newContent, UUID userId, UUID postId); | |
| 286 | + Statement updateContentQuery(String newContent, UUID userId, UUID postId); | |
| 285 | 287 | |
| 286 | 288 | @Query("SELECT * FROM posts") |
| 287 | - public Result<Post> getAll(); | |
| 289 | + Result<Post> getAll(); | |
| 288 | 290 | } |
| 289 | 291 | |
| 290 | 292 | @Accessor |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTCollectionsTest.java +6 −4
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.mapping.annotations.*; |
| 20 | 20 | import com.google.common.base.Objects; |
| 21 | 21 | import com.google.common.collect.ImmutableMap; |
| @@ -30,9 +30,11 @@ | ||
| 30 | 30 | /** |
| 31 | 31 | * Tests mapping of collections of UDTs. |
| 32 | 32 | */ |
| 33 | -public class MapperUDTCollectionsTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 34 | - | |
| 35 | - protected Collection<String> getTableDefinitions() { | |
| 33 | +@SuppressWarnings("unused") | |
| 34 | +public class MapperUDTCollectionsTest extends CCMTestsSupport { | |
| 35 | + | |
| 36 | + @Override | |
| 37 | + public Collection<String> createTestFixtures() { | |
| 36 | 38 | return Arrays.asList("CREATE TYPE sub(i int)", |
| 37 | 39 | "CREATE TABLE collection_examples (id int PRIMARY KEY, l list<frozen<sub>>, s set<frozen<sub>>, m1 map<int,frozen<sub>>, m2 map<frozen<sub>,int>, m3 map<frozen<sub>,frozen<sub>>)"); |
| 38 | 40 | } |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +7 −7
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.core.ResultSet; |
| 20 | 20 | import com.datastax.driver.core.utils.UUIDs; |
| 21 | 21 | import com.datastax.driver.mapping.annotations.*; |
| @@ -29,9 +29,11 @@ | ||
| 29 | 29 | import static org.assertj.core.api.Assertions.assertThat; |
| 30 | 30 | import static org.testng.Assert.*; |
| 31 | 31 | |
| 32 | -public class MapperUDTTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 32 | +@SuppressWarnings("unused") | |
| 33 | +public class MapperUDTTest extends CCMTestsSupport { | |
| 33 | 34 | |
| 34 | - protected Collection<String> getTableDefinitions() { | |
| 35 | + @Override | |
| 36 | + public Collection<String> createTestFixtures() { | |
| 35 | 37 | return Arrays.asList("CREATE TYPE address (street text, city text, zip_code int, phones set<text>)", |
| 36 | 38 | "CREATE TABLE users (user_id uuid PRIMARY KEY, name text, mainaddress frozen<address>, other_addresses map<text,frozen<address>>)"); |
| 37 | 39 | } |
| @@ -141,9 +143,7 @@ | ||
| 141 | 143 | this.city = city; |
| 142 | 144 | this.zipCode = zipCode; |
| 143 | 145 | this.phones = new HashSet<String>(); |
| 144 | - for (String phone : phones) { | |
| 145 | - this.phones.add(phone); | |
| 146 | - } | |
| 146 | + Collections.addAll(this.phones, phones); | |
| 147 | 147 | } |
| 148 | 148 | |
| 149 | 149 | public String getStreet() { |
| @@ -203,7 +203,7 @@ | ||
| 203 | 203 | ResultSet setOtherAddresses(@Param("id") UUID id, @Param("addresses") Map<String, Address> addresses); |
| 204 | 204 | |
| 205 | 205 | @Query("SELECT * FROM users") |
| 206 | - public Result<User> getAll(); | |
| 206 | + Result<User> getAll(); | |
| 207 | 207 | } |
| 208 | 208 | |
| 209 | 209 | @Test(groups = "short") |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/SyntheticFieldsMapperTest.java +8 −7
| @@ -15,7 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CCMBridge; | |
| 18 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 19 | 19 | import com.datastax.driver.mapping.annotations.PartitionKey; |
| 20 | 20 | import com.datastax.driver.mapping.annotations.Table; |
| 21 | 21 | import com.google.common.io.Closeables; |
| @@ -25,15 +25,17 @@ | ||
| 25 | 25 | import java.io.IOException; |
| 26 | 26 | import java.io.InputStream; |
| 27 | 27 | import java.lang.reflect.Constructor; |
| 28 | -import java.util.Arrays; | |
| 29 | 28 | import java.util.Collection; |
| 29 | +import java.util.Collections; | |
| 30 | 30 | |
| 31 | 31 | import static org.testng.Assert.assertEquals; |
| 32 | 32 | |
| 33 | -public class SyntheticFieldsMapperTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 33 | +@SuppressWarnings("unused") | |
| 34 | +public class SyntheticFieldsMapperTest extends CCMTestsSupport { | |
| 34 | 35 | |
| 35 | - protected Collection<String> getTableDefinitions() { | |
| 36 | - return Arrays.asList("CREATE TABLE synthetic_fields (id int PRIMARY KEY)"); | |
| 36 | + @Override | |
| 37 | + public Collection<String> createTestFixtures() { | |
| 38 | + return Collections.singletonList("CREATE TABLE synthetic_fields (id int PRIMARY KEY)"); | |
| 37 | 39 | } |
| 38 | 40 | |
| 39 | 41 | /** |
| @@ -141,9 +143,8 @@ | ||
| 141 | 143 | |
| 142 | 144 | ClassWithSyntheticField that = (ClassWithSyntheticField) o; |
| 143 | 145 | |
| 144 | - if (id != that.id) return false; | |
| 146 | + return id == that.id; | |
| 145 | 147 | |
| 146 | - return true; | |
| 147 | 148 | } |
| 148 | 149 | |
| 149 | 150 | @Override |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/UDTFieldMapperTest.java +19 −6
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | import java.util.Map; |
| 28 | 28 | |
| 29 | 29 | @CassandraVersion(major = 2.1) |
| 30 | +@SuppressWarnings("unused") | |
| 30 | 31 | public class UDTFieldMapperTest { |
| 31 | 32 | |
| 32 | 33 | @Test(groups = "short") |
| @@ -36,8 +37,11 @@ | ||
| 36 | 37 | |
| 37 | 38 | try { |
| 38 | 39 | // Create type and table |
| 39 | - ccm = CCMBridge.builder("test").build(); | |
| 40 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 40 | + ccm = CCMBridge.builder().build(); | |
| 41 | + cluster = Cluster.builder() | |
| 42 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 43 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 44 | + .build(); | |
| 41 | 45 | Session session1 = cluster.connect(); |
| 42 | 46 | session1.execute("create schema if not exists java_509 " + |
| 43 | 47 | "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };"); |
| @@ -50,7 +54,10 @@ | ||
| 50 | 54 | cluster.close(); |
| 51 | 55 | |
| 52 | 56 | // Create entities with another connection |
| 53 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 57 | + cluster = Cluster.builder() | |
| 58 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 59 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 60 | + .build(); | |
| 54 | 61 | Session session2 = cluster.newSession(); |
| 55 | 62 | Mapper<MyHashWithKeyspace> hashMapper = new MappingManager(session2).mapper(MyHashWithKeyspace.class); |
| 56 | 63 | hashMapper.save(new MyHashWithKeyspace( |
| @@ -83,8 +90,11 @@ | ||
| 83 | 90 | |
| 84 | 91 | try { |
| 85 | 92 | // Create type and table |
| 86 | - ccm = CCMBridge.builder("test").build(); | |
| 87 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 93 | + ccm = CCMBridge.builder().build(); | |
| 94 | + cluster = Cluster.builder() | |
| 95 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 96 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 97 | + .build(); | |
| 88 | 98 | Session session1 = cluster.connect(); |
| 89 | 99 | session1.execute("create schema if not exists java_509 " + |
| 90 | 100 | "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };"); |
| @@ -98,7 +108,10 @@ | ||
| 98 | 108 | cluster.close(); |
| 99 | 109 | |
| 100 | 110 | // Create entities with another connection |
| 101 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 111 | + cluster = Cluster.builder() | |
| 112 | + .addContactPointsWithPorts(ccm.addressOfNode(1)) | |
| 113 | + .withAddressTranslater(ccm.addressTranslator()) | |
| 114 | + .build(); | |
| 102 | 115 | Session session2 = cluster.newSession(); |
| 103 | 116 | |
| 104 | 117 | session2.execute("use java_509"); |