Elffuss BraidHub

kikocis/java-driver public

Add AddressTranslater for EC2 multi-region deployment (JAVA-518).
Changesetbb694ea629e283117ac3daa6834826bb40e76c7b3c71efd8c198c2b5efaac31b
Authorolim7t <omichallat+github@gmail.com> · 2014-11-21 17:25 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-11-26 18:06 +01:00
Parentsdce212d79db5

Browse the files at this changeset

5 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -6,6 +6,7 @@
66
77 - [improvement] Shade Netty dependency (JAVA-538)
88 - [improvement] Target schema refreshes more precisely (JAVA-543)
9+- [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518)
910
1011
1112 2.0.8:
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +4 −0
@@ -1315,6 +1315,10 @@
13151315 if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
13161316 ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
13171317
1318+ AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
1319+ if (translater instanceof CloseableAddressTranslater)
1320+ ((CloseableAddressTranslater)translater).close();
1321+
13181322 // Then we shutdown all connections
13191323 List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1);
13201324 futures.add(controlConnection.closeAsync());
added driver-core/src/main/java/com/datastax/driver/core/policies/CloseableAddressTranslater.java +32 −0
@@ -0,0 +1,32 @@
1+/*
2+ * Copyright (C) 2012-2014 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.Cluster;
19+
20+/**
21+ * Extends {@link AddressTranslater} for implementations that need to free some resources
22+ * at {@link Cluster} shutdown.
23+ * <p>
24+ * Note: the only reason {@link #close()} was not added directly to {@code AddressTranslater}
25+ * is backward-compatibility.
26+ */
27+public interface CloseableAddressTranslater extends AddressTranslater {
28+ /**
29+ * Called at {@link Cluster} shutdown.
30+ */
31+ void close();
32+}
added driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslater.java +139 −0
@@ -0,0 +1,139 @@
1+/*
2+ * Copyright (C) 2012-2014 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.net.InetSocketAddress;
20+import java.util.Enumeration;
21+import java.util.Hashtable;
22+
23+import com.google.common.annotations.VisibleForTesting;
24+import javax.naming.Context;
25+import javax.naming.NamingEnumeration;
26+import javax.naming.NamingException;
27+import javax.naming.directory.Attribute;
28+import javax.naming.directory.Attributes;
29+import javax.naming.directory.DirContext;
30+import javax.naming.directory.InitialDirContext;
31+import org.slf4j.Logger;
32+import org.slf4j.LoggerFactory;
33+
34+import com.datastax.driver.core.exceptions.DriverException;
35+
36+/**
37+ * {@link AddressTranslater} implementation for a multi-region EC2 deployment <b>where clients are also deployed in EC2</b>.
38+ * <p>
39+ * Its distinctive feature is that it translates addresses according to the location of the Cassandra host:
40+ * <ul>
41+ * <li>addresses in different EC2 regions (than the client) are unchanged;</li>
42+ * <li>addresses in the same EC2 region are <b>translated to private IPs</b>.</li>
43+ * </ul>
44+ * This optimizes network costs, because Amazon charges more for communication over public IPs.
45+ *
46+ * <p>
47+ * Implementation note: this class performs a reverse DNS lookup of the origin address, to find the domain name of the target
48+ * instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the private/public switch automatically
49+ * based on location.
50+ */
51+public class EC2MultiRegionAddressTranslater implements CloseableAddressTranslater {
52+
53+ private static final Logger logger = LoggerFactory.getLogger(EC2MultiRegionAddressTranslater.class);
54+
55+ // TODO when we switch to Netty 4.1, we can replace this with the Netty built-in DNS client
56+ private final DirContext ctx;
57+
58+ public EC2MultiRegionAddressTranslater() {
59+ Hashtable<Object, Object> env = new Hashtable<Object, Object>();
60+ env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
61+ try {
62+ ctx = new InitialDirContext(env);
63+ } catch (NamingException e) {
64+ throw new DriverException("Could not create translater", e);
65+ }
66+ }
67+
68+ @Override
69+ public InetSocketAddress translate(InetSocketAddress socketAddress) {
70+ InetAddress address = socketAddress.getAddress();
71+ try {
72+ // InetAddress#getHostName() is supposed to perform a reverse DNS lookup, but for some reason it doesn't work
73+ // within the same EC2 region (it returns the IP address itself).
74+ // We use an alternate implementation:
75+ String domainName = lookupPtrRecord(reverse(address));
76+ if (domainName == null) {
77+ logger.warn("Found no domain name for {}, returning it as-is", address);
78+ return socketAddress;
79+ }
80+
81+ InetAddress translatedAddress = InetAddress.getByName(domainName);
82+ logger.debug("Resolved {} to {}", address, translatedAddress);
83+ return new InetSocketAddress(translatedAddress, socketAddress.getPort());
84+ } catch (Exception e) {
85+ logger.warn("Error resolving " + address + ", returning it as-is", e);
86+ return socketAddress;
87+ }
88+ }
89+
90+ private String lookupPtrRecord(String reversedDomain) throws Exception {
91+ Attributes attrs = ctx.getAttributes(reversedDomain, new String[]{ "PTR" });
92+ for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) {
93+ Attribute attr = (Attribute)ae.next();
94+ for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); )
95+ return vals.nextElement().toString();
96+ }
97+ return null;
98+ }
99+
100+ public void close() {
101+ try {
102+ ctx.close();
103+ } catch (NamingException e) {
104+ logger.warn("Error closing translater", e);
105+ }
106+ }
107+
108+ // Builds the "reversed" domain name in the ARPA domain to perform the reverse lookup
109+ @VisibleForTesting
110+ static String reverse(InetAddress address) {
111+ byte[] bytes = address.getAddress();
112+ if (bytes.length == 4)
113+ return reverseIpv4(bytes);
114+ else
115+ return reverseIpv6(bytes);
116+ }
117+
118+ private static String reverseIpv4(byte[] bytes) {
119+ StringBuilder builder = new StringBuilder();
120+ for (int i = bytes.length - 1; i >= 0; i--) {
121+ builder.append(bytes[i] & 0xFF).append('.');
122+ }
123+ builder.append("in-addr.arpa");
124+ return builder.toString();
125+ }
126+
127+ private static String reverseIpv6(byte[] bytes) {
128+ StringBuilder builder = new StringBuilder();
129+ for (int i = bytes.length - 1; i >= 0; i--) {
130+ byte b = bytes[i];
131+ int lowNibble = b & 0x0F;
132+ int highNibble = b >> 4 & 0x0F;
133+ builder.append(Integer.toHexString(lowNibble)).append('.')
134+ .append(Integer.toHexString(highNibble)).append('.');
135+ }
136+ builder.append("ip6.arpa");
137+ return builder.toString();
138+ }
139+}
added driver-core/src/test/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslaterTest.java +30 −0
@@ -0,0 +1,30 @@
1+package com.datastax.driver.core.policies;
2+
3+import java.net.InetAddress;
4+import java.net.InetSocketAddress;
5+
6+import org.testng.annotations.Test;
7+
8+import static org.assertj.core.api.Assertions.assertThat;
9+
10+public class EC2MultiRegionAddressTranslaterTest {
11+ @Test(groups = "unit")
12+ public void should_build_reversed_domain_name_for_ip_v4() throws Exception {
13+ InetAddress address = InetAddress.getByName("192.0.2.5");
14+ assertThat(
15+ EC2MultiRegionAddressTranslater.reverse(address)
16+ ).isEqualTo(
17+ "5.2.0.192.in-addr.arpa"
18+ );
19+ }
20+
21+ @Test(groups = "unit")
22+ public void should_build_reversed_domain_name_for_ip_v6() throws Exception {
23+ InetAddress address = InetAddress.getByName("2001:db8::567:89ab");
24+ assertThat(
25+ EC2MultiRegionAddressTranslater.reverse(address)
26+ ).isEqualTo(
27+ "b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa"
28+ );
29+ }
30+}
No newline at the end of the file