1 /*
2 * Copyright 2016 The Netty Project
3 *
4 * The Netty Project licenses this file to you under the Apache License,
5 * version 2.0 (the "License"); you may not use this file except in compliance
6 * with the License. You may obtain a copy of the License at:
7 *
8 * https://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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package io.netty.resolver;
17
18 import io.netty.util.concurrent.EventExecutor;
19 import io.netty.util.concurrent.Future;
20 import io.netty.util.concurrent.FutureListener;
21 import io.netty.util.concurrent.Promise;
22
23 import java.net.InetAddress;
24 import java.net.InetSocketAddress;
25 import java.net.UnknownHostException;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.concurrent.ThreadLocalRandom;
30
31 /**
32 * A {@link NameResolver} that resolves {@link InetAddress} and force Round Robin by choosing a single address
33 * randomly in {@link #resolve(String)} and {@link #resolve(String, Promise)}
34 * if multiple are returned by the {@link NameResolver}.
35 * Use {@link #asAddressResolver()} to create a {@link InetSocketAddress} resolver
36 */
37 public class RoundRobinInetAddressResolver extends InetNameResolver {
38 private final NameResolver<InetAddress> nameResolver;
39
40 /**
41 * @param executor the {@link EventExecutor} which is used to notify the listeners of the {@link Future} returned by
42 * {@link #resolve(String)}
43 * @param nameResolver the {@link NameResolver} used for name resolution
44 */
45 public RoundRobinInetAddressResolver(EventExecutor executor, NameResolver<InetAddress> nameResolver) {
46 super(executor);
47 this.nameResolver = nameResolver;
48 }
49
50 @Override
51 protected void doResolve(final String inetHost, final Promise<InetAddress> promise) throws Exception {
52 // hijack the doResolve request, but do a doResolveAll request under the hood.
53 // Note that InetSocketAddress.getHostName() will never incur a reverse lookup here,
54 // because an unresolved address always has a host name.
55 nameResolver.resolveAll(inetHost).addListener((FutureListener<List<InetAddress>>) future -> {
56 if (future.isSuccess()) {
57 List<InetAddress> inetAddresses = future.getNow();
58 int numAddresses = inetAddresses.size();
59 if (numAddresses > 0) {
60 // if there are multiple addresses: we shall pick one by one
61 // to support the round robin distribution
62 promise.setSuccess(inetAddresses.get(randomIndex(numAddresses)));
63 } else {
64 promise.setFailure(new UnknownHostException(inetHost));
65 }
66 } else {
67 promise.setFailure(future.cause());
68 }
69 });
70 }
71
72 @Override
73 protected void doResolveAll(String inetHost, final Promise<List<InetAddress>> promise) throws Exception {
74 nameResolver.resolveAll(inetHost).addListener((FutureListener<List<InetAddress>>) future -> {
75 if (future.isSuccess()) {
76 List<InetAddress> inetAddresses = future.getNow();
77 if (!inetAddresses.isEmpty()) {
78 // create a copy to make sure that it's modifiable random access collection
79 List<InetAddress> result = new ArrayList<InetAddress>(inetAddresses);
80 // rotate by different distance each time to force round robin distribution
81 Collections.rotate(result, randomIndex(inetAddresses.size()));
82 promise.setSuccess(result);
83 } else {
84 promise.setSuccess(inetAddresses);
85 }
86 } else {
87 promise.setFailure(future.cause());
88 }
89 });
90 }
91
92 private static int randomIndex(int numAddresses) {
93 return numAddresses == 1 ? 0 : ThreadLocalRandom.current().nextInt(numAddresses);
94 }
95
96 @Override
97 public void close() {
98 nameResolver.close();
99 }
100 }