Elffuss BraidHub

kikocis/java-driver public

Add WhiteListPolicy
Changesetdf49422ab9a3c060daaff69d9fb3914f8a1c2553301c41886cae259cfa372ae8
AuthorSylvain Lebresne <sylvain@datastax.com> · 2014-03-17 17:03 +01:00
CommitterSylvain Lebresne <sylvain@datastax.com> · 2014-03-17 17:03 +01:00
Parentsfae8df33a8ab

Browse the files at this changeset

5 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -6,6 +6,7 @@
66
77 - [new] Add method to check if a Cluster/Session instance has been closed already (JAVA-114)
88 - [new] Expose the name of the partitioner in use in the cluster metadata (JAVA-179)
9+- [new] Add new WhiteListPolicy to limit the nodes connected to a particular list
910
1011
1112 1.0.6:
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +17 −1
@@ -18,6 +18,7 @@
1818 import java.net.InetAddress;
1919 import java.net.UnknownHostException;
2020 import java.util.ArrayList;
21+import java.util.Collection;
2122 import java.util.List;
2223 import java.util.Set;
2324 import java.util.concurrent.*;
@@ -460,6 +461,22 @@
460461 return this;
461462 }
462463
464+ /**
465+ * Adds contact points.
466+ *
467+ * See {@link Builder#addContactPoint} for more details on contact
468+ * points.
469+ *
470+ * @param addresses addresses of the nodes to add as contact point
471+ * @return this Builder
472+ *
473+ * @see Builder#addContactPoint
474+ */
475+ public Builder addContactPoints(Collection<InetAddress> addresses) {
476+ this.addresses.addAll(addresses);
477+ return this;
478+ }
479+
463480 /**
464481 * Configures the load balancing policy to use for the new cluster.
465482 * <p>
@@ -1360,6 +1377,5 @@
13601377 }
13611378 return 0;
13621379 }
1363-
13641380 }
13651381 }
added driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +142 −0
@@ -0,0 +1,142 @@
1+/*
2+ * Copyright (C) 2012 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.InetAddress;
19+import java.util.ArrayList;
20+import java.util.Collection;
21+import java.util.Iterator;
22+import java.util.List;
23+import java.util.Set;
24+
25+import com.google.common.collect.ImmutableSet;
26+
27+import com.datastax.driver.core.Cluster;
28+import com.datastax.driver.core.Host;
29+import com.datastax.driver.core.HostDistance;
30+import com.datastax.driver.core.Query;
31+
32+/**
33+ * A load balancing policy wrapper that ensure that only hosts from a provided
34+ * white list will ever be returned.
35+ * <p>
36+ * This policy wraps another load balancing policy and will delegate the choice
37+ * of hosts to the wrapped policy with the exception that only hosts contained
38+ * in the white list provided when constructing this policy will ever be
39+ * returned. Any host not in the while list will be considered {@code IGNORED}
40+ * and thus will not be connected to.
41+ * <p>
42+ * This policy can be useful to ensure that the driver only connects to a
43+ * predefined set of hosts. Keep in mind however that this policy defeats
44+ * somewhat the host auto-detection of the driver. As such, this policy is only
45+ * useful in a few special cases or for testing, but is not optimal in general.
46+ * If all you want to do is limiting connections to hosts of the local
47+ * data-center then you should use DCAwareRoundRobinPolicy and *not* this policy
48+ * in particular.
49+ */
50+public class WhiteListPolicy implements LoadBalancingPolicy {
51+ private final LoadBalancingPolicy childPolicy;
52+ private final Set<InetAddress> whiteList;
53+
54+ /**
55+ * Create a new policy that wraps the provided child policy but only "allow" hosts
56+ * from the provided while list.
57+ *
58+ * @param childPolicy the wrapped policy.
59+ * @param whiteList the white listed hosts. Only hosts from this list may get connected
60+ * to (whether they will get connected to or not depends on the child policy).
61+ */
62+ public WhiteListPolicy(LoadBalancingPolicy childPolicy, Collection<InetAddress> whiteList) {
63+ this.childPolicy = childPolicy;
64+ this.whiteList = ImmutableSet.copyOf(whiteList);
65+ }
66+
67+ /**
68+ * Initialize this load balancing policy.
69+ *
70+ * @param cluster the {@code Cluster} instance for which the policy is created.
71+ * @param hosts the initial hosts to use.
72+ *
73+ * @throws IllegalArgumentException if none of the host in {@code hosts}
74+ * (which will correspond to the contact points) are part of the white list.
75+ */
76+ @Override
77+ public void init(Cluster cluster, Collection<Host> hosts) {
78+ List<Host> whiteHosts = new ArrayList<Host>(hosts.size());
79+ for (Host host : hosts)
80+ if (whiteList.contains(host.getAddress()))
81+ whiteHosts.add(host);
82+
83+ if (whiteHosts.isEmpty())
84+ throw new IllegalArgumentException(String.format("Cannot use WhiteListPolicy where the white list (%s) contains none of the contacts points (%s)", whiteList, hosts));
85+
86+ childPolicy.init(cluster, whiteHosts);
87+ }
88+
89+ /**
90+ * Return the HostDistance for the provided host.
91+ *
92+ * @param host the host of which to return the distance of.
93+ * @return {@link HostDistance.IGNORED} if {@code host} is not part of the white list, the HostDistance
94+ * as returned by the wrapped policy otherwise.
95+ */
96+ @Override
97+ public HostDistance distance(Host host) {
98+ return whiteList.contains(host.getAddress())
99+ ? childPolicy.distance(host)
100+ : HostDistance.IGNORED;
101+ }
102+
103+ /**
104+ * Returns the hosts to use for a new query.
105+ * <p>
106+ * It is guaranteed that only hosts from the white list will be returned.
107+ *
108+ * @param query the query for which to build the plan.
109+ * @return the new query plan.
110+ */
111+ @Override
112+ public Iterator<Host> newQueryPlan(final Query query) {
113+ // Just delegate to the child policy, since we filter the hosts not white
114+ // listed upfront, the child policy will never see a host that is not white
115+ // listed and thus can't return one.
116+ return childPolicy.newQueryPlan(query);
117+ }
118+
119+ @Override
120+ public void onUp(Host host) {
121+ if (whiteList.contains(host.getAddress()))
122+ childPolicy.onUp(host);
123+ }
124+
125+ @Override
126+ public void onDown(Host host) {
127+ if (whiteList.contains(host.getAddress()))
128+ childPolicy.onDown(host);
129+ }
130+
131+ @Override
132+ public void onAdd(Host host) {
133+ if (whiteList.contains(host.getAddress()))
134+ childPolicy.onAdd(host);
135+ }
136+
137+ @Override
138+ public void onRemove(Host host) {
139+ if (whiteList.contains(host.getAddress()))
140+ childPolicy.onRemove(host);
141+ }
142+}
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +4 −1
@@ -311,7 +311,10 @@
311311 private CCMCluster(CCMBridge cassandraCluster, Cluster.Builder builder, int totalNodes) {
312312 this.cassandraCluster = cassandraCluster;
313313 try {
314- this.cluster = builder.addContactPoints(IP_PREFIX + "1").build();
314+ String[] contactPoints = new String[totalNodes];
315+ for (int i = 0; i < totalNodes; i++)
316+ contactPoints[i] = IP_PREFIX + (i+1);
317+ this.cluster = builder.addContactPoints(contactPoints).build();
315318 this.session = cluster.connect();
316319 } catch (NoHostAvailableException e) {
317320 for (Map.Entry<InetAddress, String> entry : e.getErrors().entrySet())
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyTest.java +41 −3
@@ -15,15 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetAddress;
19+import java.util.*;
20+
1821 import static com.datastax.driver.core.TestUtils.*;
1922 import static org.testng.Assert.*;
2023 import org.testng.annotations.Test;
2124
2225 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2326 import com.datastax.driver.core.exceptions.UnavailableException;
24-import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
25-import com.datastax.driver.core.policies.RoundRobinPolicy;
26-import com.datastax.driver.core.policies.TokenAwarePolicy;
27+import com.datastax.driver.core.policies.*;
2728
2829 public class LoadBalancingPolicyTest extends AbstractPoliciesTest {
2930 private static final boolean DEBUG = false;
@@ -72,6 +73,43 @@
7273 }
7374 }
7475
76+ @Test(groups = "long")
77+ public void whiteListPolicyTest() throws Throwable {
78+
79+ List<InetAddress> whiteList = Arrays.asList(InetAddress.getByName(CCMBridge.IP_PREFIX + '2'));
80+
81+ Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), whiteList));
82+ CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
83+ try {
84+
85+ createSchema(c.session);
86+ init(c, 12);
87+ query(c, 12);
88+
89+ assertQueried(CCMBridge.IP_PREFIX + "1", 0);
90+ assertQueried(CCMBridge.IP_PREFIX + "2", 12);
91+ assertQueried(CCMBridge.IP_PREFIX + "3", 0);
92+
93+ resetCoordinators();
94+ c.cassandraCluster.decommissionNode(2);
95+ waitForDecommission(CCMBridge.IP_PREFIX + "2", c.cluster);
96+
97+ try {
98+ query(c, 12);
99+ fail("Should work, we've only whitelisted node 2 and it's been removed");
100+ } catch (NoHostAvailableException e) {
101+ // That's what we expected
102+ }
103+
104+ } catch (Throwable e) {
105+ c.errorOut();
106+ throw e;
107+ } finally {
108+ resetCoordinators();
109+ c.discard();
110+ }
111+ }
112+
75113 @Test(groups = "long")
76114 public void roundRobinWith2DCsTest() throws Throwable {
77115