Elffuss BraidHub

kikocis/java-driver public

Merge pull request #512 from datastax/java652

JAVA-652: Add DCAwareRoundRobinPolicy builder.
Changeset5e3e86a8f8bbf2160e1e5c0190993107ed0ba3b325360a4c7a1cdf201e596c71
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-11-05 19:00 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-11-05 19:00 +01:00
Parents2d8132f27b8f, eff7ed791a6c

Browse the files at this changeset

6 files changed

modified changelog/README.md +2 −0
@@ -12,6 +12,8 @@
1212 - [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo.
1313 - [bug] JAVA-966: Count uninitialized connections in conviction policy.
1414 - [improvement] JAVA-917: Document SSL configuration.
15+- [improvement] JAVA-652: Add DCAwareRoundRobinPolicy builder.
16+- [improvement] JAVA-808: Add generic filtering policy that can be used to exclude specific DCs.
1517
1618
1719 ### 2.0.11
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +105 −83
@@ -22,8 +22,7 @@
2222 import java.util.concurrent.atomic.AtomicInteger;
2323
2424 import com.google.common.annotations.VisibleForTesting;
25-import com.google.common.base.Joiner;
26-import com.google.common.base.Strings;
25+import com.google.common.base.*;
2726 import com.google.common.collect.AbstractIterator;
2827 import org.slf4j.Logger;
2928 import org.slf4j.LoggerFactory;
@@ -46,15 +45,23 @@
4645 * data center can be reached.
4746 * <p>
4847 * If used with a single data center, this policy is equivalent to the
49- * {@code LoadBalancingPolicy.RoundRobin} policy, but its DC awareness
50- * incurs a slight overhead so the {@code LoadBalancingPolicy.RoundRobin}
51- * policy could be preferred to this policy in that case.
48+ * {@link RoundRobinPolicy}, but its DC awareness incurs a slight overhead
49+ * so the latter should be preferred to this policy in that case.
5250 */
5351 public class DCAwareRoundRobinPolicy implements LoadBalancingPolicy, CloseableLoadBalancingPolicy {
5452
5553 private static final Logger logger = LoggerFactory.getLogger(DCAwareRoundRobinPolicy.class);
5654
57- private final String UNSET = "";
55+ /**
56+ * Returns a builder to create a new instance.
57+ *
58+ * @return the builder.
59+ */
60+ public static Builder builder() {
61+ return new Builder();
62+ }
63+
64+ private static final String UNSET = "";
5865
5966 private final ConcurrentMap<String, CopyOnWriteArrayList<Host>> perDcLiveHosts = new ConcurrentHashMap<String, CopyOnWriteArrayList<Host>>();
6067 private final AtomicInteger index = new AtomicInteger();
@@ -68,101 +75,35 @@
6875 private volatile Configuration configuration;
6976
7077 /**
71- * Creates a new datacenter aware round robin policy that auto-discover
72- * the local data-center.
73- * <p>
74- * If this constructor is used, the data-center used as local will the
75- * data-center of the first Cassandra node the driver connects to. This
76- * will always be ok if all the contact points use at {@code Cluster}
77- * creation are in the local data-center. If it's not the case, you should
78- * provide the local data-center name yourself by using one of the other
79- * constructor of this class.
80- * <p>
81- * This constructor is a shortcut for {@code new DCAwareRoundRobinPolicy(null)},
82- * and as such will ignore all hosts in remote data-centers.
78+ * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for
79+ * backward-compatibility purposes, it is equivalent to {@code DCAwareRoundRobinPolicy.builder().build()}.
8380 */
81+ @Deprecated
8482 public DCAwareRoundRobinPolicy() {
8583 this(null, 0, false, true);
8684 }
8785
8886 /**
89- * Creates a new datacenter aware round robin policy given the name of
90- * the local datacenter.
91- * <p>
92- * The name of the local datacenter provided must be the local
93- * datacenter name as known by Cassandra.
94- * <p>
95- * The policy created will ignore all remote hosts. In other words,
96- * this is equivalent to {@code new DCAwareRoundRobinPolicy(localDc, 0)}.
97- *
98- * @param localDc the name of the local datacenter (as known by
99- * Cassandra). If this is {@code null}, the policy will default to the
100- * data-center of the first node connected to.
87+ * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for
88+ * backward-compatibility purposes, it is equivalent to {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).build()}.
10189 */
10290 public DCAwareRoundRobinPolicy(String localDc) {
10391 this(localDc, 0, false, false);
10492 }
10593
10694 /**
107- * Creates a new DCAwareRoundRobin policy given the name of the local
108- * datacenter and that uses the provided number of host per remote
109- * datacenter as failover for the local hosts.
110- * <p>
111- * The name of the local datacenter provided must be the local
112- * datacenter name as known by Cassandra.
113- * <p>
114- * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host
115- * in the local datacenter can be reached and if the consistency
116- * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM},
117- * then up to {@code usedHostsPerRemoteDc} host per remote data-center
118- * will be tried by the policy as a fallback. Please note that no
119- * remote host will be used for {@code LOCAL_ONE} and {@code LOCAL_QUORUM}
120- * since this would change the meaning of the consistency level (and
121- * thus somewhat break the consistency contract).
122- *
123- * @param localDc the name of the local datacenter (as known by
124- * Cassandra). If this is {@code null}, the policy will default to the
125- * data-center of the first node connected to.
126- * @param usedHostsPerRemoteDc the number of host per remote
127- * datacenter that policies created by the returned factory should
128- * consider. Created policies {@code distance} method will return a
129- * {@code HostDistance.REMOTE} distance for only {@code
130- * usedHostsPerRemoteDc} hosts per remote datacenter. Other hosts
131- * of the remote datacenters will be ignored (and thus no
132- * connections to them will be maintained).
95+ * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for
96+ * backward-compatibility purposes, it is equivalent to
97+ * {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).withUsedHostsPerRemoteDc(usedHostsPerRemoteDc).build()}.
13398 */
13499 public DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc) {
135100 this(localDc, usedHostsPerRemoteDc, false, false);
136101 }
137102
138103 /**
139- * Creates a new DCAwareRoundRobin policy given the name of the local
140- * datacenter and that uses the provided number of host per remote
141- * datacenter as failover for the local hosts.
142- * <p>
143- * This constructor is equivalent to {@link #DCAwareRoundRobinPolicy(String, int)}
144- * but allows to override the policy of never using remote data-center
145- * nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is
146- * however inadvisable to do so in almost all cases, as this would
147- * potentially break consistency guarantees and if you are fine with that,
148- * it's probably better to use a weaker consitency like {@code ONE}, {@code
149- * TWO} or {@code THREE}. As such, this constructor should generally
150- * be avoided in favor of {@link #DCAwareRoundRobinPolicy(String, int)}.
151- * Use it only if you know and understand what you do.
152- *
153- * @param localDc the name of the local datacenter (as known by
154- * Cassandra). If this is {@code null}, the policy will default to the
155- * data-center of the first node connected to.
156- * @param usedHostsPerRemoteDc the number of host per remote
157- * datacenter that policies created by the returned factory should
158- * consider. Created policies {@code distance} method will return a
159- * {@code HostDistance.REMOTE} distance for only {@code
160- * usedHostsPerRemoteDc} hosts per remote datacenter. Other hosts
161- * of the remote datacenters will be ignored (and thus no
162- * connections to them will be maintained).
163- * @param allowRemoteDCsForLocalConsistencyLevel whether or not the
164- * policy may return remote host when building query plan for query
165- * having consitency {@code LOCAL_ONE} and {@code LOCAL_QUORUM}.
104+ * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for
105+ * backward-compatibility purposes, it is equivalent to
106+ * {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).withUsedHostsPerRemoteDc(usedHostsPerRemoteDc).allowRemoteDCsForLocalConsistencyLevel().build()}.
166107 */
167108 public DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc, boolean allowRemoteDCsForLocalConsistencyLevel) {
168109 this(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, false);
@@ -381,4 +322,85 @@
381322 public void close() {
382323 // nothing to do
383324 }
325+
326+ /**
327+ * Helper class to build the policy.
328+ */
329+ public static class Builder {
330+ private String localDc;
331+ private int usedHostsPerRemoteDc;
332+ private boolean allowRemoteDCsForLocalConsistencyLevel;
333+
334+ /**
335+ * Sets the name of the datacenter that will be considered "local" by the policy.
336+ * <p>
337+ * This must be the name as known by Cassandra (in other words, the name in that appears in
338+ * {@code system.peers}, or in the output of admin tools like nodetool).
339+ * <p>
340+ * If this method isn't called, the policy will default to the datacenter of the first node
341+ * connected to. This will always be ok if all the contact points use at {@code Cluster}
342+ * creation are in the local data-center. Otherwise, you should provide the name yourself
343+ * with this method.
344+ *
345+ * @param localDc the name of the datacenter. It should not be {@code null}.
346+ * @return this builder.
347+ */
348+ public Builder withLocalDc(String localDc) {
349+ Preconditions.checkArgument(!Strings.isNullOrEmpty(localDc),
350+ "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC");
351+ this.localDc = localDc;
352+ return this;
353+ }
354+
355+ /**
356+ * Sets the number of hosts per remote datacenter that the policy should consider.
357+ * <p>
358+ * The policy's {@code distance()} method will return a {@code HostDistance.REMOTE} distance for only {@code usedHostsPerRemoteDc}
359+ * hosts per remote datacenter. Other hosts of the remote datacenters will be ignored (and thus no connections to them will be
360+ * maintained).
361+ * <p>
362+ * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host in the local datacenter can be reached and if the consistency
363+ * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM}, then up to {@code usedHostsPerRemoteDc} hosts per remote
364+ * datacenter will be tried by the policy as a fallback. By default, no remote host will be used for {@code LOCAL_ONE} and
365+ * {@code LOCAL_QUORUM}, since this would change the meaning of the consistency level, somewhat breaking the consistency contract
366+ * (this can be overridden with {@link #allowRemoteDCsForLocalConsistencyLevel()}).
367+ * <p>
368+ * If this method isn't called, the policy will default to 0.
369+ *
370+ * @param usedHostsPerRemoteDc the number.
371+ * @return this builder.
372+ */
373+ public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) {
374+ Preconditions.checkArgument(usedHostsPerRemoteDc >= 0,
375+ "usedHostsPerRemoteDc must be equal or greater than 0");
376+ this.usedHostsPerRemoteDc = usedHostsPerRemoteDc;
377+ return this;
378+ }
379+
380+ /**
381+ * Allows the policy to return remote hosts when building query plans for queries having consistency level {@code LOCAL_ONE}
382+ * or {@code LOCAL_QUORUM}.
383+ * <p>
384+ * When used in conjunction with {@link #withUsedHostsPerRemoteDc(int) usedHostsPerRemoteDc} > 0, this overrides the policy of
385+ * never using remote datacenter nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is however inadvisable to do
386+ * so in almost all cases, as this would potentially break consistency guarantees and if you are fine with that, it's probably
387+ * better to use a weaker consitency like {@code ONE}, {@code TWO} or {@code THREE}. As such, this method should generally be
388+ * avoided; use it only if you know and understand what you do.
389+ *
390+ * @return this builder.
391+ */
392+ public Builder allowRemoteDCsForLocalConsistencyLevel() {
393+ this.allowRemoteDCsForLocalConsistencyLevel = true;
394+ return this;
395+ }
396+
397+ /**
398+ * Builds the policy configured by this builder.
399+ *
400+ * @return the policy.
401+ */
402+ public DCAwareRoundRobinPolicy build() {
403+ return new DCAwareRoundRobinPolicy(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, true);
404+ }
405+ }
384406 }
added driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java +184 −0
@@ -0,0 +1,184 @@
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.net.InetSocketAddress;
19+import java.util.ArrayList;
20+import java.util.Collection;
21+import java.util.Iterator;
22+import java.util.List;
23+
24+import com.google.common.base.Predicate;
25+import com.google.common.base.Predicates;
26+import com.google.common.collect.ImmutableSet;
27+
28+import com.datastax.driver.core.Cluster;
29+import com.datastax.driver.core.Host;
30+import com.datastax.driver.core.HostDistance;
31+import com.datastax.driver.core.Statement;
32+
33+/**
34+ * A load balancing policy wrapper that ensures that only hosts matching the predicate
35+ * will ever be returned.
36+ * <p>
37+ * This policy wraps another load balancing policy and will delegate the choice
38+ * of hosts to the wrapped policy with the exception that only hosts matching
39+ * the predicate provided when constructing this policy will ever be
40+ * returned. Any host not matching the predicate will be considered {@code IGNORED}
41+ * and thus will not be connected to.
42+ */
43+public class HostFilterPolicy implements ChainableLoadBalancingPolicy, CloseableLoadBalancingPolicy {
44+ private final LoadBalancingPolicy childPolicy;
45+ private final Predicate<Host> predicate;
46+
47+ /**
48+ * Create a new policy that wraps the provided child policy but only "allows" hosts
49+ * matching the predicate.
50+ *
51+ * @param childPolicy the wrapped policy.
52+ * @param predicate the host predicate. Only hosts matching this predicate may get connected
53+ * to (whether they will get connected to or not depends on the child policy).
54+ */
55+ public HostFilterPolicy(LoadBalancingPolicy childPolicy, Predicate<Host> predicate) {
56+ this.childPolicy = childPolicy;
57+ this.predicate = predicate;
58+ }
59+
60+ @Override
61+ public LoadBalancingPolicy getChildPolicy() {
62+ return childPolicy;
63+ }
64+
65+ /**
66+ * {@inheritDoc}
67+ *
68+ * @throws IllegalArgumentException if none of the host in {@code hosts}
69+ * (which will correspond to the contact points) matches the predicate.
70+ */
71+ @Override
72+ public void init(Cluster cluster, Collection<Host> hosts) {
73+ List<Host> whiteHosts = new ArrayList<Host>(hosts.size());
74+ for (Host host : hosts)
75+ if (predicate.apply(host))
76+ whiteHosts.add(host);
77+
78+ if (whiteHosts.isEmpty())
79+ throw new IllegalArgumentException(String.format("Cannot use HostFilterPolicy where the filter allows none of the contacts points (%s)", hosts));
80+
81+ childPolicy.init(cluster, whiteHosts);
82+ }
83+
84+ /**
85+ * {@inheritDoc}
86+ *
87+ * @return {@link HostDistance#IGNORED} if {@code host} is not matching the predicate, the HostDistance
88+ * as returned by the wrapped policy otherwise.
89+ */
90+ @Override
91+ public HostDistance distance(Host host) {
92+ return predicate.apply(host)
93+ ? childPolicy.distance(host)
94+ : HostDistance.IGNORED;
95+ }
96+
97+ /**
98+ * {@inheritDoc}
99+ * <p>
100+ * It is guaranteed that only hosts matching the predicate will be returned.
101+ */
102+ @Override
103+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
104+ // Just delegate to the child policy, since we filter the hosts not white
105+ // listed upfront, the child policy will never see a host that is not white
106+ // listed and thus can't return one.
107+ return childPolicy.newQueryPlan(loggedKeyspace, statement);
108+ }
109+
110+ @Override
111+ public void onUp(Host host) {
112+ if (predicate.apply(host))
113+ childPolicy.onUp(host);
114+ }
115+
116+ @SuppressWarnings("deprecation")
117+ @Override
118+ public void onSuspected(Host host) {
119+ if (predicate.apply(host))
120+ childPolicy.onSuspected(host);
121+ }
122+
123+ @Override
124+ public void onDown(Host host) {
125+ if (predicate.apply(host))
126+ childPolicy.onDown(host);
127+ }
128+
129+ @Override
130+ public void onAdd(Host host) {
131+ if (predicate.apply(host))
132+ childPolicy.onAdd(host);
133+ }
134+
135+ @Override
136+ public void onRemove(Host host) {
137+ if (predicate.apply(host))
138+ childPolicy.onRemove(host);
139+ }
140+
141+ @Override
142+ public void close() {
143+ if (childPolicy instanceof CloseableLoadBalancingPolicy)
144+ ((CloseableLoadBalancingPolicy)childPolicy).close();
145+ }
146+
147+ /**
148+ * Create a new policy that wraps the provided child policy but only "allows" hosts
149+ * whose DC belongs to the provided list.
150+ *
151+ * @param childPolicy the wrapped policy.
152+ * @param dcs the DCs.
153+ *
154+ * @return the policy.
155+ */
156+ public static HostFilterPolicy fromDCWhiteList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
157+ return new HostFilterPolicy(childPolicy, hostDCPredicate(dcs, true));
158+ }
159+
160+ /**
161+ * Create a new policy that wraps the provided child policy but only "forbids" hosts
162+ * whose DC belongs to the provided list.
163+ *
164+ * @param childPolicy the wrapped policy.
165+ * @param dcs the DCs.
166+ *
167+ * @return the policy.
168+ */
169+ public static HostFilterPolicy fromDCBlackList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
170+ return new HostFilterPolicy(childPolicy, Predicates.not(hostDCPredicate(dcs, false)));
171+ }
172+
173+ private static Predicate<Host> hostDCPredicate(Iterable<String> dcs, final boolean includeNullDC) {
174+ final ImmutableSet<String> _dcs = ImmutableSet.copyOf(dcs);
175+ return new Predicate<Host>() {
176+ @Override
177+ public boolean apply(Host host) {
178+ String hdc = host.getDatacenter();
179+ return (hdc == null) ? includeNullDC : _dcs.contains(hdc);
180+ }
181+ };
182+ }
183+
184+}
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +1 −1
@@ -87,7 +87,7 @@
8787 public static LoadBalancingPolicy defaultLoadBalancingPolicy() {
8888 // Note: balancing policies are stateful, so we can't store that in a static or that would screw thing
8989 // up if multiple Cluster instance are started in the same JVM.
90- return new TokenAwarePolicy(new DCAwareRoundRobinPolicy());
90+ return new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build());
9191 }
9292
9393 /**
modified driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +14 −106
@@ -16,18 +16,12 @@
1616 package com.datastax.driver.core.policies;
1717
1818 import java.net.InetSocketAddress;
19-import java.util.ArrayList;
2019 import java.util.Collection;
21-import java.util.Iterator;
22-import java.util.List;
23-import java.util.Set;
2420
21+import com.google.common.base.Predicate;
2522 import com.google.common.collect.ImmutableSet;
2623
27-import com.datastax.driver.core.Cluster;
2824 import com.datastax.driver.core.Host;
29-import com.datastax.driver.core.HostDistance;
30-import com.datastax.driver.core.Statement;
3125
3226 /**
3327 * A load balancing policy wrapper that ensure that only hosts from a provided
@@ -46,13 +40,13 @@
4640 * If all you want to do is limiting connections to hosts of the local
4741 * data-center then you should use DCAwareRoundRobinPolicy and *not* this policy
4842 * in particular.
43+ *
44+ * @see HostFilterPolicy
4945 */
50-public class WhiteListPolicy implements ChainableLoadBalancingPolicy, CloseableLoadBalancingPolicy {
51- private final LoadBalancingPolicy childPolicy;
52- private final Set<InetSocketAddress> whiteList;
46+public class WhiteListPolicy extends HostFilterPolicy {
5347
5448 /**
55- * Create a new policy that wraps the provided child policy but only "allow" hosts
49+ * Creates a new policy that wraps the provided child policy but only "allows" hosts
5650 * from the provided while list.
5751 *
5852 * @param childPolicy the wrapped policy.
@@ -60,103 +54,17 @@
6054 * to (whether they will get connected to or not depends on the child policy).
6155 */
6256 public WhiteListPolicy(LoadBalancingPolicy childPolicy, Collection<InetSocketAddress> whiteList) {
63- this.childPolicy = childPolicy;
64- this.whiteList = ImmutableSet.copyOf(whiteList);
57+ super(childPolicy, buildPredicate(whiteList));
6558 }
6659
67- @Override
68- public LoadBalancingPolicy getChildPolicy() {
69- return childPolicy;
60+ private static Predicate<Host> buildPredicate(Collection<InetSocketAddress> whiteList) {
61+ final ImmutableSet<InetSocketAddress> hosts = ImmutableSet.copyOf(whiteList);
62+ return new Predicate<Host>() {
63+ @Override
64+ public boolean apply(Host host) {
65+ return hosts.contains(host.getSocketAddress());
66+ }
67+ };
7068 }
7169
72- /**
73- * Initialize this load balancing policy.
74- *
75- * @param cluster the {@code Cluster} instance for which the policy is created.
76- * @param hosts the initial hosts to use.
77- *
78- * @throws IllegalArgumentException if none of the host in {@code hosts}
79- * (which will correspond to the contact points) are part of the white list.
80- */
81- @Override
82- public void init(Cluster cluster, Collection<Host> hosts) {
83- List<Host> whiteHosts = new ArrayList<Host>(hosts.size());
84- for (Host host : hosts)
85- if (whiteList.contains(host.getSocketAddress()))
86- whiteHosts.add(host);
87-
88- if (whiteHosts.isEmpty())
89- throw new IllegalArgumentException(String.format("Cannot use WhiteListPolicy where the white list (%s) contains none of the contacts points (%s)", whiteList, hosts));
90-
91- childPolicy.init(cluster, whiteHosts);
92- }
93-
94- /**
95- * Return the HostDistance for the provided host.
96- *
97- * @param host the host of which to return the distance of.
98- * @return {@link HostDistance#IGNORED} if {@code host} is not part of the white list, the HostDistance
99- * as returned by the wrapped policy otherwise.
100- */
101- @Override
102- public HostDistance distance(Host host) {
103- return whiteList.contains(host.getSocketAddress())
104- ? childPolicy.distance(host)
105- : HostDistance.IGNORED;
106- }
107-
108- /**
109- * Returns the hosts to use for a new query.
110- * <p>
111- * It is guaranteed that only hosts from the white list will be returned.
112- *
113- * @param loggedKeyspace the currently logged keyspace (the one set through either
114- * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for
115- * the session on which this plan need to be built. This can be {@code null} if
116- * the corresponding session has no keyspace logged in.
117- * @param statement the query for which to build a plan.
118- */
119- @Override
120- public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
121- // Just delegate to the child policy, since we filter the hosts not white
122- // listed upfront, the child policy will never see a host that is not white
123- // listed and thus can't return one.
124- return childPolicy.newQueryPlan(loggedKeyspace, statement);
125- }
126-
127- @Override
128- public void onUp(Host host) {
129- if (whiteList.contains(host.getSocketAddress()))
130- childPolicy.onUp(host);
131- }
132-
133- @Override
134- public void onSuspected(Host host) {
135- if (whiteList.contains(host.getSocketAddress()))
136- childPolicy.onSuspected(host);
137- }
138-
139- @Override
140- public void onDown(Host host) {
141- if (whiteList.contains(host.getSocketAddress()))
142- childPolicy.onDown(host);
143- }
144-
145- @Override
146- public void onAdd(Host host) {
147- if (whiteList.contains(host.getSocketAddress()))
148- childPolicy.onAdd(host);
149- }
150-
151- @Override
152- public void onRemove(Host host) {
153- if (whiteList.contains(host.getSocketAddress()))
154- childPolicy.onRemove(host);
155- }
156-
157- @Override
158- public void close() {
159- if (childPolicy instanceof CloseableLoadBalancingPolicy)
160- ((CloseableLoadBalancingPolicy)childPolicy).close();
161- }
16270 }
added driver-core/src/test/java/com/datastax/driver/core/policies/HostFilterPolicyTest.java +168 −0
@@ -0,0 +1,168 @@
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.net.InetSocketAddress;
19+import java.util.Collection;
20+
21+import com.google.common.base.Predicate;
22+import com.google.common.base.Predicates;
23+import com.google.common.collect.Iterators;
24+import com.google.common.collect.Lists;
25+import org.mockito.ArgumentCaptor;
26+import org.mockito.Captor;
27+import org.mockito.Mock;
28+import org.mockito.MockitoAnnotations;
29+import org.testng.annotations.BeforeMethod;
30+import org.testng.annotations.Test;
31+
32+import static org.assertj.core.api.Assertions.assertThat;
33+import static org.mockito.Mockito.*;
34+
35+import com.datastax.driver.core.Cluster;
36+import com.datastax.driver.core.Host;
37+import com.datastax.driver.core.HostDistance;
38+import com.datastax.driver.core.Statement;
39+
40+public class HostFilterPolicyTest {
41+ @Mock
42+ Cluster cluster;
43+
44+ @Mock
45+ Host host1, host2, host3;
46+
47+ InetSocketAddress address1 = InetSocketAddress.createUnresolved("192.168.1.1", 2345);
48+ InetSocketAddress address2 = InetSocketAddress.createUnresolved("192.168.1.2", 9876);
49+ InetSocketAddress address3 = InetSocketAddress.createUnresolved("192.168.1.3", 6666);
50+
51+ @Mock
52+ CloseableLoadBalancingPolicy wrappedPolicy;
53+
54+ @Captor
55+ ArgumentCaptor<Collection<Host>> hostsCaptor;
56+
57+ @BeforeMethod(groups = "unit")
58+ public void setup() {
59+ MockitoAnnotations.initMocks(this);
60+
61+ when(host1.getSocketAddress()).thenReturn(address1);
62+ when(host2.getSocketAddress()).thenReturn(address2);
63+ when(host3.getSocketAddress()).thenReturn(address3);
64+
65+ when(wrappedPolicy.distance(any(Host.class))).thenReturn(HostDistance.LOCAL);
66+ }
67+
68+ @Test(groups = "unit")
69+ public void should_delegate_to_wrapped_policy_when_predicate_is_true() {
70+ Predicate<Host> predicate = Predicates.alwaysTrue();
71+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate);
72+
73+ policy.onAdd(host1);
74+ verify(wrappedPolicy).onAdd(host1);
75+
76+ policy.onDown(host1);
77+ verify(wrappedPolicy).onDown(host1);
78+
79+ policy.onUp(host1);
80+ verify(wrappedPolicy).onUp(host1);
81+
82+ policy.onRemove(host1);
83+ verify(wrappedPolicy).onRemove(host1);
84+
85+ assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL);
86+
87+ policy.close();
88+ verify(wrappedPolicy).close();
89+ }
90+
91+ @Test(groups = "unit")
92+ public void should_not_delegate_to_wrapped_policy_when_predicate_is_false() {
93+ Predicate<Host> predicate = Predicates.alwaysFalse();
94+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate);
95+
96+ policy.onAdd(host1);
97+ verify(wrappedPolicy, never()).onAdd(host1);
98+
99+ policy.onDown(host1);
100+ verify(wrappedPolicy, never()).onDown(host1);
101+
102+ policy.onUp(host1);
103+ verify(wrappedPolicy, never()).onUp(host1);
104+
105+ policy.onRemove(host1);
106+ verify(wrappedPolicy, never()).onRemove(host1);
107+
108+ assertThat(policy.distance(host1)).isSameAs(HostDistance.IGNORED);
109+ }
110+
111+ @Test(groups = "unit")
112+ public void should_filter_init_hosts_with_predicate() {
113+ Predicate<Host> predicate = Predicates.in(Lists.newArrayList(host1, host2));
114+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate);
115+
116+ policy.init(cluster, Lists.newArrayList(host1, host2, host3));
117+
118+ verify(wrappedPolicy).init(eq(cluster), hostsCaptor.capture());
119+ assertThat(hostsCaptor.getValue()).containsOnly(host1, host2);
120+ }
121+
122+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
123+ public void should_throw_if_predicate_filters_out_all_init_hosts() {
124+ Predicate<Host> predicate = Predicates.alwaysFalse();
125+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate);
126+
127+ policy.init(cluster, Lists.newArrayList(host1, host2, host3));
128+ }
129+
130+ @Test(groups = "unit")
131+ public void should_return_query_plan_of_wrapped_policy() {
132+ when(wrappedPolicy.newQueryPlan(any(String.class), any(Statement.class)))
133+ .thenReturn(Iterators.forArray(host1, host2, host3));
134+
135+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, null);
136+
137+ assertThat(policy.newQueryPlan("keyspace", mock(Statement.class)))
138+ .containsExactly(host1, host2, host3);
139+ }
140+
141+ @Test(groups = "unit")
142+ public void should_ignore_DCs_in_black_list() {
143+ when(host1.getDatacenter()).thenReturn("dc1");
144+ when(host2.getDatacenter()).thenReturn("dc2");
145+ when(host3.getDatacenter()).thenReturn(null);
146+
147+ HostFilterPolicy policy = HostFilterPolicy.fromDCBlackList(wrappedPolicy,
148+ Lists.newArrayList("dc2"));
149+
150+ assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL);
151+ assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED);
152+ assertThat(policy.distance(host3)).isSameAs(HostDistance.LOCAL);
153+ }
154+
155+ @Test(groups = "unit")
156+ public void should_ignore_DCs_not_in_white_list_and_not_null() {
157+ when(host1.getDatacenter()).thenReturn("dc1");
158+ when(host2.getDatacenter()).thenReturn("dc2");
159+ when(host3.getDatacenter()).thenReturn(null);
160+
161+ HostFilterPolicy policy = HostFilterPolicy.fromDCWhiteList(wrappedPolicy,
162+ Lists.newArrayList("dc1"));
163+
164+ assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL);
165+ assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED);
166+ assertThat(policy.distance(host3)).isSameAs(HostDistance.LOCAL);
167+ }
168+}