Elffuss BraidHub

kikocis/java-driver public

JAVA-1055: Add ErrorAware load balancing policy
Changeseta3a881df6a44c073c5734f3eaa01ff69301b967e67559962370f4ba23b06a897
AuthorKevin Gallardo <kevin.gallardo@datastax.com> · 2016-07-07 17:13 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-07-27 10:01 -07:00
Parentsbd5e396c0627

Browse the files at this changeset

5 files changed

modified changelog/README.md +1 −0
@@ -13,6 +13,7 @@
1313 - [new feature] JAVA-541: Add polymorphism support to object mapper.
1414 - [new feature] JAVA-636: Allow @Column annotations on getters/setters as well as fields.
1515 - [new feature] JAVA-984: Allow non-void setters in object mapping.
16+- [new feature] JAVA-1055: Add ErrorAware load balancing policy.
1617
1718 Merged from 3.0.x branch:
1819
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +8 −9
@@ -471,7 +471,7 @@
471471 * Registers the provided tracker to be updated with hosts read
472472 * latencies.
473473 * <p/>
474- * Registering the same listener multiple times is a no-op.
474+ * Registering the same tracker multiple times is a no-op.
475475 * <p/>
476476 * Beware that the registered tracker's
477477 * {@link LatencyTracker#update(Host, Statement, Exception, long) update}
@@ -490,7 +490,7 @@
490490 */
491491 public Cluster register(LatencyTracker tracker) {
492492 checkNotClosed(manager);
493- boolean added = manager.trackers.add(tracker);
493+ boolean added = manager.latencyTrackers.add(tracker);
494494 if (added)
495495 tracker.onRegister(this);
496496 return this;
@@ -508,7 +508,7 @@
508508 */
509509 public Cluster unregister(LatencyTracker tracker) {
510510 checkNotClosed(manager);
511- boolean removed = manager.trackers.remove(tracker);
511+ boolean removed = manager.latencyTrackers.remove(tracker);
512512 if (removed)
513513 tracker.onUnregister(this);
514514 return this;
@@ -1341,7 +1341,7 @@
13411341 ConcurrentMap<MD5Digest, PreparedStatement> preparedQueries;
13421342
13431343 final Set<Host.StateListener> listeners;
1344- final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
1344+ final Set<LatencyTracker> latencyTrackers = new CopyOnWriteArraySet<LatencyTracker>();
13451345 final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
13461346
13471347 EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer;
@@ -1484,11 +1484,10 @@
14841484 configuration.getPolicies().getRetryPolicy().init(Cluster.this);
14851485 reconnectionPolicy().init(Cluster.this);
14861486 configuration.getPolicies().getAddressTranslator().init(Cluster.this);
1487- for (LatencyTracker tracker : trackers)
1487+ for (LatencyTracker tracker : latencyTrackers)
14881488 tracker.onRegister(Cluster.this);
14891489 for (Host.StateListener listener : listeners)
14901490 listener.onRegister(Cluster.this);
1491-
14921491 for (Host host : removedContactPointHosts) {
14931492 loadBalancingPolicy().onRemove(host);
14941493 for (Host.StateListener listener : listeners)
@@ -1592,8 +1591,8 @@
15921591 return sessions.remove(session);
15931592 }
15941593
1595- void reportLatency(Host host, Statement statement, Exception exception, long latencyNanos) {
1596- for (LatencyTracker tracker : trackers) {
1594+ void reportQuery(Host host, Statement statement, Exception exception, long latencyNanos) {
1595+ for (LatencyTracker tracker : latencyTrackers) {
15971596 tracker.update(host, statement, exception, latencyNanos);
15981597 }
15991598 }
@@ -1634,7 +1633,7 @@
16341633 configuration.getPolicies().getRetryPolicy().close();
16351634 reconnectionPolicy().close();
16361635 configuration.getPolicies().getAddressTranslator().close();
1637- for (LatencyTracker tracker : trackers)
1636+ for (LatencyTracker tracker : latencyTrackers)
16381637 tracker.onUnregister(Cluster.this);
16391638 for (Host.StateListener listener : listeners)
16401639 listener.onUnregister(Cluster.this);
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +5 −4
@@ -638,8 +638,9 @@
638638 exceptionToReport = e;
639639 setFinalException(connection, e);
640640 } finally {
641- if (queriedHost != null && statement != Statement.DEFAULT)
642- manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency);
641+ if (queriedHost != null && statement != Statement.DEFAULT) {
642+ manager.cluster.manager.reportQuery(queriedHost, statement, exceptionToReport, latency);
643+ }
643644 }
644645 }
645646
@@ -746,7 +747,7 @@
746747 setFinalException(null, new DriverInternalError("An unexpected error happened while handling exception " + exception, e));
747748 } finally {
748749 if (queriedHost != null && statement != Statement.DEFAULT)
749- manager.cluster.manager.reportLatency(queriedHost, statement, exception, latency);
750+ manager.cluster.manager.reportQuery(queriedHost, statement, exception, latency);
750751 }
751752 }
752753
@@ -774,7 +775,7 @@
774775 setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e));
775776 } finally {
776777 if (queriedHost != null && statement != Statement.DEFAULT)
777- manager.cluster.manager.reportLatency(queriedHost, statement, timeoutException, latency);
778+ manager.cluster.manager.reportQuery(queriedHost, statement, timeoutException, latency);
778779 }
779780 return true;
780781 }
added driver-core/src/main/java/com/datastax/driver/core/policies/ErrorAwarePolicy.java +364 −0
@@ -0,0 +1,364 @@
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.*;
19+import com.datastax.driver.core.exceptions.*;
20+import com.google.common.annotations.Beta;
21+import com.google.common.annotations.VisibleForTesting;
22+import com.google.common.collect.AbstractIterator;
23+import com.google.common.collect.ImmutableList;
24+import org.slf4j.Logger;
25+import org.slf4j.LoggerFactory;
26+
27+import java.util.Collection;
28+import java.util.Iterator;
29+import java.util.List;
30+import java.util.concurrent.ConcurrentHashMap;
31+import java.util.concurrent.ConcurrentMap;
32+import java.util.concurrent.TimeUnit;
33+
34+import static java.util.concurrent.TimeUnit.MINUTES;
35+import static java.util.concurrent.TimeUnit.NANOSECONDS;
36+
37+/**
38+ * Chainable load balancing policy that filters out hosts based on their error rates.
39+ * <p/>
40+ * When creating a query plan, this policy gathers a list of candidate hosts from its child policy; for each candidate
41+ * host, it then determines whether it should be included into or excluded from the final query plan, based on its
42+ * current error rate (measured over the last minute, with a 5-second granularity).
43+ * <p/>
44+ * Note that the policy should not blindly count all errors in its measurements: some type of errors (e.g. CQL syntax
45+ * errors) can originate from the client and occur on all hosts, therefore they should not count towards the exclusion
46+ * threshold or all hosts could become excluded. You can provide your own {@link ErrorFilter} to customize that logic.
47+ * <p/>
48+ * The policy follows the builder pattern to be created, the {@link Builder} class can be created with
49+ * {@link #builder} method.
50+ * <p/>
51+ * This policy is currently in BETA mode and its behavior might be changing throughout different driver versions.
52+ */
53+@Beta
54+public class ErrorAwarePolicy implements ChainableLoadBalancingPolicy {
55+
56+ private static final Logger logger = LoggerFactory.getLogger(ErrorAwarePolicy.class);
57+
58+ private final LoadBalancingPolicy childPolicy;
59+
60+ private final long retryPeriodNanos;
61+
62+ PerHostErrorTracker errorTracker;
63+
64+ private ErrorAwarePolicy(Builder builder) {
65+ this.childPolicy = builder.childPolicy;
66+ this.retryPeriodNanos = builder.retryPeriodNanos;
67+ this.errorTracker = new PerHostErrorTracker(builder.maxErrorsPerMinute, builder.errorFilter, builder.clock);
68+ }
69+
70+ @Override
71+ public LoadBalancingPolicy getChildPolicy() {
72+ return childPolicy;
73+ }
74+
75+ @Override
76+ public void init(Cluster cluster, Collection<Host> hosts) {
77+ childPolicy.init(cluster, hosts);
78+ cluster.register(this.errorTracker);
79+ }
80+
81+ @Override
82+ public HostDistance distance(Host host) {
83+ return childPolicy.distance(host);
84+ }
85+
86+ @Override
87+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
88+ final Iterator<Host> childQueryPlan = childPolicy.newQueryPlan(loggedKeyspace, statement);
89+
90+ return new AbstractIterator<Host>() {
91+
92+ @Override
93+ protected Host computeNext() {
94+ while (childQueryPlan.hasNext()) {
95+ Host host = childQueryPlan.next();
96+ if (!errorTracker.isExcluded(host)) {
97+ return host;
98+ }
99+ }
100+ return endOfData();
101+ }
102+ };
103+ }
104+
105+ @Override
106+ public void onAdd(Host host) {
107+ childPolicy.onAdd(host);
108+ }
109+
110+ @Override
111+ public void onUp(Host host) {
112+ childPolicy.onUp(host);
113+ }
114+
115+ @Override
116+ public void onDown(Host host) {
117+ childPolicy.onDown(host);
118+ }
119+
120+ @Override
121+ public void onRemove(Host host) {
122+ childPolicy.onRemove(host);
123+ }
124+
125+ /**
126+ * Creates a new error aware policy builder given the child policy
127+ * that the resulting policy should wrap.
128+ *
129+ * @param childPolicy the load balancing policy to wrap with error
130+ * awareness.
131+ * @return the created builder.
132+ */
133+ public static Builder builder(LoadBalancingPolicy childPolicy) {
134+ return new Builder(childPolicy);
135+ }
136+
137+ @Override
138+ public void close() {
139+ childPolicy.close();
140+ }
141+
142+ /**
143+ * Utility class to create a {@link ErrorAwarePolicy}.
144+ */
145+ public static class Builder {
146+ final LoadBalancingPolicy childPolicy;
147+
148+ private int maxErrorsPerMinute = 1;
149+ private long retryPeriodNanos = NANOSECONDS.convert(2, MINUTES);
150+ private Clock clock = Clock.DEFAULT;
151+
152+ private ErrorFilter errorFilter = new DefaultErrorFilter();
153+
154+ /**
155+ * Creates a {@link Builder} instance.
156+ *
157+ * @param childPolicy the load balancing policy to wrap with error
158+ * awareness.
159+ */
160+ public Builder(LoadBalancingPolicy childPolicy) {
161+ this.childPolicy = childPolicy;
162+ }
163+
164+ /**
165+ * Defines the maximum number of errors allowed per minute for each host.
166+ * <p/>
167+ * The policy keeps track of the number of errors on each host (filtered by
168+ * {@link #withErrorsFilter(ErrorFilter)}) over a sliding 1-minute window. If a host had more than this number
169+ * of errors, it will be excluded from the query plan for the duration defined by
170+ * {@link #withRetryPeriod(long, TimeUnit)}.
171+ * <p/>
172+ * Default value for the threshold is 1.
173+ *
174+ * @param maxErrorsPerMinute the number.
175+ * @return this {@link Builder} instance, for method chaining.
176+ */
177+ public Builder withMaxErrorsPerMinute(int maxErrorsPerMinute) {
178+ this.maxErrorsPerMinute = maxErrorsPerMinute;
179+ return this;
180+ }
181+
182+ /**
183+ * Defines the time during which a host is excluded by the policy once it has exceeded
184+ * {@link #withMaxErrorsPerMinute(int)}.
185+ * <p/>
186+ * Default value for the retry period is 2 minutes.
187+ *
188+ * @param retryPeriod the period of exclusion for a host.
189+ * @param retryPeriodTimeUnit the time unit for the retry period.
190+ * @return this {@link Builder} instance, for method chaining.
191+ */
192+ public Builder withRetryPeriod(long retryPeriod, TimeUnit retryPeriodTimeUnit) {
193+ this.retryPeriodNanos = retryPeriodTimeUnit.toNanos(retryPeriod);
194+ return this;
195+ }
196+
197+ /**
198+ * Provides a filter that will decide which errors are counted towards {@link #withMaxErrorsPerMinute(int)}.
199+ * <p/>
200+ * The default implementation will exclude from the error counting, the following exception types:
201+ * <ul>
202+ * <li>{@link QueryConsistencyException} and {@link UnavailableException}: the assumption is that these errors
203+ * are most often caused by other replicas being unavailable, not by something wrong on the coordinator;</li>
204+ * <li>{@link InvalidQueryException}, {@link AlreadyExistsException}, {@link SyntaxError}: these are likely
205+ * caused by a bad query in client code, that will fail on all hosts. Excluding hosts could lead to complete
206+ * loss of connectivity, rather the solution is to fix the query;</li>
207+ * <li>{@link FunctionExecutionException}: similarly, this is caused by a bad function definition and likely to
208+ * fail on all hosts.</li>
209+ * </ul>
210+ *
211+ * @param errorFilter the filter class that the policy will use.
212+ * @return this {@link Builder} instance, for method chaining.
213+ */
214+ public Builder withErrorsFilter(ErrorFilter errorFilter) {
215+ this.errorFilter = errorFilter;
216+ return this;
217+ }
218+
219+ @VisibleForTesting
220+ Builder withClock(Clock clock) {
221+ this.clock = clock;
222+ return this;
223+ }
224+
225+ /**
226+ * Creates the {@link ErrorAwarePolicy} instance.
227+ *
228+ * @return the newly created {@link ErrorAwarePolicy}.
229+ */
230+ public ErrorAwarePolicy build() {
231+ return new ErrorAwarePolicy(this);
232+ }
233+ }
234+
235+ class PerHostErrorTracker implements LatencyTracker {
236+
237+ private final int maxErrorsPerMinute;
238+ private final ErrorFilter errorFilter;
239+ private final Clock clock;
240+ private final ConcurrentMap<Host, RollingCount> hostsCounts = new ConcurrentHashMap<Host, RollingCount>();
241+ private final ConcurrentMap<Host, Long> exclusionTimes = new ConcurrentHashMap<Host, Long>();
242+
243+ PerHostErrorTracker(int maxErrorsPerMinute, ErrorFilter errorFilter, Clock clock) {
244+ this.maxErrorsPerMinute = maxErrorsPerMinute;
245+ this.errorFilter = errorFilter;
246+ this.clock = clock;
247+ }
248+
249+ @Override
250+ public void update(Host host, Statement statement, Exception exception, long newLatencyNanos) {
251+ if (exception == null) {
252+ return;
253+ }
254+ if (!errorFilter.shouldConsiderError(exception, host, statement)) {
255+ return;
256+ }
257+ RollingCount hostCount = getOrCreateCount(host);
258+ hostCount.increment();
259+ }
260+
261+ boolean isExcluded(Host host) {
262+ Long excludedTime = exclusionTimes.get(host);
263+ boolean expired = excludedTime != null && clock.nanoTime() - excludedTime >= retryPeriodNanos;
264+ if (excludedTime == null || expired) {
265+ if (maybeExcludeNow(host, excludedTime)) {
266+ return true;
267+ }
268+ if (expired) {
269+ // Cleanup, but make sure we don't overwrite if another thread just set it
270+ exclusionTimes.remove(host, excludedTime);
271+ }
272+ return false;
273+ } else { // host is already excluded
274+ return true;
275+ }
276+ }
277+
278+ // Exclude if we're over the threshold
279+ private boolean maybeExcludeNow(Host host, Long previousTime) {
280+ RollingCount rollingCount = getOrCreateCount(host);
281+ long count = rollingCount.get();
282+ if (count > maxErrorsPerMinute) {
283+ excludeNow(host, count, previousTime);
284+ return true;
285+ } else {
286+ return false;
287+ }
288+ }
289+
290+ // Set the exclusion time to now, handling potential races
291+ private void excludeNow(Host host, long count, Long previousTime) {
292+ long now = clock.nanoTime();
293+ boolean didNotRace = (previousTime == null)
294+ ? exclusionTimes.putIfAbsent(host, now) == null
295+ : exclusionTimes.replace(host, previousTime, now);
296+
297+ if (didNotRace && logger.isDebugEnabled()) {
298+ logger.debug(String.format("Host %s encountered %d errors in the last minute, which is more " +
299+ "than the maximum allowed (%d). It will be excluded from query plans for the " +
300+ "next %d nanoseconds.",
301+ host, count, maxErrorsPerMinute, retryPeriodNanos));
302+ }
303+ }
304+
305+ private RollingCount getOrCreateCount(Host host) {
306+ RollingCount hostCount = hostsCounts.get(host);
307+ if (hostCount == null) {
308+ RollingCount tmp = new RollingCount(clock);
309+ hostCount = hostsCounts.putIfAbsent(host, tmp);
310+ if (hostCount == null)
311+ hostCount = tmp;
312+ }
313+ return hostCount;
314+ }
315+
316+ @Override
317+ public void onRegister(Cluster cluster) {
318+ // nothing to do.
319+ }
320+
321+ @Override
322+ public void onUnregister(Cluster cluster) {
323+ // nothing to do.
324+ }
325+ }
326+
327+ static class DefaultErrorFilter implements ErrorFilter {
328+ private static final List<Class<? extends Exception>> IGNORED_EXCEPTIONS =
329+ ImmutableList.<Class<? extends Exception>>builder()
330+ .add(FunctionExecutionException.class)
331+ .add(QueryConsistencyException.class)
332+ .add(UnavailableException.class)
333+ .add(AlreadyExistsException.class)
334+ .add(InvalidQueryException.class)
335+ .add(SyntaxError.class)
336+ .build();
337+
338+ @Override
339+ public boolean shouldConsiderError(Exception e, Host host, Statement statement) {
340+ for (Class<? extends Exception> ignoredException : IGNORED_EXCEPTIONS) {
341+ if (ignoredException.isInstance(e))
342+ return false;
343+ }
344+ return true;
345+ }
346+ }
347+
348+ /**
349+ * A filter for the errors considered by {@link ErrorAwarePolicy}.
350+ * <p/>
351+ * Only errors that indicate something wrong with a host should lead to its exclusion from query plans.
352+ */
353+ public interface ErrorFilter {
354+ /**
355+ * Whether an error should be counted in the host's error rate.
356+ *
357+ * @param e the exception.
358+ * @param host the host.
359+ * @param statement the statement that caused the exception.
360+ * @return {@code true} if the exception should be counted.
361+ */
362+ boolean shouldConsiderError(Exception e, Host host, Statement statement);
363+ }
364+}
added driver-core/src/test/java/com/datastax/driver/core/policies/PerHostErrorTrackerTest.java +256 −0
@@ -0,0 +1,256 @@
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+
19+import com.datastax.driver.core.Cluster;
20+import com.datastax.driver.core.Host;
21+import com.datastax.driver.core.HostDistance;
22+import com.datastax.driver.core.ResultSet;
23+import com.datastax.driver.core.ScassandraCluster;
24+import com.datastax.driver.core.Session;
25+import com.datastax.driver.core.Statement;
26+import com.datastax.driver.core.exceptions.UnauthorizedException;
27+import org.scassandra.Scassandra;
28+import org.testng.annotations.Test;
29+
30+import java.util.ArrayList;
31+import java.util.Collection;
32+import java.util.Collections;
33+import java.util.Comparator;
34+import java.util.Iterator;
35+import java.util.List;
36+
37+import static org.assertj.core.api.Assertions.assertThat;
38+import static org.assertj.core.api.Assertions.fail;
39+import static org.scassandra.http.client.PrimingRequest.queryBuilder;
40+import static org.scassandra.http.client.Result.success;
41+import static org.scassandra.http.client.Result.unauthorized;
42+
43+public class PerHostErrorTrackerTest {
44+
45+ @Test
46+ public void meterTest() throws InterruptedException {
47+ ScassandraCluster sCluster = ScassandraCluster.builder()
48+ .withNodes(3)
49+ .build();
50+
51+ String query = "SELECT foo FROM bar";
52+ sCluster.init();
53+
54+ for (Scassandra scassandra : sCluster.nodes()) {
55+ scassandra.primingClient().prime(
56+ queryBuilder()
57+ .withQuery(query)
58+ .withResult(success)
59+ .build()
60+ );
61+ }
62+
63+ sCluster.node(1).primingClient().prime(queryBuilder()
64+ .withQuery(query)
65+ .withResult(unauthorized)
66+ .build()
67+ );
68+
69+ LoadBalancingPolicy lbp =
70+ ErrorAwarePolicy.builder(new AlwaysSameHostsPolicy())
71+ .withInclusionThreshold(0.0000001)
72+ .withRetryPeriod(100000)
73+ .build();
74+
75+ Cluster cluster = Cluster.builder()
76+ .addContactPoints(sCluster.address(1).getAddress(), sCluster.address(2).getAddress(), sCluster.address(3).getAddress())
77+ .withPort(sCluster.getBinaryPort())
78+ .withLoadBalancingPolicy(lbp)
79+ .withRetryPolicy(FallthroughRetryPolicy.INSTANCE)
80+ .build();
81+
82+ Session session = cluster.connect();
83+
84+ try {
85+ // will send to node1, which will respond with an error.
86+ session.execute(query);
87+ } catch (UnauthorizedException e) {
88+ assertThat(e.getAddress()).isEqualTo(sCluster.address(1));
89+ }
90+
91+ // For some reason, it takes a certain time for the Meter to be updated when it's at 0...
92+ // So the previous is accounted, but it only appears to the tracker a little bit later.
93+ Thread.sleep(7000);
94+
95+ try {
96+ // will send to node1, which will respond with an error.
97+ session.execute(query);
98+ fail("Should have failed after sending query to node1");
99+ } catch (UnauthorizedException e) {
100+ assertThat(e.getAddress()).isEqualTo(sCluster.address(1));
101+ }
102+
103+ Thread.sleep(1000);
104+
105+ ResultSet rs = session.execute(query);
106+ assertThat(rs.getExecutionInfo().getQueriedHost().getSocketAddress()).isEqualTo(sCluster.address(2));
107+ }
108+
109+ @Test
110+ public void meterTest2() throws InterruptedException {
111+ ScassandraCluster sCluster = ScassandraCluster.builder()
112+ .withNodes(3)
113+ .build();
114+
115+ String query = "SELECT foo FROM bar";
116+ sCluster.init();
117+
118+ for (Scassandra scassandra : sCluster.nodes()) {
119+ scassandra.primingClient().prime(
120+ queryBuilder()
121+ .withQuery(query)
122+ .withResult(success)
123+ .build()
124+ );
125+ }
126+
127+ sCluster.node(1).primingClient().prime(queryBuilder()
128+ .withQuery(query)
129+ .withResult(unauthorized)
130+ .build()
131+ );
132+
133+ LoadBalancingPolicy lbp =
134+ ErrorAwarePolicy.builder(new AlwaysSameHostsPolicy())
135+ .withInclusionThreshold(0.2)
136+ .withRetryPeriod(1000)
137+ .build();
138+
139+ Cluster cluster = Cluster.builder()
140+ .addContactPoints(sCluster.address(1).getAddress(), sCluster.address(2).getAddress(), sCluster.address(3).getAddress())
141+ .withPort(sCluster.getBinaryPort())
142+ .withLoadBalancingPolicy(lbp)
143+ .withRetryPolicy(FallthroughRetryPolicy.INSTANCE)
144+ .build();
145+
146+ Session session = cluster.connect();
147+
148+ try {
149+ // will send to node1, which will respond with an error.
150+ session.execute(query);
151+ fail("Should have failed after sending query to node1");
152+ } catch (UnauthorizedException e) {
153+ assertThat(e.getAddress()).isEqualTo(sCluster.address(1));
154+ }
155+
156+ Thread.sleep(7000);
157+
158+ try {
159+ // will send to node1, which will respond with an error.
160+ session.execute(query);
161+ fail("Should have failed after sending query to node1");
162+ } catch (UnauthorizedException e) {
163+ assertThat(e.getAddress()).isEqualTo(sCluster.address(1));
164+ }
165+ // now node1 excluded
166+
167+ // wait until it is reconsidered
168+ Thread.sleep(2000);
169+
170+ try {
171+ // will send to node1, which will respond with an error.
172+ session.execute(query);
173+ fail("Should have failed after sending query to node1");
174+ } catch (UnauthorizedException e) {
175+ assertThat(e.getAddress()).isEqualTo(sCluster.address(1));
176+ }
177+
178+ }
179+
180+
181+
182+ private class AlwaysSameHostsPolicy implements LoadBalancingPolicy {
183+
184+ Collection<Host> hosts;
185+
186+ @Override
187+ public void init(Cluster cluster, Collection<Host> hosts) {
188+ // hosts may have been shuffled so need to sort in ascending order
189+ List<Host> copyHosts = new ArrayList<Host>(hosts);
190+ Collections.sort(copyHosts, new Comparator<Host>() {
191+ @Override
192+ public int compare(Host o1, Host o2) {
193+ byte[] ba1 = o1.getAddress().getAddress();
194+ byte[] ba2 = o2.getAddress().getAddress();
195+
196+ // general ordering: ipv4 before ipv6
197+ if (ba1.length < ba2.length) return -1;
198+ if (ba1.length > ba2.length) return 1;
199+
200+ // we have 2 ips of the same type, so we have to compare each byte
201+ for (int i = 0; i < ba1.length; i++) {
202+ int b1 = unsignedByteToInt(ba1[i]);
203+ int b2 = unsignedByteToInt(ba2[i]);
204+ if (b1 == b2)
205+ continue;
206+ if (b1 < b2)
207+ return -1;
208+ else
209+ return 1;
210+ }
211+ return 0;
212+ }
213+
214+ private int unsignedByteToInt(byte b) {
215+ return (int) b & 0xFF;
216+ }
217+ });
218+ this.hosts = copyHosts;
219+ }
220+
221+ @Override
222+ public HostDistance distance(Host host) {
223+ return HostDistance.LOCAL;
224+ }
225+
226+ @Override
227+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
228+ return hosts.iterator();
229+ }
230+
231+ @Override
232+ public void onAdd(Host host) {
233+
234+ }
235+
236+ @Override
237+ public void onUp(Host host) {
238+
239+ }
240+
241+ @Override
242+ public void onDown(Host host) {
243+
244+ }
245+
246+ @Override
247+ public void onRemove(Host host) {
248+
249+ }
250+
251+ @Override
252+ public void close() {
253+
254+ }
255+ }
256+}