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