|
| 1 | +/* |
| 2 | + * Copyright 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.oss.driver.internal.core.addresstranslation; |
| 17 | + |
| 18 | +import com.datastax.oss.driver.api.core.addresstranslation.AddressTranslator; |
| 19 | +import com.datastax.oss.driver.api.core.context.DriverContext; |
| 20 | +import com.datastax.oss.driver.internal.core.util.Loggers; |
| 21 | +import com.datastax.oss.driver.shaded.guava.common.annotations.VisibleForTesting; |
| 22 | +import java.net.InetAddress; |
| 23 | +import java.net.InetSocketAddress; |
| 24 | +import java.util.Enumeration; |
| 25 | +import java.util.Hashtable; |
| 26 | +import javax.naming.Context; |
| 27 | +import javax.naming.NamingEnumeration; |
| 28 | +import javax.naming.NamingException; |
| 29 | +import javax.naming.directory.Attribute; |
| 30 | +import javax.naming.directory.Attributes; |
| 31 | +import javax.naming.directory.DirContext; |
| 32 | +import javax.naming.directory.InitialDirContext; |
| 33 | +import org.slf4j.Logger; |
| 34 | +import org.slf4j.LoggerFactory; |
| 35 | + |
| 36 | +/** |
| 37 | + * {@link AddressTranslator} implementation for a multi-region EC2 deployment <b>where clients are |
| 38 | + * also deployed in EC2</b>. |
| 39 | + * |
| 40 | + * <p>Its distinctive feature is that it translates addresses according to the location of the |
| 41 | + * Cassandra host: |
| 42 | + * |
| 43 | + * <ul> |
| 44 | + * <li>addresses in different EC2 regions (than the client) are unchanged; |
| 45 | + * <li>addresses in the same EC2 region are <b>translated to private IPs</b>. |
| 46 | + * </ul> |
| 47 | + * |
| 48 | + * This optimizes network costs, because Amazon charges more for communication over public IPs. |
| 49 | + * |
| 50 | + * <p>Implementation note: this class performs a reverse DNS lookup of the origin address, to find |
| 51 | + * the domain name of the target instance. Then it performs a forward DNS lookup of the domain name; |
| 52 | + * the EC2 DNS does the private/public switch automatically based on location. |
| 53 | + */ |
| 54 | +public class Ec2MultiRegionAddressTranslator implements AddressTranslator { |
| 55 | + |
| 56 | + private static final Logger LOG = LoggerFactory.getLogger(Ec2MultiRegionAddressTranslator.class); |
| 57 | + |
| 58 | + private final DirContext ctx; |
| 59 | + private final String logPrefix; |
| 60 | + |
| 61 | + public Ec2MultiRegionAddressTranslator(@SuppressWarnings("unused") DriverContext context) { |
| 62 | + this.logPrefix = context.sessionName(); |
| 63 | + @SuppressWarnings("JdkObsolete") |
| 64 | + Hashtable<Object, Object> env = new Hashtable<>(); |
| 65 | + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); |
| 66 | + try { |
| 67 | + ctx = new InitialDirContext(env); |
| 68 | + } catch (NamingException e) { |
| 69 | + throw new RuntimeException("Could not create translator", e); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + @VisibleForTesting |
| 74 | + Ec2MultiRegionAddressTranslator(DirContext ctx) { |
| 75 | + this.logPrefix = "test"; |
| 76 | + this.ctx = ctx; |
| 77 | + } |
| 78 | + |
| 79 | + @Override |
| 80 | + public InetSocketAddress translate(InetSocketAddress socketAddress) { |
| 81 | + InetAddress address = socketAddress.getAddress(); |
| 82 | + try { |
| 83 | + // InetAddress#getHostName() is supposed to perform a reverse DNS lookup, but for some reason |
| 84 | + // it doesn't work within the same EC2 region (it returns the IP address itself). |
| 85 | + // We use an alternate implementation: |
| 86 | + String domainName = lookupPtrRecord(reverse(address)); |
| 87 | + if (domainName == null) { |
| 88 | + LOG.warn("[{}] Found no domain name for {}, returning it as-is", logPrefix, address); |
| 89 | + return socketAddress; |
| 90 | + } |
| 91 | + |
| 92 | + InetAddress translatedAddress = InetAddress.getByName(domainName); |
| 93 | + LOG.debug("[{}] Resolved {} to {}", logPrefix, address, translatedAddress); |
| 94 | + return new InetSocketAddress(translatedAddress, socketAddress.getPort()); |
| 95 | + } catch (Exception e) { |
| 96 | + Loggers.warnWithException( |
| 97 | + LOG, "[{}] Error resolving {}, returning it as-is", logPrefix, address, e); |
| 98 | + return socketAddress; |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + private String lookupPtrRecord(String reversedDomain) throws Exception { |
| 103 | + Attributes attrs = ctx.getAttributes(reversedDomain, new String[] {"PTR"}); |
| 104 | + for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) { |
| 105 | + Attribute attr = (Attribute) ae.next(); |
| 106 | + Enumeration<?> vals = attr.getAll(); |
| 107 | + if (vals.hasMoreElements()) { |
| 108 | + return vals.nextElement().toString(); |
| 109 | + } |
| 110 | + } |
| 111 | + return null; |
| 112 | + } |
| 113 | + |
| 114 | + @Override |
| 115 | + public void close() { |
| 116 | + try { |
| 117 | + ctx.close(); |
| 118 | + } catch (NamingException e) { |
| 119 | + Loggers.warnWithException(LOG, "Error closing translator", e); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + // Builds the "reversed" domain name in the ARPA domain to perform the reverse lookup |
| 124 | + @VisibleForTesting |
| 125 | + static String reverse(InetAddress address) { |
| 126 | + byte[] bytes = address.getAddress(); |
| 127 | + if (bytes.length == 4) return reverseIpv4(bytes); |
| 128 | + else return reverseIpv6(bytes); |
| 129 | + } |
| 130 | + |
| 131 | + private static String reverseIpv4(byte[] bytes) { |
| 132 | + StringBuilder builder = new StringBuilder(); |
| 133 | + for (int i = bytes.length - 1; i >= 0; i--) { |
| 134 | + builder.append(bytes[i] & 0xFF).append('.'); |
| 135 | + } |
| 136 | + builder.append("in-addr.arpa"); |
| 137 | + return builder.toString(); |
| 138 | + } |
| 139 | + |
| 140 | + private static String reverseIpv6(byte[] bytes) { |
| 141 | + StringBuilder builder = new StringBuilder(); |
| 142 | + for (int i = bytes.length - 1; i >= 0; i--) { |
| 143 | + byte b = bytes[i]; |
| 144 | + int lowNibble = b & 0x0F; |
| 145 | + int highNibble = b >> 4 & 0x0F; |
| 146 | + builder |
| 147 | + .append(Integer.toHexString(lowNibble)) |
| 148 | + .append('.') |
| 149 | + .append(Integer.toHexString(highNibble)) |
| 150 | + .append('.'); |
| 151 | + } |
| 152 | + builder.append("ip6.arpa"); |
| 153 | + return builder.toString(); |
| 154 | + } |
| 155 | +} |
0 commit comments