View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to you under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.hadoop.hbase.util;
18  
19  import java.lang.reflect.Method;
20  import java.net.UnknownHostException;
21  
22  import org.apache.hadoop.hbase.classification.InterfaceAudience;
23  
24  /**
25   * Wrapper around Hadoop's DNS class to hide reflection.
26   */
27  @InterfaceAudience.Private
28  public class DNS {
29    private static boolean HAS_NEW_DNS_GET_DEFAULT_HOST_API;
30    private static Method GET_DEFAULT_HOST_METHOD;
31  
32    static {
33      try {
34        GET_DEFAULT_HOST_METHOD = org.apache.hadoop.net.DNS.class
35            .getMethod("getDefaultHost", String.class, String.class, boolean.class);
36        HAS_NEW_DNS_GET_DEFAULT_HOST_API = true;
37      } catch (Exception e) {
38        HAS_NEW_DNS_GET_DEFAULT_HOST_API = false;
39      }
40    }
41    
42    private DNS() {}
43  
44    /**
45     * @see org.apache.hadoop.net.DNS#getDefaultHost(String, String)
46     */
47    public static String getDefaultHost(String strInterface, String nameserver)
48        throws UnknownHostException {
49      if (HAS_NEW_DNS_GET_DEFAULT_HOST_API) {
50        try {
51          // Hadoop-2.8 includes a String, String, boolean variant of getDefaultHost
52          // which properly handles multi-homed systems with Kerberos.
53          return (String) GET_DEFAULT_HOST_METHOD.invoke(null, strInterface, nameserver, true);
54        } catch (Exception e) {
55          // If we can't invoke the method as it should exist, throw an exception
56          throw new RuntimeException("Failed to invoke DNS.getDefaultHost via reflection", e);
57        }
58      } else {
59        return org.apache.hadoop.net.DNS.getDefaultHost(strInterface, nameserver);
60      }
61    }
62  }