kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 3901b60c6dfc37d1a30839dcff7e74a77cfc36e2dee845fc766072bb1abea662 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-06-26 23:49 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-06-26 23:50 +02:00 |
| Parents | 8a16bdb3a49c, a7f003430035 |
21 files changed
modified changelog/README.md +2 −0
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | - [improvement] Do not include epoll JAR in binary distribution (JAVA-766) |
| 33 | 33 | - [improvement] Optimize internal copies of Request objects (JAVA-726) |
| 34 | 34 | - [bug] Preserve tracing across retries (JAVA-815) |
| 35 | +- [improvement] New RetryDecision.tryNextHost() (JAVA-709) | |
| 35 | 36 | |
| 36 | 37 | |
| 37 | 38 | ### 2.1.6 |
| @@ -266,6 +267,7 @@ | ||
| 266 | 267 | - [improvement] Do not include epoll JAR in binary distribution (JAVA-766) |
| 267 | 268 | - [improvement] Optimize internal copies of Request objects (JAVA-726) |
| 268 | 269 | - [bug] Preserve tracing across retries (JAVA-815) |
| 270 | +- [improvement] New RetryDecision.tryNextHost() (JAVA-709) | |
| 269 | 271 | |
| 270 | 272 | Merged from 2.0.10_fixes branch: |
| 271 | 273 |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +1 −1
| @@ -579,7 +579,7 @@ | ||
| 579 | 579 | logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel()); |
| 580 | 580 | if (metricsEnabled()) |
| 581 | 581 | metrics().getErrorMetrics().getRetries().inc(); |
| 582 | - retry(true, retry.getRetryConsistencyLevel()); | |
| 582 | + retry(retry.isRetryCurrent(), retry.getRetryConsistencyLevel()); | |
| 583 | 583 | break; |
| 584 | 584 | case RETHROW: |
| 585 | 585 | setFinalResult(connection, response); |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +16 −8
| @@ -24,7 +24,7 @@ | ||
| 24 | 24 | * <p> |
| 25 | 25 | * This policy retries queries in only two cases: |
| 26 | 26 | * <ul> |
| 27 | - * <li>On a read timeout, if enough replica replied but data was not retrieved.</li> | |
| 27 | + * <li>On a read timeout, if enough replicas replied but data was not retrieved.</li> | |
| 28 | 28 | * <li>On a write timeout, if we timeout while writing the distributed log used by batch statements.</li> |
| 29 | 29 | * </ul> |
| 30 | 30 | * <p> |
| @@ -44,13 +44,13 @@ | ||
| 44 | 44 | * Defines whether to retry and at which consistency level on a read timeout. |
| 45 | 45 | * <p> |
| 46 | 46 | * This method triggers a maximum of one retry, and only if enough |
| 47 | - * replica had responded to the read request but data was not retrieved | |
| 47 | + * replicas had responded to the read request but data was not retrieved | |
| 48 | 48 | * amongst those. Indeed, that case usually means that enough replica |
| 49 | 49 | * are alive to satisfy the consistency but the coordinator picked a |
| 50 | 50 | * dead one for data retrieval, not having detected that replica as dead |
| 51 | 51 | * yet. The reasoning for retrying then is that by the time we get the |
| 52 | 52 | * timeout the dead replica will likely have been detected as dead and |
| 53 | - * the retry has a high change of success. | |
| 53 | + * the retry has a high chance of success. | |
| 54 | 54 | * |
| 55 | 55 | * @param statement the original query that timed out. |
| 56 | 56 | * @param cl the original consistency level of the read that timed out. |
| @@ -60,7 +60,7 @@ | ||
| 60 | 60 | * by the time the timeout exception was raised. |
| 61 | 61 | * @param dataRetrieved whether actual data (by opposition to data checksum) |
| 62 | 62 | * was present in the received responses. |
| 63 | - * @param nbRetry the number of retry already performed for this operation. | |
| 63 | + * @param nbRetry the number of retries already performed for this operation. | |
| 64 | 64 | * @return {@code RetryDecision.retry(cl)} if no retry attempt has yet been tried and |
| 65 | 65 | * {@code receivedResponses >= requiredResponses && !dataRetrieved}, {@code RetryDecision.rethrow()} otherwise. |
| 66 | 66 | */ |
| @@ -78,7 +78,7 @@ | ||
| 78 | 78 | * This method triggers a maximum of one retry, and only in the case of |
| 79 | 79 | * a {@code WriteType.BATCH_LOG} write. The reasoning for the retry in |
| 80 | 80 | * that case is that write to the distributed batch log is tried by the |
| 81 | - * coordinator of the write against a small subset of all the node alive | |
| 81 | + * coordinator of the write against a small subset of all the nodes alive | |
| 82 | 82 | * in the local datacenter. Hence, a timeout usually means that none of |
| 83 | 83 | * the nodes in that subset were alive but the coordinator hasn't |
| 84 | 84 | * detected them as dead. By the time we get the timeout the dead |
| @@ -109,8 +109,14 @@ | ||
| 109 | 109 | * Defines whether to retry and at which consistency level on an |
| 110 | 110 | * unavailable exception. |
| 111 | 111 | * <p> |
| 112 | - * This method never retries as a retry on an unavailable exception | |
| 113 | - * using the same consistency level has almost no change of success. | |
| 112 | + * This method triggers a retry iff no retry has been executed before | |
| 113 | + * (nbRetry == 0), with {@link RetryDecision#tryNextHost}, otherwise it | |
| 114 | + * throws an exception. The retry will be processed on the next host | |
| 115 | + * in the query plan according to the current Load Balancing Policy. | |
| 116 | + * Where retrying on the same host in the event of an Unavailable exception | |
| 117 | + * has almost no chance of success, if the first replica tried happens to | |
| 118 | + * be "network" isolated from all the other nodes but can still answer to | |
| 119 | + * the client, it makes sense to retry the query on another node. | |
| 114 | 120 | * |
| 115 | 121 | * @param statement the original query for which the consistency level cannot |
| 116 | 122 | * be achieved. |
| @@ -124,6 +130,8 @@ | ||
| 124 | 130 | */ |
| 125 | 131 | @Override |
| 126 | 132 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { |
| 127 | - return RetryDecision.rethrow(); | |
| 133 | + return (nbRetry == 0) | |
| 134 | + ? RetryDecision.tryNextHost(cl) | |
| 135 | + : RetryDecision.rethrow(); | |
| 128 | 136 | } |
| 129 | 137 | } |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +2 −2
| @@ -75,9 +75,9 @@ | ||
| 75 | 75 | private RetryDecision maxLikelyToWorkCL(int knownOk) { |
| 76 | 76 | if (knownOk >= 3) |
| 77 | 77 | return RetryDecision.retry(ConsistencyLevel.THREE); |
| 78 | - else if (knownOk >= 2) | |
| 78 | + else if (knownOk == 2) | |
| 79 | 79 | return RetryDecision.retry(ConsistencyLevel.TWO); |
| 80 | - else if (knownOk >= 1) | |
| 80 | + else if (knownOk == 1) | |
| 81 | 81 | return RetryDecision.retry(ConsistencyLevel.ONE); |
| 82 | 82 | else |
| 83 | 83 | return RetryDecision.rethrow(); |
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +30 −9
| @@ -42,18 +42,20 @@ | ||
| 42 | 42 | * exception will return an empty result set.</li> |
| 43 | 43 | * </ul> |
| 44 | 44 | */ |
| 45 | - public static class RetryDecision { | |
| 45 | + class RetryDecision { | |
| 46 | 46 | /** |
| 47 | 47 | * The type of retry decisions. |
| 48 | 48 | */ |
| 49 | - public static enum Type { RETRY, RETHROW, IGNORE }; | |
| 49 | + public enum Type { RETRY, RETHROW, IGNORE }; | |
| 50 | 50 | |
| 51 | 51 | private final Type type; |
| 52 | 52 | private final ConsistencyLevel retryCL; |
| 53 | + private final boolean retryCurrent; | |
| 53 | 54 | |
| 54 | - private RetryDecision(Type type, ConsistencyLevel retryCL) { | |
| 55 | + private RetryDecision(Type type, ConsistencyLevel retryCL, boolean retryCurrent){ | |
| 55 | 56 | this.type = type; |
| 56 | 57 | this.retryCL = retryCL; |
| 58 | + this.retryCurrent = retryCurrent; | |
| 57 | 59 | } |
| 58 | 60 | |
| 59 | 61 | /** |
| @@ -75,13 +77,22 @@ | ||
| 75 | 77 | return retryCL; |
| 76 | 78 | } |
| 77 | 79 | |
| 80 | + /** | |
| 81 | + * Whether the retry policy uses the same host for retry decision. | |
| 82 | + * | |
| 83 | + * @return the retry on next host boolean. Default is false. | |
| 84 | + */ | |
| 85 | + public boolean isRetryCurrent() { | |
| 86 | + return retryCurrent; | |
| 87 | + } | |
| 88 | + | |
| 78 | 89 | /** |
| 79 | 90 | * Creates a RETHROW retry decision. |
| 80 | 91 | * |
| 81 | 92 | * @return a RETHROW retry decision. |
| 82 | 93 | */ |
| 83 | 94 | public static RetryDecision rethrow() { |
| 84 | - return new RetryDecision(Type.RETHROW, null); | |
| 95 | + return new RetryDecision(Type.RETHROW, null, true); | |
| 85 | 96 | } |
| 86 | 97 | |
| 87 | 98 | /** |
| @@ -91,7 +102,7 @@ | ||
| 91 | 102 | * @return a RETRY with consistency level {@code consistency} retry decision. |
| 92 | 103 | */ |
| 93 | 104 | public static RetryDecision retry(ConsistencyLevel consistency) { |
| 94 | - return new RetryDecision(Type.RETRY, consistency); | |
| 105 | + return new RetryDecision(Type.RETRY, consistency, true); | |
| 95 | 106 | } |
| 96 | 107 | |
| 97 | 108 | /** |
| @@ -100,15 +111,25 @@ | ||
| 100 | 111 | * @return an IGNORE retry decision. |
| 101 | 112 | */ |
| 102 | 113 | public static RetryDecision ignore() { |
| 103 | - return new RetryDecision(Type.IGNORE, null); | |
| 114 | + return new RetryDecision(Type.IGNORE, null, true); | |
| 115 | + } | |
| 116 | + | |
| 117 | + /** | |
| 118 | + * Creates a RETRY retry decision and indicates to retry on another host | |
| 119 | + * using the provided consistency level. | |
| 120 | + * | |
| 121 | + * @return a RETRY retry decision. | |
| 122 | + */ | |
| 123 | + public static RetryDecision tryNextHost(ConsistencyLevel retryCL) { | |
| 124 | + return new RetryDecision(Type.RETRY, retryCL, false); | |
| 104 | 125 | } |
| 105 | 126 | |
| 106 | 127 | @Override |
| 107 | 128 | public String toString() { |
| 108 | 129 | switch (type) { |
| 109 | - case RETRY: return "Retry at " + retryCL; | |
| 110 | - case RETHROW: return "Rethrow"; | |
| 111 | - case IGNORE: return "Ignore"; | |
| 130 | + case RETRY: return "Retry at " + retryCL + " on " + (retryCurrent ? "same " : "next ") + "host."; | |
| 131 | + case RETHROW: return "Rethrow"; | |
| 132 | + case IGNORE: return "Ignore"; | |
| 112 | 133 | } |
| 113 | 134 | throw new AssertionError(); |
| 114 | 135 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +18 −4
| @@ -506,7 +506,13 @@ | ||
| 506 | 506 | |
| 507 | 507 | @AfterClass(groups = { "short", "long" }) |
| 508 | 508 | public void afterClass() { |
| 509 | - clearSimpleKeyspace(); | |
| 509 | + try { | |
| 510 | + clearSimpleKeyspace(); | |
| 511 | + } finally { | |
| 512 | + if(cluster != null) { | |
| 513 | + cluster.close(); | |
| 514 | + } | |
| 515 | + } | |
| 510 | 516 | } |
| 511 | 517 | |
| 512 | 518 | private void maybeInitCluster(){ |
| @@ -570,9 +576,17 @@ | ||
| 570 | 576 | } |
| 571 | 577 | |
| 572 | 578 | private void clearSimpleKeyspace() { |
| 573 | - session.execute("DROP KEYSPACE " + keyspace); | |
| 574 | - if (cluster != null) { | |
| 575 | - cluster.close(); | |
| 579 | + if(keyspace != null) { | |
| 580 | + // Temporarily extend read timeout to 1 minute to accommodate keyspaces with many tables. | |
| 581 | + // This should be more than enough although some tests create many tables, so dropping a keyspace | |
| 582 | + // could take as long as 12 seconds on restricted hardware. | |
| 583 | + int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis(); | |
| 584 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000); | |
| 585 | + try { | |
| 586 | + session.execute("DROP KEYSPACE " + keyspace); | |
| 587 | + } finally { | |
| 588 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout); | |
| 589 | + } | |
| 576 | 590 | } |
| 577 | 591 | } |
| 578 | 592 |
deleted driver-core/src/test/java/com/datastax/driver/core/RetryPolicyTest.java +0 −553
| @@ -1,553 +0,0 @@ | ||
| 1 | -/* | |
| 2 | - * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | - * | |
| 4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | - * you may not use this file except in compliance with the License. | |
| 6 | - * You may obtain a copy of the License at | |
| 7 | - * | |
| 8 | - * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | - * | |
| 10 | - * Unless required by applicable law or agreed to in writing, software | |
| 11 | - * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | - * See the License for the specific language governing permissions and | |
| 14 | - * limitations under the License. | |
| 15 | - */ | |
| 16 | -package com.datastax.driver.core; | |
| 17 | - | |
| 18 | -import org.testng.annotations.Test; | |
| 19 | - | |
| 20 | -import com.datastax.driver.core.exceptions.*; | |
| 21 | -import com.datastax.driver.core.policies.*; | |
| 22 | - | |
| 23 | -import static com.datastax.driver.core.TestUtils.waitFor; | |
| 24 | -import static com.datastax.driver.core.TestUtils.waitForDownWithWait; | |
| 25 | -import static org.testng.Assert.*; | |
| 26 | - | |
| 27 | -public class RetryPolicyTest extends AbstractPoliciesTest { | |
| 28 | - | |
| 29 | - /** | |
| 30 | - * Test RetryPolicy to ensure the basic unit get tests for the RetryDecisions. | |
| 31 | - */ | |
| 32 | - public static class TestRetryPolicy implements RetryPolicy { | |
| 33 | - public RetryDecision onReadTimeout(Statement query, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 34 | - return RetryDecision.rethrow(); | |
| 35 | - } | |
| 36 | - public RetryDecision onWriteTimeout(Statement query, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 37 | - return RetryDecision.rethrow(); | |
| 38 | - } | |
| 39 | - public RetryDecision onUnavailable(Statement query, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 40 | - return RetryDecision.rethrow(); | |
| 41 | - } | |
| 42 | - public static void testRetryDecision() { | |
| 43 | - assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).getType(), RetryDecision.Type.RETRY); | |
| 44 | - assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).getRetryConsistencyLevel(), ConsistencyLevel.ONE); | |
| 45 | - assertEquals(RetryDecision.rethrow().getType(), RetryDecision.Type.RETHROW); | |
| 46 | - assertEquals(RetryDecision.ignore().getType(), RetryDecision.Type.IGNORE); | |
| 47 | - | |
| 48 | - assertEquals(RetryDecision.retry(ConsistencyLevel.ONE).toString(), "Retry at " + ConsistencyLevel.ONE); | |
| 49 | - assertEquals(RetryDecision.rethrow().toString(), "Rethrow"); | |
| 50 | - assertEquals(RetryDecision.ignore().toString(), "Ignore"); | |
| 51 | - } | |
| 52 | - } | |
| 53 | - | |
| 54 | - /** | |
| 55 | - * Test RetryDecision get variables and defaults are correct. | |
| 56 | - */ | |
| 57 | - @Test(groups = "unit") | |
| 58 | - public void RetryDecisionTest() throws Throwable { | |
| 59 | - TestRetryPolicy.testRetryDecision(); | |
| 60 | - } | |
| 61 | - | |
| 62 | - /* | |
| 63 | - * Test the DefaultRetryPolicy. | |
| 64 | - */ | |
| 65 | - @Test(groups = "long") | |
| 66 | - public void defaultRetryPolicy() throws Throwable { | |
| 67 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()); | |
| 68 | - defaultPolicyTest(builder); | |
| 69 | - } | |
| 70 | - | |
| 71 | - /* | |
| 72 | - * Test the DefaultRetryPolicy with Logging enabled. | |
| 73 | - */ | |
| 74 | - @Test(groups = "long") | |
| 75 | - public void defaultLoggingPolicy() throws Throwable { | |
| 76 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()) | |
| 77 | - .withRetryPolicy(new LoggingRetryPolicy(DefaultRetryPolicy.INSTANCE)); | |
| 78 | - defaultPolicyTest(builder); | |
| 79 | - } | |
| 80 | - | |
| 81 | - /* | |
| 82 | - * Test the FallthroughRetryPolicy. | |
| 83 | - * Uses the same code that DefaultRetryPolicy uses. | |
| 84 | - */ | |
| 85 | - @Test(groups = "long") | |
| 86 | - public void fallthroughRetryPolicy() throws Throwable { | |
| 87 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()) | |
| 88 | - .withRetryPolicy(FallthroughRetryPolicy.INSTANCE); | |
| 89 | - defaultPolicyTest(builder); | |
| 90 | - } | |
| 91 | - | |
| 92 | - /* | |
| 93 | - * Test the FallthroughRetryPolicy with Logging enabled. | |
| 94 | - * Uses the same code that DefaultRetryPolicy uses. | |
| 95 | - */ | |
| 96 | - @Test(groups = "long") | |
| 97 | - public void fallthroughLoggingPolicy() throws Throwable { | |
| 98 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()) | |
| 99 | - .withRetryPolicy(new LoggingRetryPolicy(FallthroughRetryPolicy.INSTANCE)); | |
| 100 | - defaultPolicyTest(builder); | |
| 101 | - } | |
| 102 | - | |
| 103 | - public void defaultPolicyTest(Cluster.Builder builder) throws Throwable { | |
| 104 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder); | |
| 105 | - try { | |
| 106 | - createSchema(c.session); | |
| 107 | - // FIXME: Race condition where the nodes are not fully up yet and assertQueried reports slightly different numbers with fallthrough*Policy | |
| 108 | - Thread.sleep(5000); | |
| 109 | - | |
| 110 | - init(c, 12); | |
| 111 | - query(c, 12); | |
| 112 | - | |
| 113 | - assertQueried(CCMBridge.IP_PREFIX + '1', 6); | |
| 114 | - assertQueried(CCMBridge.IP_PREFIX + '2', 6); | |
| 115 | - | |
| 116 | - resetCoordinators(); | |
| 117 | - | |
| 118 | - // Test reads | |
| 119 | - boolean successfulQuery = false; | |
| 120 | - boolean readTimeoutOnce = false; | |
| 121 | - boolean unavailableOnce = false; | |
| 122 | - boolean restartOnce = false; | |
| 123 | - for (int i = 0; i < 10000; ++i) { | |
| 124 | - try { | |
| 125 | - // Force a ReadTimeoutException to be performed once | |
| 126 | - if (!readTimeoutOnce) { | |
| 127 | - c.cassandraCluster.forceStop(2); | |
| 128 | - } | |
| 129 | - | |
| 130 | - // Force an UnavailableException to be performed once | |
| 131 | - if (readTimeoutOnce && !unavailableOnce) { | |
| 132 | - waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 5); | |
| 133 | - } | |
| 134 | - | |
| 135 | - // Bring back node to ensure other errors are not thrown on restart | |
| 136 | - if (unavailableOnce && !restartOnce) { | |
| 137 | - c.cassandraCluster.start(2); | |
| 138 | - restartOnce = true; | |
| 139 | - } | |
| 140 | - | |
| 141 | - query(c, 12); | |
| 142 | - | |
| 143 | - if (restartOnce) | |
| 144 | - successfulQuery = true; | |
| 145 | - } catch (UnavailableException e) { | |
| 146 | - assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage()); | |
| 147 | - unavailableOnce = true; | |
| 148 | - } catch (ReadTimeoutException e) { | |
| 149 | - assertEquals("Cassandra timeout during read query at consistency ONE (1 responses were required but only 0 replica responded)", e.getMessage()); | |
| 150 | - readTimeoutOnce = true; | |
| 151 | - } | |
| 152 | - } | |
| 153 | - | |
| 154 | - // Ensure the full cycle was completed | |
| 155 | - assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n"); | |
| 156 | - assertTrue(readTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n"); | |
| 157 | - assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n"); | |
| 158 | - | |
| 159 | - // A weak test to ensure that the nodes were contacted | |
| 160 | - assertQueriedAtLeast(CCMBridge.IP_PREFIX + '1', 1); | |
| 161 | - assertQueriedAtLeast(CCMBridge.IP_PREFIX + '2', 1); | |
| 162 | - | |
| 163 | - resetCoordinators(); | |
| 164 | - | |
| 165 | - | |
| 166 | - // Test writes | |
| 167 | - successfulQuery = false; | |
| 168 | - boolean writeTimeoutOnce = false; | |
| 169 | - unavailableOnce = false; | |
| 170 | - restartOnce = false; | |
| 171 | - for (int i = 0; i < 100; ++i) { | |
| 172 | - try { | |
| 173 | - // Force a WriteTimeoutException to be performed once | |
| 174 | - if (!writeTimeoutOnce) { | |
| 175 | - c.cassandraCluster.forceStop(2); | |
| 176 | - } | |
| 177 | - | |
| 178 | - // Force an UnavailableException to be performed once | |
| 179 | - if (writeTimeoutOnce && !unavailableOnce) { | |
| 180 | - waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 5); | |
| 181 | - } | |
| 182 | - | |
| 183 | - // Bring back node to ensure other errors are not thrown on restart | |
| 184 | - if (unavailableOnce && !restartOnce) { | |
| 185 | - c.cassandraCluster.start(2); | |
| 186 | - waitFor(CCMBridge.IP_PREFIX + "2", c.cluster); | |
| 187 | - restartOnce = true; | |
| 188 | - } | |
| 189 | - | |
| 190 | - write(c, 12); | |
| 191 | - | |
| 192 | - if (restartOnce) | |
| 193 | - successfulQuery = true; | |
| 194 | - } catch (UnavailableException e) { | |
| 195 | - assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage()); | |
| 196 | - unavailableOnce = true; | |
| 197 | - } catch (WriteTimeoutException e) { | |
| 198 | - assertEquals("Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)", e.getMessage()); | |
| 199 | - writeTimeoutOnce = true; | |
| 200 | - } | |
| 201 | - } | |
| 202 | - // Ensure the full cycle was completed | |
| 203 | - assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n"); | |
| 204 | - assertTrue(writeTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n"); | |
| 205 | - assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n"); | |
| 206 | - | |
| 207 | - // TODO: Missing test to see if nodes were written to | |
| 208 | - | |
| 209 | - | |
| 210 | - // Test batch writes | |
| 211 | - successfulQuery = false; | |
| 212 | - writeTimeoutOnce = false; | |
| 213 | - unavailableOnce = false; | |
| 214 | - restartOnce = false; | |
| 215 | - for (int i = 0; i < 100; ++i) { | |
| 216 | - try { | |
| 217 | - // Force a WriteTimeoutException to be performed once | |
| 218 | - if (!writeTimeoutOnce) { | |
| 219 | - c.cassandraCluster.forceStop(2); | |
| 220 | - } | |
| 221 | - | |
| 222 | - // Force an UnavailableException to be performed once | |
| 223 | - if (writeTimeoutOnce && !unavailableOnce) { | |
| 224 | - waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 5); | |
| 225 | - } | |
| 226 | - | |
| 227 | - // Bring back node to ensure other errors are not thrown on restart | |
| 228 | - if (unavailableOnce && !restartOnce) { | |
| 229 | - c.cassandraCluster.start(2); | |
| 230 | - waitFor(CCMBridge.IP_PREFIX + "2", c.cluster); | |
| 231 | - restartOnce = true; | |
| 232 | - } | |
| 233 | - | |
| 234 | - write(c, 12, true); | |
| 235 | - | |
| 236 | - if (restartOnce) | |
| 237 | - successfulQuery = true; | |
| 238 | - } catch (UnavailableException e) { | |
| 239 | - assertEquals("Not enough replica available for query at consistency ONE (1 required but only 0 alive)", e.getMessage()); | |
| 240 | - unavailableOnce = true; | |
| 241 | - } catch (WriteTimeoutException e) { | |
| 242 | - assertEquals("Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)", e.getMessage()); | |
| 243 | - writeTimeoutOnce = true; | |
| 244 | - } | |
| 245 | - } | |
| 246 | - // Ensure the full cycle was completed | |
| 247 | - assertTrue(successfulQuery, "Hit testing race condition. [Never completed successfully.] (Shouldn't be an issue.):\n"); | |
| 248 | - assertTrue(writeTimeoutOnce, "Hit testing race condition. [Never encountered a ReadTimeoutException.] (Shouldn't be an issue.):\n"); | |
| 249 | - assertTrue(unavailableOnce, "Hit testing race condition. [Never encountered an UnavailableException.] (Shouldn't be an issue.):\n"); | |
| 250 | - | |
| 251 | - // TODO: Missing test to see if nodes were written to | |
| 252 | - | |
| 253 | - } catch (Throwable e) { | |
| 254 | - c.errorOut(); | |
| 255 | - throw e; | |
| 256 | - } finally { | |
| 257 | - resetCoordinators(); | |
| 258 | - c.discard(); | |
| 259 | - } | |
| 260 | - } | |
| 261 | - | |
| 262 | - /** | |
| 263 | - * Tests DowngradingConsistencyRetryPolicy | |
| 264 | - */ | |
| 265 | - @Test(groups = "long") | |
| 266 | - public void downgradingConsistencyRetryPolicy() throws Throwable { | |
| 267 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()) | |
| 268 | - .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 269 | - downgradingConsistencyRetryPolicy(builder); | |
| 270 | - } | |
| 271 | - | |
| 272 | - /** | |
| 273 | - * Tests DowngradingConsistencyRetryPolicy with LoggingRetryPolicy | |
| 274 | - */ | |
| 275 | - @Test(groups = "long") | |
| 276 | - public void downgradingConsistencyLoggingPolicy() throws Throwable { | |
| 277 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()) | |
| 278 | - .withRetryPolicy(new LoggingRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE)); | |
| 279 | - downgradingConsistencyRetryPolicy(builder); | |
| 280 | - } | |
| 281 | - | |
| 282 | - /** | |
| 283 | - * Tests DowngradingConsistencyRetryPolicy | |
| 284 | - */ | |
| 285 | - public void downgradingConsistencyRetryPolicy(Cluster.Builder builder) throws Throwable { | |
| 286 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 287 | - try { | |
| 288 | - createSchema(c.session, 3); | |
| 289 | - // FIXME: Race condition where the nodes are not fully up yet and assertQueried reports slightly different numbers | |
| 290 | - Thread.sleep(5000); | |
| 291 | - | |
| 292 | - init(c, 12, ConsistencyLevel.ALL); | |
| 293 | - query(c, 12, ConsistencyLevel.ALL); | |
| 294 | - | |
| 295 | - assertQueried(CCMBridge.IP_PREFIX + '1', 4); | |
| 296 | - assertQueried(CCMBridge.IP_PREFIX + '2', 4); | |
| 297 | - assertQueried(CCMBridge.IP_PREFIX + '3', 4); | |
| 298 | - | |
| 299 | - resetCoordinators(); | |
| 300 | - c.cassandraCluster.stop(2); | |
| 301 | - waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 10); | |
| 302 | - | |
| 303 | - query(c, 12, ConsistencyLevel.ALL); | |
| 304 | - | |
| 305 | - assertQueried(CCMBridge.IP_PREFIX + '1', 6); | |
| 306 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 307 | - assertQueried(CCMBridge.IP_PREFIX + '3', 6); | |
| 308 | - | |
| 309 | - resetCoordinators(); | |
| 310 | - c.cassandraCluster.stop(1); | |
| 311 | - waitForDownWithWait(CCMBridge.IP_PREFIX + '1', c.cluster, 10); | |
| 312 | - | |
| 313 | - try { | |
| 314 | - query(c, 12, ConsistencyLevel.ALL); | |
| 315 | - } catch (ReadTimeoutException e) { | |
| 316 | - assertEquals("Cassandra timeout during read query at consistency TWO (2 responses were required but only 1 replica responded)", e.getMessage()); | |
| 317 | - } | |
| 318 | - | |
| 319 | - Thread.sleep(15000); | |
| 320 | - resetCoordinators(); | |
| 321 | - | |
| 322 | - try { | |
| 323 | - query(c, 12, ConsistencyLevel.TWO); | |
| 324 | - } catch (Exception e) { | |
| 325 | - fail("Only 1 node is up and CL.TWO should downgrade and pass."); | |
| 326 | - } | |
| 327 | - | |
| 328 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 329 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 330 | - assertQueried(CCMBridge.IP_PREFIX + '3', 12); | |
| 331 | - | |
| 332 | - resetCoordinators(); | |
| 333 | - | |
| 334 | - try { | |
| 335 | - query(c, 12, ConsistencyLevel.ALL); | |
| 336 | - } catch (Exception e) { | |
| 337 | - fail("Only 1 node is up and CL.ALL should downgrade and pass."); | |
| 338 | - } | |
| 339 | - | |
| 340 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 341 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 342 | - assertQueried(CCMBridge.IP_PREFIX + '3', 12); | |
| 343 | - | |
| 344 | - resetCoordinators(); | |
| 345 | - | |
| 346 | - query(c, 12, ConsistencyLevel.QUORUM); | |
| 347 | - | |
| 348 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 349 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 350 | - assertQueried(CCMBridge.IP_PREFIX + '3', 12); | |
| 351 | - | |
| 352 | - resetCoordinators(); | |
| 353 | - | |
| 354 | - query(c, 12, ConsistencyLevel.TWO); | |
| 355 | - | |
| 356 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 357 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 358 | - assertQueried(CCMBridge.IP_PREFIX + '3', 12); | |
| 359 | - | |
| 360 | - resetCoordinators(); | |
| 361 | - | |
| 362 | - query(c, 12, ConsistencyLevel.ONE); | |
| 363 | - | |
| 364 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 365 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 366 | - assertQueried(CCMBridge.IP_PREFIX + '3', 12); | |
| 367 | - | |
| 368 | - } catch (Throwable e) { | |
| 369 | - c.errorOut(); | |
| 370 | - throw e; | |
| 371 | - } finally { | |
| 372 | - resetCoordinators(); | |
| 373 | - c.discard(); | |
| 374 | - } | |
| 375 | - } | |
| 376 | - | |
| 377 | - /* | |
| 378 | - * Test the AlwaysIgnoreRetryPolicy with Logging enabled. | |
| 379 | - */ | |
| 380 | - @Test(groups = "long") | |
| 381 | - public void alwaysIgnoreRetryPolicyTest() throws Throwable { | |
| 382 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()) | |
| 383 | - .withRetryPolicy(new LoggingRetryPolicy(AlwaysIgnoreRetryPolicy.INSTANCE)); | |
| 384 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder); | |
| 385 | - | |
| 386 | - try { | |
| 387 | - createSchema(c.session); | |
| 388 | - init(c, 12); | |
| 389 | - query(c, 12); | |
| 390 | - | |
| 391 | - assertQueried(CCMBridge.IP_PREFIX + '1', 6); | |
| 392 | - assertQueried(CCMBridge.IP_PREFIX + '2', 6); | |
| 393 | - | |
| 394 | - resetCoordinators(); | |
| 395 | - | |
| 396 | - // Test failed reads | |
| 397 | - c.cassandraCluster.forceStop(2); | |
| 398 | - for (int i = 0; i < 10; ++i) { | |
| 399 | - query(c, 12); | |
| 400 | - } | |
| 401 | - | |
| 402 | - // A weak test to ensure that the nodes were contacted | |
| 403 | - assertQueried(CCMBridge.IP_PREFIX + '1', 120); | |
| 404 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 405 | - resetCoordinators(); | |
| 406 | - | |
| 407 | - | |
| 408 | - c.cassandraCluster.start(2); | |
| 409 | - waitFor(CCMBridge.IP_PREFIX + '2', c.cluster); | |
| 410 | - | |
| 411 | - // Test successful reads | |
| 412 | - for (int i = 0; i < 10; ++i) { | |
| 413 | - query(c, 12); | |
| 414 | - } | |
| 415 | - | |
| 416 | - // A weak test to ensure that the nodes were contacted | |
| 417 | - assertQueriedAtLeast(CCMBridge.IP_PREFIX + '1', 1); | |
| 418 | - assertQueriedAtLeast(CCMBridge.IP_PREFIX + '2', 1); | |
| 419 | - resetCoordinators(); | |
| 420 | - | |
| 421 | - | |
| 422 | - // Test writes | |
| 423 | - for (int i = 0; i < 100; ++i) { | |
| 424 | - init(c, 12); | |
| 425 | - } | |
| 426 | - | |
| 427 | - // TODO: Missing test to see if nodes were written to | |
| 428 | - | |
| 429 | - | |
| 430 | - // Test failed writes | |
| 431 | - c.cassandraCluster.forceStop(2); | |
| 432 | - for (int i = 0; i < 100; ++i) { | |
| 433 | - init(c, 12); | |
| 434 | - } | |
| 435 | - | |
| 436 | - // TODO: Missing test to see if nodes were written to | |
| 437 | - | |
| 438 | - } catch (Throwable e) { | |
| 439 | - c.errorOut(); | |
| 440 | - throw e; | |
| 441 | - } finally { | |
| 442 | - resetCoordinators(); | |
| 443 | - c.discard(); | |
| 444 | - } | |
| 445 | - } | |
| 446 | - | |
| 447 | - private class QueryRunnable implements Runnable { | |
| 448 | - private CCMBridge.CCMCluster c; | |
| 449 | - private int i; | |
| 450 | - | |
| 451 | - public QueryRunnable(CCMBridge.CCMCluster c, int i) { | |
| 452 | - this.c = c; | |
| 453 | - this.i = i; | |
| 454 | - } | |
| 455 | - | |
| 456 | - public void run(){ | |
| 457 | - query(c, i); | |
| 458 | - } | |
| 459 | - } | |
| 460 | - | |
| 461 | - private class InitRunnable implements Runnable { | |
| 462 | - private CCMBridge.CCMCluster c; | |
| 463 | - private int i; | |
| 464 | - | |
| 465 | - public InitRunnable(CCMBridge.CCMCluster c, int i) { | |
| 466 | - this.c = c; | |
| 467 | - this.i = i; | |
| 468 | - } | |
| 469 | - | |
| 470 | - public void run(){ | |
| 471 | - try { | |
| 472 | - init(c, i); | |
| 473 | - fail(); | |
| 474 | - } catch (DriverInternalError e) { | |
| 475 | - } catch (NoHostAvailableException e) { } | |
| 476 | - } | |
| 477 | - } | |
| 478 | - | |
| 479 | - /* | |
| 480 | - * Test the AlwaysIgnoreRetryPolicy with Logging enabled. | |
| 481 | - */ | |
| 482 | - @Test(groups = "long") | |
| 483 | - public void alwaysRetryRetryPolicyTest() throws Throwable { | |
| 484 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new RoundRobinPolicy()) | |
| 485 | - .withRetryPolicy(new LoggingRetryPolicy(AlwaysRetryRetryPolicy.INSTANCE)); | |
| 486 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, builder); | |
| 487 | - | |
| 488 | - try { | |
| 489 | - createSchema(c.session); | |
| 490 | - init(c, 12); | |
| 491 | - query(c, 12); | |
| 492 | - | |
| 493 | - assertQueried(CCMBridge.IP_PREFIX + '1', 6); | |
| 494 | - assertQueried(CCMBridge.IP_PREFIX + '2', 6); | |
| 495 | - | |
| 496 | - resetCoordinators(); | |
| 497 | - | |
| 498 | - // Test failed reads | |
| 499 | - c.cassandraCluster.forceStop(2); | |
| 500 | - | |
| 501 | - Thread t1 = new Thread(new QueryRunnable(c, 12)); | |
| 502 | - t1.start(); | |
| 503 | - t1.join(10000); | |
| 504 | - if (t1.isAlive()) | |
| 505 | - t1.interrupt(); | |
| 506 | - | |
| 507 | - // A weak test to ensure that the nodes were contacted | |
| 508 | - assertQueried(CCMBridge.IP_PREFIX + '1', 0); | |
| 509 | - assertQueried(CCMBridge.IP_PREFIX + '2', 0); | |
| 510 | - resetCoordinators(); | |
| 511 | - | |
| 512 | - | |
| 513 | - c.cassandraCluster.start(2); | |
| 514 | - waitFor(CCMBridge.IP_PREFIX + '2', c.cluster); | |
| 515 | - | |
| 516 | - // Test successful reads | |
| 517 | - for (int i = 0; i < 10; ++i) { | |
| 518 | - query(c, 12); | |
| 519 | - } | |
| 520 | - | |
| 521 | - // A weak test to ensure that the nodes were contacted | |
| 522 | - assertQueriedAtLeast(CCMBridge.IP_PREFIX + '1', 1); | |
| 523 | - assertQueriedAtLeast(CCMBridge.IP_PREFIX + '2', 1); | |
| 524 | - resetCoordinators(); | |
| 525 | - | |
| 526 | - | |
| 527 | - // Test writes | |
| 528 | - for (int i = 0; i < 100; ++i) { | |
| 529 | - init(c, 12); | |
| 530 | - } | |
| 531 | - | |
| 532 | - // TODO: Missing test to see if nodes were written to | |
| 533 | - | |
| 534 | - | |
| 535 | - // Test failed writes | |
| 536 | - c.cassandraCluster.forceStop(2); | |
| 537 | - Thread t2 = new Thread(new InitRunnable(c, 12)); | |
| 538 | - t2.start(); | |
| 539 | - t2.join(10000); | |
| 540 | - if (t2.isAlive()) | |
| 541 | - t2.interrupt(); | |
| 542 | - | |
| 543 | - // TODO: Missing test to see if nodes were written to | |
| 544 | - | |
| 545 | - } catch (Throwable e) { | |
| 546 | - c.errorOut(); | |
| 547 | - throw e; | |
| 548 | - } finally { | |
| 549 | - resetCoordinators(); | |
| 550 | - c.discard(); | |
| 551 | - } | |
| 552 | - } | |
| 553 | -} |
modified driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +16 −3
| @@ -25,9 +25,7 @@ | ||
| 25 | 25 | import com.google.common.collect.Lists; |
| 26 | 26 | import org.scassandra.Scassandra; |
| 27 | 27 | import org.scassandra.ScassandraFactory; |
| 28 | -import org.scassandra.http.client.ColumnTypes; | |
| 29 | -import org.scassandra.http.client.PrimingClient; | |
| 30 | -import org.scassandra.http.client.PrimingRequest; | |
| 28 | +import org.scassandra.http.client.*; | |
| 31 | 29 | |
| 32 | 30 | /** |
| 33 | 31 | * Launches multiple SCassandra instances, and mocks the appropriate request to make the driver think |
| @@ -43,11 +41,13 @@ | ||
| 43 | 41 | private final List<Scassandra> scassandras; |
| 44 | 42 | private final List<InetAddress> addresses; |
| 45 | 43 | private final List<PrimingClient> primingClients; |
| 44 | + private final List<ActivityClient> activityClients; | |
| 46 | 45 | |
| 47 | 46 | public SCassandraCluster(String ipPrefix, int nodeCount) { |
| 48 | 47 | scassandras = Lists.newArrayListWithCapacity(nodeCount); |
| 49 | 48 | addresses = Lists.newArrayListWithCapacity(nodeCount); |
| 50 | 49 | primingClients = Lists.newArrayListWithCapacity(nodeCount); |
| 50 | + activityClients = Lists.newArrayListWithCapacity(nodeCount); | |
| 51 | 51 | |
| 52 | 52 | for (int i = 1; i <= nodeCount; i++) { |
| 53 | 53 | String ip = ipPrefix + i; |
| @@ -64,6 +64,10 @@ | ||
| 64 | 64 | primingClients.add(PrimingClient.builder() |
| 65 | 65 | .withHost(ip).withPort(scassandra.getAdminPort()) |
| 66 | 66 | .build()); |
| 67 | + activityClients.add(ActivityClient.builder() | |
| 68 | + .withHost(ip).withPort(scassandra.getAdminPort()) | |
| 69 | + .build() | |
| 70 | + ); | |
| 67 | 71 | } |
| 68 | 72 | primePeers(); |
| 69 | 73 | } |
| @@ -82,12 +86,21 @@ | ||
| 82 | 86 | return this; |
| 83 | 87 | } |
| 84 | 88 | |
| 89 | + public List<Query> retrieveQueries(int node) { | |
| 90 | + return activityClients.get(node - 1).retrieveQueries(); | |
| 91 | + } | |
| 92 | + | |
| 85 | 93 | public void clearAllPrimes() { |
| 86 | 94 | for (PrimingClient primingClient : primingClients) |
| 87 | 95 | primingClient.clearAllPrimes(); |
| 88 | 96 | primePeers(); |
| 89 | 97 | } |
| 90 | 98 | |
| 99 | + public void clearAllRecordedActivity() { | |
| 100 | + for (ActivityClient activityClient : activityClients) | |
| 101 | + activityClient.clearAllRecordedActivity(); | |
| 102 | + } | |
| 103 | + | |
| 91 | 104 | private void primePeers() { |
| 92 | 105 | for (int i = 0; i < scassandras.size(); i++) |
| 93 | 106 | primePeers(primingClients.get(i), scassandras.get(i)); |
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +100 −91
| @@ -20,6 +20,8 @@ | ||
| 20 | 20 | import com.google.common.util.concurrent.*; |
| 21 | 21 | import org.slf4j.Logger; |
| 22 | 22 | import org.slf4j.LoggerFactory; |
| 23 | +import org.testng.annotations.AfterMethod; | |
| 24 | +import org.testng.annotations.BeforeMethod; | |
| 23 | 25 | import org.testng.annotations.Test; |
| 24 | 26 | |
| 25 | 27 | import java.net.InetSocketAddress; |
| @@ -35,6 +37,12 @@ | ||
| 35 | 37 | |
| 36 | 38 | private ListeningExecutorService executorService; |
| 37 | 39 | |
| 40 | + private Cluster stressCluster; | |
| 41 | + | |
| 42 | + private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor(); | |
| 43 | + | |
| 44 | + private List<InetSocketAddress> contactPoints; | |
| 45 | + | |
| 38 | 46 | public SessionStressTest() { |
| 39 | 47 | // 8 threads should be enough so that we stress the driver and not the OS thread scheduler |
| 40 | 48 | executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8)); |
| @@ -45,6 +53,27 @@ | ||
| 45 | 53 | return new ArrayList<String>(0); |
| 46 | 54 | } |
| 47 | 55 | |
| 56 | + @BeforeMethod | |
| 57 | + public void setUp() { | |
| 58 | + contactPoints = Collections.singletonList(hostAddress); | |
| 59 | + // override inherited field with a new cluster object and ensure 0 sessions and connections | |
| 60 | + channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); | |
| 61 | + stressCluster = Cluster.builder().addContactPointsWithPorts(contactPoints) | |
| 62 | + .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)) | |
| 63 | + .withNettyOptions(channelMonitor.nettyOptions()).build(); | |
| 64 | + stressCluster.init(); | |
| 65 | + } | |
| 66 | + | |
| 67 | + @AfterMethod | |
| 68 | + public void tearDown() { | |
| 69 | + stressCluster.close(); | |
| 70 | + | |
| 71 | + // Ensure no channels remain open. | |
| 72 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 0); | |
| 73 | + | |
| 74 | + channelMonitor.stop(); | |
| 75 | + channelMonitor.report(); | |
| 76 | + } | |
| 48 | 77 | |
| 49 | 78 | /** |
| 50 | 79 | * Stress test on opening/closing sessions. |
| @@ -71,100 +100,82 @@ | ||
| 71 | 100 | */ |
| 72 | 101 | @Test(groups = "long") |
| 73 | 102 | public void sessions_should_not_leak_connections() { |
| 74 | - // override inherited field with a new cluster object and ensure 0 sessions and connections | |
| 75 | - SocketChannelMonitor channelMonitor = new SocketChannelMonitor(); | |
| 76 | - channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); | |
| 77 | - List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress); | |
| 78 | - cluster = Cluster.builder().addContactPointsWithPorts(contactPoints) | |
| 79 | - .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1)) | |
| 80 | - .withNettyOptions(channelMonitor.nettyOptions()).build(); | |
| 81 | - cluster.init(); | |
| 82 | - | |
| 83 | 103 | // The cluster has been initialized, we should have 1 connection. |
| 84 | - assertEquals(cluster.manager.sessions.size(), 0); | |
| 85 | - assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 104 | + assertEquals(stressCluster.manager.sessions.size(), 0); | |
| 105 | + assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 86 | 106 | |
| 87 | 107 | // The first session initializes the cluster and its control connection |
| 88 | 108 | // This is a local cluster so we also have 2 connections per session |
| 89 | - Session session = cluster.connect(); | |
| 90 | - assertEquals(cluster.manager.sessions.size(), 1); | |
| 91 | - int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster); | |
| 92 | - assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections); | |
| 109 | + Session session = stressCluster.connect(); | |
| 110 | + assertEquals(stressCluster.manager.sessions.size(), 1); | |
| 111 | + int coreConnections = TestUtils.numberOfLocalCoreConnections(stressCluster); | |
| 112 | + assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections); | |
| 93 | 113 | assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections); |
| 94 | 114 | |
| 95 | 115 | // Closing the session keeps the control connection opened |
| 96 | 116 | session.close(); |
| 97 | - assertEquals(cluster.manager.sessions.size(), 0); | |
| 98 | - assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 117 | + assertEquals(stressCluster.manager.sessions.size(), 0); | |
| 118 | + assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 99 | 119 | assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); |
| 100 | 120 | |
| 101 | - try { | |
| 102 | - int nbOfSessions = 2000; | |
| 103 | - int halfOfTheSessions = nbOfSessions / 2; | |
| 104 | - int nbOfIterations = 5; | |
| 105 | - int sleepTime = 20; | |
| 106 | - | |
| 107 | - for (int iteration = 1; iteration <= nbOfIterations; iteration++) { | |
| 108 | - logger.info("On iteration {}/{}.", iteration, nbOfIterations); | |
| 109 | - logger.info("Creating {} sessions.", nbOfSessions); | |
| 110 | - waitFor(openSessionsConcurrently(nbOfSessions)); | |
| 111 | - | |
| 112 | - // We should see the exact number of opened sessions | |
| 113 | - // Since we have 2 connections per session, we should see 2 * sessions + control connection | |
| 114 | - assertEquals(cluster.manager.sessions.size(), nbOfSessions); | |
| 115 | - assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), | |
| 116 | - coreConnections * nbOfSessions + 1); | |
| 117 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1); | |
| 118 | - | |
| 119 | - // Close half of the sessions asynchronously | |
| 120 | - logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions); | |
| 121 | - waitFor(closeSessionsConcurrently(halfOfTheSessions)); | |
| 122 | - | |
| 123 | - // Check that we have the right number of sessions and connections | |
| 124 | - assertEquals(cluster.manager.sessions.size(), halfOfTheSessions); | |
| 125 | - assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), | |
| 126 | - coreConnections * (nbOfSessions / 2) + 1); | |
| 127 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), | |
| 128 | - coreConnections * (nbOfSessions / 2) + 1); | |
| 129 | - | |
| 130 | - // Close and open the same number of sessions concurrently | |
| 131 | - logger.info("Closing and Opening {} sessions concurrently.", halfOfTheSessions); | |
| 132 | - CountDownLatch startSignal = new CountDownLatch(2); | |
| 133 | - List<ListenableFuture<Session>> openSessionFutures = | |
| 134 | - openSessionsConcurrently(halfOfTheSessions, startSignal); | |
| 135 | - List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions, | |
| 136 | - startSignal); | |
| 137 | - startSignal.countDown(); | |
| 138 | - waitFor(openSessionFutures); | |
| 139 | - waitFor(closeSessionsFutures); | |
| 140 | - | |
| 141 | - // Check that we have the same number of sessions and connections | |
| 142 | - assertEquals(cluster.manager.sessions.size(), halfOfTheSessions); | |
| 143 | - assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), | |
| 144 | - coreConnections * (nbOfSessions / 2) + 1); | |
| 145 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), | |
| 146 | - coreConnections * (nbOfSessions / 2) + 1); | |
| 147 | - | |
| 148 | - // Close the remaining sessions | |
| 149 | - logger.info("Closing remaining {} sessions.", halfOfTheSessions); | |
| 150 | - waitFor(closeSessionsConcurrently(halfOfTheSessions)); | |
| 151 | - | |
| 152 | - // Check that we have a clean state | |
| 153 | - assertEquals(cluster.manager.sessions.size(), 0); | |
| 154 | - assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 155 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 156 | - | |
| 157 | - // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl) | |
| 158 | - logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime); | |
| 159 | - Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS); | |
| 160 | - } | |
| 161 | - } finally { | |
| 162 | - cluster.close(); | |
| 163 | - | |
| 164 | - // Ensure no channels remain open. | |
| 165 | - channelMonitor.stop(); | |
| 166 | - channelMonitor.report(); | |
| 167 | - assertEquals(channelMonitor.openChannels(contactPoints).size(), 0); | |
| 121 | + int nbOfSessions = 2000; | |
| 122 | + int halfOfTheSessions = nbOfSessions / 2; | |
| 123 | + int nbOfIterations = 5; | |
| 124 | + int sleepTime = 20; | |
| 125 | + | |
| 126 | + for (int iteration = 1; iteration <= nbOfIterations; iteration++) { | |
| 127 | + logger.info("On iteration {}/{}.", iteration, nbOfIterations); | |
| 128 | + logger.info("Creating {} sessions.", nbOfSessions); | |
| 129 | + waitFor(openSessionsConcurrently(nbOfSessions)); | |
| 130 | + | |
| 131 | + // We should see the exact number of opened sessions | |
| 132 | + // Since we have 2 connections per session, we should see 2 * sessions + control connection | |
| 133 | + assertEquals(stressCluster.manager.sessions.size(), nbOfSessions); | |
| 134 | + assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), | |
| 135 | + coreConnections * nbOfSessions + 1); | |
| 136 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1); | |
| 137 | + | |
| 138 | + // Close half of the sessions asynchronously | |
| 139 | + logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions); | |
| 140 | + waitFor(closeSessionsConcurrently(halfOfTheSessions)); | |
| 141 | + | |
| 142 | + // Check that we have the right number of sessions and connections | |
| 143 | + assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions); | |
| 144 | + assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), | |
| 145 | + coreConnections * (nbOfSessions / 2) + 1); | |
| 146 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), | |
| 147 | + coreConnections * (nbOfSessions / 2) + 1); | |
| 148 | + | |
| 149 | + // Close and open the same number of sessions concurrently | |
| 150 | + logger.info("Closing and Opening {} sessions concurrently.", halfOfTheSessions); | |
| 151 | + CountDownLatch startSignal = new CountDownLatch(2); | |
| 152 | + List<ListenableFuture<Session>> openSessionFutures = | |
| 153 | + openSessionsConcurrently(halfOfTheSessions, startSignal); | |
| 154 | + List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions, | |
| 155 | + startSignal); | |
| 156 | + startSignal.countDown(); | |
| 157 | + waitFor(openSessionFutures); | |
| 158 | + waitFor(closeSessionsFutures); | |
| 159 | + | |
| 160 | + // Check that we have the same number of sessions and connections | |
| 161 | + assertEquals(stressCluster.manager.sessions.size(), halfOfTheSessions); | |
| 162 | + assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), | |
| 163 | + coreConnections * (nbOfSessions / 2) + 1); | |
| 164 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), | |
| 165 | + coreConnections * (nbOfSessions / 2) + 1); | |
| 166 | + | |
| 167 | + // Close the remaining sessions | |
| 168 | + logger.info("Closing remaining {} sessions.", halfOfTheSessions); | |
| 169 | + waitFor(closeSessionsConcurrently(halfOfTheSessions)); | |
| 170 | + | |
| 171 | + // Check that we have a clean state | |
| 172 | + assertEquals(stressCluster.manager.sessions.size(), 0); | |
| 173 | + assertEquals((int) stressCluster.getMetrics().getOpenConnections().getValue(), 1); | |
| 174 | + assertEquals(channelMonitor.openChannels(contactPoints).size(), 1); | |
| 175 | + | |
| 176 | + // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl) | |
| 177 | + logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime); | |
| 178 | + Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS); | |
| 168 | 179 | } |
| 169 | 180 | } |
| 170 | 181 | |
| @@ -177,7 +188,7 @@ | ||
| 177 | 188 | // Open new sessions once all tasks have been created |
| 178 | 189 | List<ListenableFuture<Session>> sessionFutures = Lists.newArrayListWithCapacity(iterations); |
| 179 | 190 | for (int i = 0; i < iterations; i++) { |
| 180 | - sessionFutures.add(executorService.submit(new OpenSession(cluster, countDownLatch))); | |
| 191 | + sessionFutures.add(executorService.submit(new OpenSession(countDownLatch))); | |
| 181 | 192 | } |
| 182 | 193 | countDownLatch.countDown(); |
| 183 | 194 | return sessionFutures; |
| @@ -191,7 +202,7 @@ | ||
| 191 | 202 | private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations, CountDownLatch countDownLatch) { |
| 192 | 203 | // Get a reference to every session we want to close |
| 193 | 204 | Stack<Session> sessionsToClose = new Stack<Session>(); |
| 194 | - Iterator<? extends Session> iterator = cluster.manager.sessions.iterator(); | |
| 205 | + Iterator<? extends Session> iterator = stressCluster.manager.sessions.iterator(); | |
| 195 | 206 | for (int i = 0; i < iterations; i++) { |
| 196 | 207 | sessionsToClose.push(iterator.next()); |
| 197 | 208 | } |
| @@ -228,19 +239,17 @@ | ||
| 228 | 239 | } |
| 229 | 240 | } |
| 230 | 241 | |
| 231 | - private static class OpenSession implements Callable<Session> { | |
| 232 | - private final Cluster cluster; | |
| 242 | + private class OpenSession implements Callable<Session> { | |
| 233 | 243 | private final CountDownLatch startSignal; |
| 234 | 244 | |
| 235 | - OpenSession(Cluster cluster, CountDownLatch startSignal) { | |
| 236 | - this.cluster = cluster; | |
| 245 | + OpenSession(CountDownLatch startSignal) { | |
| 237 | 246 | this.startSignal = startSignal; |
| 238 | 247 | } |
| 239 | 248 | |
| 240 | 249 | @Override |
| 241 | 250 | public Session call() throws Exception { |
| 242 | 251 | startSignal.await(); |
| 243 | - return cluster.connect(); | |
| 252 | + return stressCluster.connect(); | |
| 244 | 253 | } |
| 245 | 254 | } |
| 246 | 255 |
added driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java +83 −0
| @@ -0,0 +1,83 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +import java.util.Collection; | |
| 19 | +import java.util.Comparator; | |
| 20 | +import java.util.Iterator; | |
| 21 | +import java.util.SortedSet; | |
| 22 | +import java.util.concurrent.ConcurrentSkipListSet; | |
| 23 | + | |
| 24 | +import com.google.common.primitives.UnsignedBytes; | |
| 25 | + | |
| 26 | +import com.datastax.driver.core.policies.LoadBalancingPolicy; | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * A load balancing policy that sorts hosts on the last byte of the address, | |
| 30 | + * so that the query plan is always [host1, host2, host3]. | |
| 31 | + */ | |
| 32 | +public class SortingLoadBalancingPolicy implements LoadBalancingPolicy { | |
| 33 | + | |
| 34 | + private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() { | |
| 35 | + @Override | |
| 36 | + public int compare(Host host1, Host host2) { | |
| 37 | + byte[] address1 = host1.getAddress().getAddress(); | |
| 38 | + byte[] address2 = host2.getAddress().getAddress(); | |
| 39 | + return UnsignedBytes.compare( | |
| 40 | + address1[address1.length - 1], | |
| 41 | + address2[address2.length - 1]); | |
| 42 | + } | |
| 43 | + }); | |
| 44 | + | |
| 45 | + @Override | |
| 46 | + public void init(Cluster cluster, Collection<Host> hosts) { | |
| 47 | + this.hosts.addAll(hosts); | |
| 48 | + } | |
| 49 | + | |
| 50 | + @Override | |
| 51 | + public HostDistance distance(Host host) { | |
| 52 | + return HostDistance.LOCAL; | |
| 53 | + } | |
| 54 | + | |
| 55 | + @Override | |
| 56 | + public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 57 | + return hosts.iterator(); | |
| 58 | + } | |
| 59 | + | |
| 60 | + @Override | |
| 61 | + public void onAdd(Host host) { | |
| 62 | + onUp(host); | |
| 63 | + } | |
| 64 | + | |
| 65 | + @Override | |
| 66 | + public void onUp(Host host) { | |
| 67 | + hosts.add(host); | |
| 68 | + } | |
| 69 | + | |
| 70 | + @Override | |
| 71 | + public void onDown(Host host) { | |
| 72 | + hosts.remove(host); | |
| 73 | + } | |
| 74 | + | |
| 75 | + @Override | |
| 76 | + public void onRemove(Host host) { | |
| 77 | + onDown(host); | |
| 78 | + } | |
| 79 | + | |
| 80 | + @Override | |
| 81 | + public void onSuspected(Host host) { | |
| 82 | + } | |
| 83 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +0 −60
| @@ -16,17 +16,14 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import java.util.*; |
| 19 | -import java.util.concurrent.ConcurrentSkipListSet; | |
| 20 | 19 | |
| 21 | 20 | import com.datastax.driver.core.policies.SpeculativeExecutionPolicy; |
| 22 | 21 | import com.google.common.collect.ImmutableList; |
| 23 | 22 | import com.google.common.collect.ImmutableMap; |
| 24 | -import com.google.common.primitives.UnsignedBytes; | |
| 25 | 23 | import org.scassandra.http.client.PrimingRequest; |
| 26 | 24 | import org.testng.annotations.*; |
| 27 | 25 | |
| 28 | 26 | import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy; |
| 29 | -import com.datastax.driver.core.policies.LoadBalancingPolicy; | |
| 30 | 27 | import com.datastax.driver.core.policies.RetryPolicy; |
| 31 | 28 | |
| 32 | 29 | import static com.datastax.driver.core.Assertions.assertThat; |
| @@ -218,63 +215,6 @@ | ||
| 218 | 215 | scassandras.stop(); |
| 219 | 216 | } |
| 220 | 217 | |
| 221 | - /** | |
| 222 | - * A load balancing policy that sorts hosts on the last byte of the address, | |
| 223 | - * so that the query plan is always [host1, host2, host3]. | |
| 224 | - */ | |
| 225 | - static class SortingLoadBalancingPolicy implements LoadBalancingPolicy { | |
| 226 | - | |
| 227 | - private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() { | |
| 228 | - @Override | |
| 229 | - public int compare(Host host1, Host host2) { | |
| 230 | - byte[] address1 = host1.getAddress().getAddress(); | |
| 231 | - byte[] address2 = host2.getAddress().getAddress(); | |
| 232 | - return UnsignedBytes.compare( | |
| 233 | - address1[address1.length - 1], | |
| 234 | - address2[address2.length - 1]); | |
| 235 | - } | |
| 236 | - }); | |
| 237 | - | |
| 238 | - @Override | |
| 239 | - public void init(Cluster cluster, Collection<Host> hosts) { | |
| 240 | - this.hosts.addAll(hosts); | |
| 241 | - } | |
| 242 | - | |
| 243 | - @Override | |
| 244 | - public HostDistance distance(Host host) { | |
| 245 | - return HostDistance.LOCAL; | |
| 246 | - } | |
| 247 | - | |
| 248 | - @Override | |
| 249 | - public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 250 | - return hosts.iterator(); | |
| 251 | - } | |
| 252 | - | |
| 253 | - @Override | |
| 254 | - public void onAdd(Host host) { | |
| 255 | - onUp(host); | |
| 256 | - } | |
| 257 | - | |
| 258 | - @Override | |
| 259 | - public void onUp(Host host) { | |
| 260 | - hosts.add(host); | |
| 261 | - } | |
| 262 | - | |
| 263 | - @Override | |
| 264 | - public void onDown(Host host) { | |
| 265 | - hosts.remove(host); | |
| 266 | - } | |
| 267 | - | |
| 268 | - @Override | |
| 269 | - public void onRemove(Host host) { | |
| 270 | - onDown(host); | |
| 271 | - } | |
| 272 | - | |
| 273 | - @Override | |
| 274 | - public void onSuspected(Host host) { | |
| 275 | - } | |
| 276 | - } | |
| 277 | - | |
| 278 | 218 | /** |
| 279 | 219 | * Custom retry policy that retries at ONE on read timeout. |
| 280 | 220 | * This deals with the fact that Scassandra only allows read timeouts with 0 replicas. |
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +13 −17
| @@ -68,8 +68,6 @@ | ||
| 68 | 68 | |
| 69 | 69 | static List<InetSocketAddress> nodes; |
| 70 | 70 | |
| 71 | - static PreparedStatement statement; | |
| 72 | - | |
| 73 | 71 | @BeforeClass(groups = "long") |
| 74 | 72 | public void beforeClass() throws Exception { |
| 75 | 73 | ccmBridge = CCMBridge.create("test", 3); |
| @@ -87,9 +85,6 @@ | ||
| 87 | 85 | .withPoolingOptions(poolingOptions) |
| 88 | 86 | .withNettyOptions(channelMonitor.nettyOptions()) |
| 89 | 87 | .build(); |
| 90 | - Session session = cluster.connect(); | |
| 91 | - setupSchema(session); | |
| 92 | - session.close(); | |
| 93 | 88 | } |
| 94 | 89 | |
| 95 | 90 | @AfterClass(groups = "long") |
| @@ -129,11 +124,17 @@ | ||
| 129 | 124 | * @since 2.0.10, 2.1.6 |
| 130 | 125 | */ |
| 131 | 126 | @Test(groups = "long") |
| 132 | - public void host_state_should_be_maintained_with_timeouts() { | |
| 127 | + public void host_state_should_be_maintained_with_timeouts() throws Exception { | |
| 128 | + // Setup schema and insert records. | |
| 129 | + Session session = cluster.connect(); | |
| 130 | + setupSchema(session); | |
| 131 | + session.close(); | |
| 132 | + | |
| 133 | 133 | // Set very low timeouts. |
| 134 | 134 | cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS); |
| 135 | 135 | cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS); |
| 136 | - Session session = cluster.connect(); | |
| 136 | + session = cluster.connect(); | |
| 137 | + PreparedStatement statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;"); | |
| 137 | 138 | |
| 138 | 139 | int workers = Runtime.getRuntime().availableProcessors(); |
| 139 | 140 | ExecutorService workerPool = Executors.newFixedThreadPool(workers, |
| @@ -147,7 +148,7 @@ | ||
| 147 | 148 | try { |
| 148 | 149 | Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES); |
| 149 | 150 | for (int i = 0; i < workers; i++) { |
| 150 | - workerPool.submit(new TimeoutStressWorker(session, concurrentQueries, stopped)); | |
| 151 | + workerPool.submit(new TimeoutStressWorker(session, statement, concurrentQueries, stopped)); | |
| 151 | 152 | } |
| 152 | 153 | |
| 153 | 154 | long startTime = System.currentTimeMillis(); |
| @@ -213,20 +214,13 @@ | ||
| 213 | 214 | + ");"); |
| 214 | 215 | |
| 215 | 216 | int records = 30000; |
| 216 | - List<ResultSetFuture> futures = Lists.newArrayListWithExpectedSize(records); | |
| 217 | - | |
| 218 | 217 | PreparedStatement insertStmt = session.prepare("insert into record (name, phone, value) values (?, ?, ?)"); |
| 219 | 218 | |
| 220 | 219 | for (int i = 0; i < records; i++) { |
| 221 | 220 | if (i % 1000 == 0) |
| 222 | 221 | logger.debug("Inserting record {}.", i); |
| 223 | - futures.add(session.executeAsync(insertStmt.bind("0", Integer.toString(i), "test"))); | |
| 222 | + session.execute(insertStmt.bind("0", Integer.toString(i), "test")); | |
| 224 | 223 | } |
| 225 | - | |
| 226 | - statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;"); | |
| 227 | - | |
| 228 | - logger.debug("Completed inserting data. Waiting up to 30 for inserts to complete seconds before proceeding."); | |
| 229 | - Futures.allAsList(futures).get(30, TimeUnit.SECONDS); | |
| 230 | 224 | logger.debug("Inserts complete."); |
| 231 | 225 | } |
| 232 | 226 | |
| @@ -235,9 +229,11 @@ | ||
| 235 | 229 | private final Semaphore concurrentQueries; |
| 236 | 230 | private final AtomicBoolean stopped; |
| 237 | 231 | private final Session session; |
| 232 | + private final PreparedStatement statement; | |
| 238 | 233 | |
| 239 | - public TimeoutStressWorker(Session session, Semaphore concurrentQueries, AtomicBoolean stopped) { | |
| 234 | + public TimeoutStressWorker(Session session, PreparedStatement statement, Semaphore concurrentQueries, AtomicBoolean stopped) { | |
| 240 | 235 | this.session = session; |
| 236 | + this.statement = statement; | |
| 241 | 237 | this.concurrentQueries = concurrentQueries; |
| 242 | 238 | this.stopped = stopped; |
| 243 | 239 | } |
added driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +128 −0
| @@ -0,0 +1,128 @@ | ||
| 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.policies; | |
| 17 | + | |
| 18 | +import java.util.List; | |
| 19 | +import java.util.Map; | |
| 20 | + | |
| 21 | +import com.google.common.collect.ImmutableList; | |
| 22 | +import com.google.common.collect.ImmutableMap; | |
| 23 | +import org.mockito.Mockito; | |
| 24 | +import org.scassandra.http.client.PrimingRequest; | |
| 25 | +import org.testng.annotations.BeforeClass; | |
| 26 | +import org.testng.annotations.BeforeMethod; | |
| 27 | + | |
| 28 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 29 | +import static org.mockito.Matchers.any; | |
| 30 | +import static org.mockito.Matchers.anyBoolean; | |
| 31 | +import static org.mockito.Matchers.anyInt; | |
| 32 | +import static org.mockito.Mockito.times; | |
| 33 | + | |
| 34 | +import com.datastax.driver.core.*; | |
| 35 | + | |
| 36 | +/** | |
| 37 | + * Base class for retry policy integration tests. | |
| 38 | + * | |
| 39 | + * We use SCassandra to easily simulate specific errors (unavailable, read timeout...) on nodes, | |
| 40 | + * and SortingLoadBalancingPolicy to get a predictable order of the query plan (always host1, host2, host3). | |
| 41 | + * | |
| 42 | + * Note that SCassandra only allows a limited number of test cases, for instance it always returns errors | |
| 43 | + * with receivedResponses = 0. If that becomes more finely tuneable in the future, we'll be able to add more | |
| 44 | + * tests in child classes. | |
| 45 | + */ | |
| 46 | +public class AbstractRetryPolicyIntegrationTest { | |
| 47 | + protected SCassandraCluster scassandras; | |
| 48 | + protected Cluster cluster = null; | |
| 49 | + protected Metrics.Errors errors; | |
| 50 | + protected Host host1, host2, host3; | |
| 51 | + protected Session session; | |
| 52 | + | |
| 53 | + protected RetryPolicy retryPolicy; | |
| 54 | + | |
| 55 | + protected AbstractRetryPolicyIntegrationTest(RetryPolicy retryPolicy) { | |
| 56 | + this.retryPolicy = Mockito.spy(retryPolicy); | |
| 57 | + } | |
| 58 | + | |
| 59 | + @BeforeClass(groups = "short") | |
| 60 | + public void beforeClass() { | |
| 61 | + scassandras = new SCassandraCluster(CCMBridge.IP_PREFIX, 3); | |
| 62 | + } | |
| 63 | + | |
| 64 | + @BeforeMethod(groups = "short") | |
| 65 | + public void beforeMethod() { | |
| 66 | + cluster = Cluster.builder() | |
| 67 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 68 | + .withRetryPolicy(retryPolicy) | |
| 69 | + .withLoadBalancingPolicy(new SortingLoadBalancingPolicy()) | |
| 70 | + .build(); | |
| 71 | + | |
| 72 | + session = cluster.connect(); | |
| 73 | + | |
| 74 | + host1 = TestUtils.findHost(cluster, 1); | |
| 75 | + host2 = TestUtils.findHost(cluster, 2); | |
| 76 | + host3 = TestUtils.findHost(cluster, 3); | |
| 77 | + | |
| 78 | + errors = cluster.getMetrics().getErrorMetrics(); | |
| 79 | + | |
| 80 | + Mockito.reset(retryPolicy); | |
| 81 | + scassandras.clearAllPrimes(); | |
| 82 | + scassandras.clearAllRecordedActivity(); | |
| 83 | + } | |
| 84 | + | |
| 85 | + protected void simulateError(int hostNumber, PrimingRequest.Result result) { | |
| 86 | + scassandras | |
| 87 | + .prime(hostNumber, PrimingRequest.queryBuilder() | |
| 88 | + .withQuery("mock query") | |
| 89 | + .withResult(result) | |
| 90 | + .build()); | |
| 91 | + } | |
| 92 | + | |
| 93 | + protected void simulateNormalResponse(int hostNumber) { | |
| 94 | + scassandras | |
| 95 | + .prime(hostNumber, PrimingRequest.queryBuilder() | |
| 96 | + .withQuery("mock query") | |
| 97 | + .withRows(row("result", "result1")) | |
| 98 | + .build()); | |
| 99 | + } | |
| 100 | + | |
| 101 | + private static List<Map<String, ?>> row(String key, String value) { | |
| 102 | + return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value)); | |
| 103 | + } | |
| 104 | + | |
| 105 | + protected ResultSet query() { | |
| 106 | + return session.execute("mock query"); | |
| 107 | + } | |
| 108 | + | |
| 109 | + protected void assertOnReadTimeoutWasCalled(int times) { | |
| 110 | + Mockito.verify(retryPolicy, times(times)).onReadTimeout( | |
| 111 | + any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyBoolean(), anyInt()); | |
| 112 | + | |
| 113 | + } | |
| 114 | + | |
| 115 | + protected void assertOnWriteTimeoutWasCalled(int times) { | |
| 116 | + Mockito.verify(retryPolicy, times(times)).onWriteTimeout( | |
| 117 | + any(Statement.class), any(ConsistencyLevel.class), any(WriteType.class), anyInt(), anyInt(), anyInt()); | |
| 118 | + } | |
| 119 | + | |
| 120 | + protected void assertOnUnavailableWasCalled(int times) { | |
| 121 | + Mockito.verify(retryPolicy, times(times)).onUnavailable( | |
| 122 | + any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt()); | |
| 123 | + } | |
| 124 | + | |
| 125 | + protected void assertQueried(int hostNumber, int times) { | |
| 126 | + assertThat(scassandras.retrieveQueries(hostNumber)).hasSize(times); | |
| 127 | + } | |
| 128 | +} |
deleted driver-core/src/test/java/com/datastax/driver/core/policies/AlwaysIgnoreRetryPolicy.java +0 −39
| @@ -1,39 +0,0 @@ | ||
| 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.policies; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | -import com.datastax.driver.core.Statement; | |
| 20 | -import com.datastax.driver.core.WriteType; | |
| 21 | - | |
| 22 | -public class AlwaysIgnoreRetryPolicy implements RetryPolicy { | |
| 23 | - | |
| 24 | - public static final AlwaysIgnoreRetryPolicy INSTANCE = new AlwaysIgnoreRetryPolicy(); | |
| 25 | - | |
| 26 | - private AlwaysIgnoreRetryPolicy() {} | |
| 27 | - | |
| 28 | - public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 29 | - return RetryDecision.ignore(); | |
| 30 | - } | |
| 31 | - | |
| 32 | - public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 33 | - return RetryDecision.ignore(); | |
| 34 | - } | |
| 35 | - | |
| 36 | - public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 37 | - return RetryDecision.ignore(); | |
| 38 | - } | |
| 39 | -} |
deleted driver-core/src/test/java/com/datastax/driver/core/policies/AlwaysRetryRetryPolicy.java +0 −39
| @@ -1,39 +0,0 @@ | ||
| 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.policies; | |
| 17 | - | |
| 18 | -import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | -import com.datastax.driver.core.Statement; | |
| 20 | -import com.datastax.driver.core.WriteType; | |
| 21 | - | |
| 22 | -public class AlwaysRetryRetryPolicy implements RetryPolicy { | |
| 23 | - | |
| 24 | - public static final AlwaysRetryRetryPolicy INSTANCE = new AlwaysRetryRetryPolicy(); | |
| 25 | - | |
| 26 | - private AlwaysRetryRetryPolicy() {} | |
| 27 | - | |
| 28 | - public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 29 | - return RetryDecision.retry(ConsistencyLevel.ONE); | |
| 30 | - } | |
| 31 | - | |
| 32 | - public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 33 | - return RetryDecision.retry(ConsistencyLevel.ONE); | |
| 34 | - } | |
| 35 | - | |
| 36 | - public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 37 | - return RetryDecision.retry(ConsistencyLevel.ONE); | |
| 38 | - } | |
| 39 | -} |
added driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +91 −0
| @@ -0,0 +1,91 @@ | ||
| 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.policies; | |
| 17 | + | |
| 18 | +import org.testng.annotations.Test; | |
| 19 | + | |
| 20 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 21 | +import static org.assertj.core.api.Assertions.fail; | |
| 22 | +import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout; | |
| 23 | +import static org.scassandra.http.client.PrimingRequest.Result.unavailable; | |
| 24 | + | |
| 25 | +import com.datastax.driver.core.ConsistencyLevel; | |
| 26 | +import com.datastax.driver.core.ResultSet; | |
| 27 | +import com.datastax.driver.core.Statement; | |
| 28 | +import com.datastax.driver.core.WriteType; | |
| 29 | +import com.datastax.driver.core.exceptions.UnavailableException; | |
| 30 | + | |
| 31 | +/** | |
| 32 | + * Integration test with a custom implementation, to test retry and ignore decisions. | |
| 33 | + */ | |
| 34 | +public class CustomRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { | |
| 35 | + public CustomRetryPolicyIntegrationTest() { | |
| 36 | + super(new CustomRetryPolicy()); | |
| 37 | + } | |
| 38 | + | |
| 39 | + @Test(groups = "short") | |
| 40 | + public void should_ignore_read_timeout() { | |
| 41 | + simulateError(1, read_request_timeout); | |
| 42 | + | |
| 43 | + ResultSet rs = query(); | |
| 44 | + assertThat(rs.iterator().hasNext()).isFalse(); // ignore decisions produce empty result sets | |
| 45 | + | |
| 46 | + assertOnReadTimeoutWasCalled(1); | |
| 47 | + assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0); | |
| 48 | + assertQueried(1, 1); | |
| 49 | + assertQueried(2, 0); | |
| 50 | + assertQueried(3, 0); | |
| 51 | + } | |
| 52 | + | |
| 53 | + @Test(groups = "short") | |
| 54 | + public void should_retry_once_on_same_host_on_unavailable() { | |
| 55 | + simulateError(1, unavailable); | |
| 56 | + | |
| 57 | + try { | |
| 58 | + query(); | |
| 59 | + fail("expected an UnavailableException"); | |
| 60 | + } catch (UnavailableException e) {/*expected*/} | |
| 61 | + | |
| 62 | + assertOnUnavailableWasCalled(2); | |
| 63 | + assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); | |
| 64 | + assertQueried(1, 2); | |
| 65 | + assertQueried(2, 0); | |
| 66 | + assertQueried(3, 0); | |
| 67 | + } | |
| 68 | + | |
| 69 | + /** | |
| 70 | + * Ignores read and write timeouts, and retries at most once on unavailable. | |
| 71 | + */ | |
| 72 | + static class CustomRetryPolicy implements RetryPolicy { | |
| 73 | + | |
| 74 | + @Override | |
| 75 | + public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 76 | + return RetryDecision.ignore(); | |
| 77 | + } | |
| 78 | + | |
| 79 | + @Override | |
| 80 | + public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 81 | + return RetryDecision.ignore(); | |
| 82 | + } | |
| 83 | + | |
| 84 | + @Override | |
| 85 | + public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 86 | + return (nbRetry == 0) | |
| 87 | + ? RetryDecision.retry(cl) | |
| 88 | + : RetryDecision.rethrow(); | |
| 89 | + } | |
| 90 | + } | |
| 91 | +} |
added driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +97 −0
| @@ -0,0 +1,97 @@ | ||
| 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.policies; | |
| 17 | + | |
| 18 | +import org.testng.annotations.Test; | |
| 19 | + | |
| 20 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 21 | +import static org.assertj.core.api.Assertions.fail; | |
| 22 | +import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout; | |
| 23 | +import static org.scassandra.http.client.PrimingRequest.Result.unavailable; | |
| 24 | +import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout; | |
| 25 | + | |
| 26 | +import com.datastax.driver.core.exceptions.ReadTimeoutException; | |
| 27 | +import com.datastax.driver.core.exceptions.UnavailableException; | |
| 28 | +import com.datastax.driver.core.exceptions.WriteTimeoutException; | |
| 29 | + | |
| 30 | +public class DefaultRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { | |
| 31 | + public DefaultRetryPolicyIntegrationTest() { | |
| 32 | + super(DefaultRetryPolicy.INSTANCE); | |
| 33 | + } | |
| 34 | + | |
| 35 | + @Test(groups = "short") | |
| 36 | + public void should_rethrow_on_read_timeout_with_0_receivedResponses() { | |
| 37 | + simulateError(1, read_request_timeout); | |
| 38 | + | |
| 39 | + try { | |
| 40 | + query(); | |
| 41 | + fail("expected a ReadTimeoutException"); | |
| 42 | + } catch (ReadTimeoutException e) {/*expected*/ } | |
| 43 | + | |
| 44 | + assertOnReadTimeoutWasCalled(1); | |
| 45 | + assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0); | |
| 46 | + assertQueried(1, 1); | |
| 47 | + assertQueried(2, 0); | |
| 48 | + assertQueried(3, 0); | |
| 49 | + } | |
| 50 | + | |
| 51 | + @Test(groups = "short") | |
| 52 | + public void should_rethrow_on_write_timeout_with_SIMPLE_write_type() { | |
| 53 | + simulateError(1, write_request_timeout); | |
| 54 | + | |
| 55 | + try { | |
| 56 | + query(); | |
| 57 | + fail("expected a WriteTimeoutException"); | |
| 58 | + } catch (WriteTimeoutException e) {/*expected*/} | |
| 59 | + | |
| 60 | + assertOnWriteTimeoutWasCalled(1); | |
| 61 | + assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0); | |
| 62 | + assertQueried(1, 1); | |
| 63 | + assertQueried(2, 0); | |
| 64 | + assertQueried(3, 0); | |
| 65 | + } | |
| 66 | + | |
| 67 | + @Test(groups = "short") | |
| 68 | + public void should_try_next_host_on_first_unavailable() { | |
| 69 | + simulateError(1, unavailable); | |
| 70 | + simulateNormalResponse(2); | |
| 71 | + | |
| 72 | + query(); | |
| 73 | + | |
| 74 | + assertOnUnavailableWasCalled(1); | |
| 75 | + assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); | |
| 76 | + assertQueried(1, 1); | |
| 77 | + assertQueried(2, 1); | |
| 78 | + assertQueried(3, 0); | |
| 79 | + } | |
| 80 | + | |
| 81 | + @Test(groups = "short") | |
| 82 | + public void should_rethrow_on_second_unavailable() { | |
| 83 | + simulateError(1, unavailable); | |
| 84 | + simulateError(2, unavailable); | |
| 85 | + | |
| 86 | + try { | |
| 87 | + query(); | |
| 88 | + fail("expected an UnavailableException"); | |
| 89 | + } catch (UnavailableException e) {/*expected*/} | |
| 90 | + | |
| 91 | + assertOnUnavailableWasCalled(2); | |
| 92 | + assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); | |
| 93 | + assertQueried(1, 1); | |
| 94 | + assertQueried(2, 1); | |
| 95 | + assertQueried(3, 0); | |
| 96 | + } | |
| 97 | +} |
added driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +109 −0
| @@ -0,0 +1,109 @@ | ||
| 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.policies; | |
| 17 | + | |
| 18 | +import com.google.common.base.Objects; | |
| 19 | +import org.mockito.Mockito; | |
| 20 | +import org.mockito.verification.VerificationMode; | |
| 21 | +import org.testng.annotations.Test; | |
| 22 | + | |
| 23 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 24 | +import static org.mockito.Matchers.any; | |
| 25 | +import static org.mockito.Matchers.anyInt; | |
| 26 | +import static org.mockito.Mockito.never; | |
| 27 | +import static org.mockito.Mockito.times; | |
| 28 | + | |
| 29 | +import com.datastax.driver.core.*; | |
| 30 | + | |
| 31 | +import static com.datastax.driver.core.ConsistencyLevel.ALL; | |
| 32 | +import static com.datastax.driver.core.ConsistencyLevel.ONE; | |
| 33 | +import static com.datastax.driver.core.ConsistencyLevel.QUORUM; | |
| 34 | +import static com.datastax.driver.core.ConsistencyLevel.TWO; | |
| 35 | + | |
| 36 | +/** | |
| 37 | + * Note: we can't extend {@link AbstractRetryPolicyIntegrationTest} here, because SCassandra doesn't allow custom values for | |
| 38 | + * receivedResponses in primed responses. | |
| 39 | + * If that becomes possible in the future, we could refactor this test. | |
| 40 | + */ | |
| 41 | +public class DowngradingConsistencyRetryPolicyIntegrationTest { | |
| 42 | + | |
| 43 | + @Test(groups = "long") | |
| 44 | + public void should_downgrade_if_not_enough_replicas_for_requested_CL() { | |
| 45 | + CCMBridge ccm = null; | |
| 46 | + Cluster cluster = null; | |
| 47 | + try { | |
| 48 | + // 3-node cluster, keyspace with RF = 3 | |
| 49 | + ccm = CCMBridge.create(this.getClass().getName(), 3); | |
| 50 | + cluster = Cluster.builder() | |
| 51 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 52 | + .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE)) | |
| 53 | + .build(); | |
| 54 | + Session session = cluster.connect(); | |
| 55 | + | |
| 56 | + session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}"); | |
| 57 | + session.execute("CREATE TABLE test.foo(k int primary key)"); | |
| 58 | + session.execute("INSERT INTO test.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 | + ccm.stop(1); | |
| 66 | + ccm.waitForDown(1); | |
| 67 | + // Two replicas remaining: should downgrade to 2 when CL > 2 | |
| 68 | + checkAchievedConsistency(ALL, TWO, session); | |
| 69 | + checkAchievedConsistency(QUORUM, QUORUM, session); // since RF = 3, quorum is still achievable with two nodes | |
| 70 | + checkAchievedConsistency(TWO, TWO, session); | |
| 71 | + checkAchievedConsistency(ONE, ONE, session); | |
| 72 | + | |
| 73 | + ccm.stop(2); | |
| 74 | + ccm.waitForDown(2); | |
| 75 | + // One replica remaining: should downgrade to 1 when CL > 1 | |
| 76 | + checkAchievedConsistency(ALL, ONE, session); | |
| 77 | + checkAchievedConsistency(QUORUM, ONE, session); | |
| 78 | + checkAchievedConsistency(TWO, ONE, session); | |
| 79 | + checkAchievedConsistency(ONE, ONE, session); | |
| 80 | + | |
| 81 | + } finally { | |
| 82 | + if (cluster != null) | |
| 83 | + cluster.close(); | |
| 84 | + if (ccm != null) | |
| 85 | + ccm.remove(); | |
| 86 | + } | |
| 87 | + } | |
| 88 | + | |
| 89 | + private void checkAchievedConsistency(ConsistencyLevel requested, ConsistencyLevel expected, Session session) { | |
| 90 | + RetryPolicy retryPolicy = session.getCluster().getConfiguration().getPolicies().getRetryPolicy(); | |
| 91 | + Mockito.reset(retryPolicy); | |
| 92 | + | |
| 93 | + Statement s = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0") | |
| 94 | + .setConsistencyLevel(requested); | |
| 95 | + | |
| 96 | + ResultSet rs = session.execute(s); | |
| 97 | + | |
| 98 | + ConsistencyLevel achieved = rs.getExecutionInfo().getAchievedConsistencyLevel(); | |
| 99 | + // ExecutionInfo returns null when the requested level was met. | |
| 100 | + ConsistencyLevel actual = Objects.firstNonNull(achieved, requested); | |
| 101 | + | |
| 102 | + assertThat(actual).isEqualTo(expected); | |
| 103 | + | |
| 104 | + // If the level was downgraded the policy should have been invoked | |
| 105 | + VerificationMode expectedCallsToPolicy = (expected == requested) ? never() : times(1); | |
| 106 | + Mockito.verify(retryPolicy, expectedCallsToPolicy).onUnavailable( | |
| 107 | + any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt()); | |
| 108 | + } | |
| 109 | +} |
added driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +82 −0
| @@ -0,0 +1,82 @@ | ||
| 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.policies; | |
| 17 | + | |
| 18 | +import org.testng.annotations.Test; | |
| 19 | + | |
| 20 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 21 | +import static org.assertj.core.api.Assertions.fail; | |
| 22 | +import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout; | |
| 23 | +import static org.scassandra.http.client.PrimingRequest.Result.unavailable; | |
| 24 | +import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout; | |
| 25 | + | |
| 26 | +import com.datastax.driver.core.exceptions.ReadTimeoutException; | |
| 27 | +import com.datastax.driver.core.exceptions.UnavailableException; | |
| 28 | +import com.datastax.driver.core.exceptions.WriteTimeoutException; | |
| 29 | + | |
| 30 | +public class FallthroughRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { | |
| 31 | + public FallthroughRetryPolicyIntegrationTest() { | |
| 32 | + super(FallthroughRetryPolicy.INSTANCE); | |
| 33 | + } | |
| 34 | + | |
| 35 | + @Test(groups = "short") | |
| 36 | + public void should_rethrow_on_read_timeout_with_0_receivedResponses() { | |
| 37 | + simulateError(1, read_request_timeout); | |
| 38 | + | |
| 39 | + try { | |
| 40 | + query(); | |
| 41 | + fail("expected a ReadTimeoutException"); | |
| 42 | + } catch (ReadTimeoutException e) {/*expected*/ } | |
| 43 | + | |
| 44 | + assertOnReadTimeoutWasCalled(1); | |
| 45 | + assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0); | |
| 46 | + assertQueried(1, 1); | |
| 47 | + assertQueried(2, 0); | |
| 48 | + assertQueried(3, 0); | |
| 49 | + } | |
| 50 | + | |
| 51 | + @Test(groups = "short") | |
| 52 | + public void should_rethrow_on_write_timeout_with_SIMPLE_write_type() { | |
| 53 | + simulateError(1, write_request_timeout); | |
| 54 | + | |
| 55 | + try { | |
| 56 | + query(); | |
| 57 | + fail("expected a WriteTimeoutException"); | |
| 58 | + } catch (WriteTimeoutException e) {/*expected*/} | |
| 59 | + | |
| 60 | + assertOnWriteTimeoutWasCalled(1); | |
| 61 | + assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0); | |
| 62 | + assertQueried(1, 1); | |
| 63 | + assertQueried(2, 0); | |
| 64 | + assertQueried(3, 0); | |
| 65 | + } | |
| 66 | + | |
| 67 | + @Test(groups = "short") | |
| 68 | + public void should_rethrow_on_unavailable() { | |
| 69 | + simulateError(1, unavailable); | |
| 70 | + | |
| 71 | + try { | |
| 72 | + query(); | |
| 73 | + fail("expected an UnavailableException"); | |
| 74 | + } catch (UnavailableException e) {/*expected*/} | |
| 75 | + | |
| 76 | + assertOnUnavailableWasCalled(1); | |
| 77 | + assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(0); | |
| 78 | + assertQueried(1, 1); | |
| 79 | + assertQueried(2, 0); | |
| 80 | + assertQueried(3, 0); | |
| 81 | + } | |
| 82 | +} |
added driver-core/src/test/java/com/datastax/driver/core/policies/RetryDecisionTest.java +65 −0
| @@ -0,0 +1,65 @@ | ||
| 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.policies; | |
| 17 | + | |
| 18 | +import org.testng.annotations.Test; | |
| 19 | + | |
| 20 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 21 | + | |
| 22 | +import com.datastax.driver.core.policies.RetryPolicy.RetryDecision; | |
| 23 | + | |
| 24 | +import static com.datastax.driver.core.ConsistencyLevel.ONE; | |
| 25 | +import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.IGNORE; | |
| 26 | +import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.RETHROW; | |
| 27 | +import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type.RETRY; | |
| 28 | + | |
| 29 | +public class RetryDecisionTest { | |
| 30 | + | |
| 31 | + @Test(groups = "unit") | |
| 32 | + public void should_expose_decision_properties() throws Throwable { | |
| 33 | + RetryDecision retryAtOne = RetryDecision.retry(ONE); | |
| 34 | + assertThat(retryAtOne.getType()) | |
| 35 | + .isEqualTo(RETRY); | |
| 36 | + assertThat(retryAtOne.getRetryConsistencyLevel()) | |
| 37 | + .isEqualTo(ONE); | |
| 38 | + assertThat(retryAtOne.isRetryCurrent()) | |
| 39 | + .isTrue(); | |
| 40 | + assertThat(retryAtOne.toString()) | |
| 41 | + .isEqualTo("Retry at ONE on same host."); | |
| 42 | + | |
| 43 | + RetryDecision tryNextAtOne = RetryDecision.tryNextHost(ONE); | |
| 44 | + assertThat(tryNextAtOne.getType()) | |
| 45 | + .isEqualTo(RETRY); | |
| 46 | + assertThat(tryNextAtOne.getRetryConsistencyLevel()) | |
| 47 | + .isEqualTo(ONE); | |
| 48 | + assertThat(tryNextAtOne.isRetryCurrent()) | |
| 49 | + .isFalse(); | |
| 50 | + assertThat(tryNextAtOne.toString()) | |
| 51 | + .isEqualTo("Retry at ONE on next host."); | |
| 52 | + | |
| 53 | + RetryDecision rethrow = RetryDecision.rethrow(); | |
| 54 | + assertThat(rethrow.getType()) | |
| 55 | + .isEqualTo(RETHROW); | |
| 56 | + assertThat(rethrow.toString()) | |
| 57 | + .isEqualTo("Rethrow"); | |
| 58 | + | |
| 59 | + RetryDecision ignore = RetryDecision.ignore(); | |
| 60 | + assertThat(ignore.getType()) | |
| 61 | + .isEqualTo(IGNORE); | |
| 62 | + assertThat(ignore.toString()) | |
| 63 | + .isEqualTo("Ignore"); | |
| 64 | + } | |
| 65 | +} |
modified upgrade_guide/README.md +25 −3
| @@ -3,6 +3,18 @@ | ||
| 3 | 3 | The purpose of this guide is to detail changes made by successive |
| 4 | 4 | versions of the Java driver. |
| 5 | 5 | |
| 6 | +### 2.1.7 | |
| 7 | + | |
| 8 | +1. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable | |
| 9 | + exception received from a request. The new behaviour will cause the driver to | |
| 10 | + process a Retry on a different node at most once, otherwise an exception will | |
| 11 | + be thrown. This change makes sense in the case where the node tried initially | |
| 12 | + for the request happens to be isolated from the rest of the cluster (e.g. | |
| 13 | + because of a network partition) but can still answer to the client normally. | |
| 14 | + In this case, trying another node has a chance of success. | |
| 15 | + The previous behaviour was to always throw an exception. | |
| 16 | + | |
| 17 | + | |
| 6 | 18 | ### 2.1.6 |
| 7 | 19 | |
| 8 | 20 | See [2.0.10](20x-to-2010). |
| @@ -109,6 +121,17 @@ | ||
| 109 | 121 | (`cluster.getConfiguration().getProtocolOptions().getProtocolVersion()`). |
| 110 | 122 | |
| 111 | 123 | |
| 124 | +### 2.0.11 | |
| 125 | + | |
| 126 | +1. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable | |
| 127 | + exception received from a request. The new behaviour will cause the driver to | |
| 128 | + process a Retry on a different node at most once, otherwise an exception will | |
| 129 | + be thrown. This change makes sense in the case where the node tried initially | |
| 130 | + for the request happens to be isolated from the rest of the cluster (e.g. | |
| 131 | + because of a network partition) but can still answer to the client normally. | |
| 132 | + In this case, trying another node has a chance of success. | |
| 133 | + The previous behaviour was to always throw an exception. | |
| 134 | + | |
| 112 | 135 | ### 2.0.x to 2.0.10 |
| 113 | 136 | |
| 114 | 137 | We try to avoid breaking changes within a branch (2.0.x to 2.0.y), but |
| @@ -209,7 +232,6 @@ | ||
| 209 | 232 | This means for instance that `eq("x", raw(foo))` will output `x = foo`, |
| 210 | 233 | not `x = 'foo'` (you don't need the raw method to output the latter string). |
| 211 | 234 | |
| 212 | - | |
| 213 | 235 | 9. The `QueryBuilder` will now sometimes use the new ability to send value as |
| 214 | 236 | bytes instead of serializing everything to string. In general the QueryBuilder |
| 215 | 237 | will do the right thing, but if you were calling the `getQueryString()` method |
| @@ -307,8 +329,8 @@ | ||
| 307 | 329 | ``` |
| 308 | 330 | |
| 309 | 331 | 3. SELECT queries are now "paged" under the hood. In other words, if a query |
| 310 | - yields a very large result, only the beginning of the `ResultSet` will be fetch | |
| 311 | - initially, the rest being fetch "on-demand". In practice, this means that: | |
| 332 | + yields a very large result, only the beginning of the `ResultSet` will be fetched | |
| 333 | + initially, the rest being fetched "on-demand". In practice, this means that: | |
| 312 | 334 | |
| 313 | 335 | ```java |
| 314 | 336 | for (Row r : session.execute("SELECT * FROM mytable")) |