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