package com.datastax.oss.driver.internal.core.metadata;
import com.datastax.oss.driver.api.core.metadata.EndPoint;
import com.datastax.oss.driver.shaded.guava.common.primitives.UnsignedBytes;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
public class SniEndPoint implements EndPoint {
private static final AtomicLong OFFSET = new AtomicLong();
private final InetSocketAddress proxyAddress;
private final String serverName;
public SniEndPoint(InetSocketAddress proxyAddress, String serverName) {
this.proxyAddress = Objects.requireNonNull(proxyAddress, "SNI address cannot be null");
this.serverName = Objects.requireNonNull(serverName, "SNI Server name cannot be null");
}
public String getServerName() {
return serverName;
}
@Override
public InetSocketAddress resolve() {
try {
InetAddress[] aRecords = InetAddress.getAllByName(proxyAddress.getHostName());
if (aRecords.length == 0) {
throw new IllegalArgumentException(
"Could not resolve proxy address " + proxyAddress.getHostName());
}
Arrays.sort(aRecords, IP_COMPARATOR);
int index = (aRecords.length == 1) ? 0 : (int) OFFSET.getAndIncrement() % aRecords.length;
return new InetSocketAddress(aRecords[index], proxyAddress.getPort());
} catch (UnknownHostException e) {
throw new IllegalArgumentException(
"Could not resolve proxy address " + proxyAddress.getHostName(), e);
}
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (other instanceof SniEndPoint) {
SniEndPoint that = (SniEndPoint) other;
return this.proxyAddress.equals(that.proxyAddress) && this.serverName.equals(that.serverName);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(proxyAddress, serverName);
}
@Override
public String toString() {
return proxyAddress.toString() + ":" + serverName;
}
@Override
public String asMetricPrefix() {
String hostString = proxyAddress.getHostString();
if (hostString == null) {
throw new IllegalArgumentException(
"Could not extract a host string from provided proxy address " + proxyAddress);
}
return hostString.replace('.', '_') + ':' + proxyAddress.getPort() + '_' + serverName;
}
private static final Comparator<InetAddress> IP_COMPARATOR =
(InetAddress address1, InetAddress address2) ->
UnsignedBytes.lexicographicalComparator()
.compare(address1.getAddress(), address2.getAddress());
}