001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to you under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.hadoop.hbase.util;
018
019import java.lang.reflect.Method;
020import java.net.UnknownHostException;
021
022import org.apache.yetus.audience.InterfaceAudience;
023
024/**
025 * Wrapper around Hadoop's DNS class to hide reflection.
026 */
027@InterfaceAudience.Private
028@edu.umd.cs.findbugs.annotations.SuppressWarnings(value="REC_CATCH_EXCEPTION",
029  justification="If exception, presume HAS_NEW_DNS_GET_DEFAULT_HOST_API false")
030public final class DNS {
031  private static boolean HAS_NEW_DNS_GET_DEFAULT_HOST_API;
032  private static Method GET_DEFAULT_HOST_METHOD;
033
034  static {
035    try {
036      GET_DEFAULT_HOST_METHOD = org.apache.hadoop.net.DNS.class
037          .getMethod("getDefaultHost", String.class, String.class, boolean.class);
038      HAS_NEW_DNS_GET_DEFAULT_HOST_API = true;
039    } catch (Exception e) {
040      HAS_NEW_DNS_GET_DEFAULT_HOST_API = false; // FindBugs: Causes REC_CATCH_EXCEPTION. Suppressed
041    }
042  }
043
044  private DNS() {}
045
046  /**
047   * Wrapper around DNS.getDefaultHost(String, String), calling
048   * DNS.getDefaultHost(String, String, boolean) when available.
049   *
050   * @param strInterface The network interface to query.
051   * @param nameserver The DNS host name.
052   * @return The default host names associated with IPs bound to the network interface.
053   */
054  public static String getDefaultHost(String strInterface, String nameserver)
055      throws UnknownHostException {
056    if (HAS_NEW_DNS_GET_DEFAULT_HOST_API) {
057      try {
058        // Hadoop-2.8 includes a String, String, boolean variant of getDefaultHost
059        // which properly handles multi-homed systems with Kerberos.
060        return (String) GET_DEFAULT_HOST_METHOD.invoke(null, strInterface, nameserver, true);
061      } catch (Exception e) {
062        // If we can't invoke the method as it should exist, throw an exception
063        throw new RuntimeException("Failed to invoke DNS.getDefaultHost via reflection", e);
064      }
065    } else {
066      return org.apache.hadoop.net.DNS.getDefaultHost(strInterface, nameserver);
067    }
068  }
069}