View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase;
19  
20  import java.io.IOException;
21  import java.lang.reflect.InvocationTargetException;
22  import java.lang.reflect.Method;
23  import java.util.Map.Entry;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.hbase.classification.InterfaceStability;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.hbase.util.VersionInfo;
31  
32  /**
33   * Adds HBase configuration files to a Configuration
34   */
35  @InterfaceAudience.Public
36  @InterfaceStability.Stable
37  public class HBaseConfiguration extends Configuration {
38  
39    private static final Log LOG = LogFactory.getLog(HBaseConfiguration.class);
40  
41    // a constant to convert a fraction to a percentage
42    private static final int CONVERT_TO_PERCENTAGE = 100;
43  
44    /**
45     * Instantinating HBaseConfiguration() is deprecated. Please use
46     * HBaseConfiguration#create() to construct a plain Configuration
47     */
48    @Deprecated
49    public HBaseConfiguration() {
50      //TODO:replace with private constructor, HBaseConfiguration should not extend Configuration
51      super();
52      addHbaseResources(this);
53      LOG.warn("instantiating HBaseConfiguration() is deprecated. Please use"
54          + " HBaseConfiguration#create() to construct a plain Configuration");
55    }
56  
57    /**
58     * Instantiating HBaseConfiguration() is deprecated. Please use
59     * HBaseConfiguration#create(conf) to construct a plain Configuration
60     */
61    @Deprecated
62    public HBaseConfiguration(final Configuration c) {
63      //TODO:replace with private constructor
64      this();
65      merge(this, c);
66    }
67  
68    private static void checkDefaultsVersion(Configuration conf) {
69      if (conf.getBoolean("hbase.defaults.for.version.skip", Boolean.FALSE)) return;
70      String defaultsVersion = conf.get("hbase.defaults.for.version");
71      String thisVersion = VersionInfo.getVersion();
72      if (!thisVersion.equals(defaultsVersion)) {
73        throw new RuntimeException(
74          "hbase-default.xml file seems to be for and old version of HBase (" +
75          defaultsVersion + "), this version is " + thisVersion);
76      }
77    }
78  
79    private static void checkForClusterFreeMemoryLimit(Configuration conf) {
80        float globalMemstoreLimit = conf.getFloat("hbase.regionserver.global.memstore.upperLimit", 0.4f);
81        int gml = (int)(globalMemstoreLimit * CONVERT_TO_PERCENTAGE);
82        float blockCacheUpperLimit =
83          conf.getFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY,
84            HConstants.HFILE_BLOCK_CACHE_SIZE_DEFAULT);
85        int bcul = (int)(blockCacheUpperLimit * CONVERT_TO_PERCENTAGE);
86        if (CONVERT_TO_PERCENTAGE - (gml + bcul)
87                < (int)(CONVERT_TO_PERCENTAGE *
88                        HConstants.HBASE_CLUSTER_MINIMUM_MEMORY_THRESHOLD)) {
89            throw new RuntimeException(
90              "Current heap configuration for MemStore and BlockCache exceeds " +
91              "the threshold required for successful cluster operation. " +
92              "The combined value cannot exceed 0.8. Please check " +
93              "the settings for hbase.regionserver.global.memstore.upperLimit and " +
94              "hfile.block.cache.size in your configuration. " +
95              "hbase.regionserver.global.memstore.upperLimit is " +
96              globalMemstoreLimit +
97              " hfile.block.cache.size is " + blockCacheUpperLimit);
98        }
99    }
100 
101   public static Configuration addHbaseResources(Configuration conf) {
102     conf.addResource("hbase-default.xml");
103     conf.addResource("hbase-site.xml");
104 
105     checkDefaultsVersion(conf);
106     checkForClusterFreeMemoryLimit(conf);
107     return conf;
108   }
109 
110   /**
111    * Creates a Configuration with HBase resources
112    * @return a Configuration with HBase resources
113    */
114   public static Configuration create() {
115     Configuration conf = new Configuration();
116     return addHbaseResources(conf);
117   }
118 
119   /**
120    * @param that Configuration to clone.
121    * @return a Configuration created with the hbase-*.xml files plus
122    * the given configuration.
123    */
124   public static Configuration create(final Configuration that) {
125     Configuration conf = create();
126     merge(conf, that);
127     return conf;
128   }
129 
130   /**
131    * Merge two configurations.
132    * @param destConf the configuration that will be overwritten with items
133    *                 from the srcConf
134    * @param srcConf the source configuration
135    **/
136   public static void merge(Configuration destConf, Configuration srcConf) {
137     for (Entry<String, String> e : srcConf) {
138       destConf.set(e.getKey(), e.getValue());
139     }
140   }
141 
142   /**
143    * @return whether to show HBase Configuration in servlet
144    */
145   public static boolean isShowConfInServlet() {
146     boolean isShowConf = false;
147     try {
148       if (Class.forName("org.apache.hadoop.conf.ConfServlet") != null) {
149         isShowConf = true;
150       }
151     } catch (LinkageError e) {
152        // should we handle it more aggressively in addition to log the error?
153        LOG.warn("Error thrown: ", e);
154     } catch (ClassNotFoundException ce) {
155       LOG.debug("ClassNotFound: ConfServlet");
156       // ignore
157     }
158     return isShowConf;
159   }
160 
161   /**
162    * Get the value of the <code>name</code> property as an <code>int</code>, possibly
163    * referring to the deprecated name of the configuration property.
164    * If no such property exists, the provided default value is returned,
165    * or if the specified value is not a valid <code>int</code>,
166    * then an error is thrown.
167    *
168    * @param name property name.
169    * @param deprecatedName a deprecatedName for the property to use
170    * if non-deprecated name is not used
171    * @param defaultValue default value.
172    * @throws NumberFormatException when the value is invalid
173    * @return property value as an <code>int</code>,
174    *         or <code>defaultValue</code>.
175    */
176   // TODO: developer note: This duplicates the functionality of deprecated
177   // property support in Configuration in Hadoop 2. But since Hadoop-1 does not
178   // contain these changes, we will do our own as usual. Replace these when H2 is default.
179   public static int getInt(Configuration conf, String name,
180       String deprecatedName, int defaultValue) {
181     if (conf.get(deprecatedName) != null) {
182       LOG.warn(String.format("Config option \"%s\" is deprecated. Instead, use \"%s\""
183         , deprecatedName, name));
184       return conf.getInt(deprecatedName, defaultValue);
185     } else {
186       return conf.getInt(name, defaultValue);
187     }
188   }
189 
190   /**
191    * Get the password from the Configuration instance using the
192    * getPassword method if it exists. If not, then fall back to the
193    * general get method for configuration elements.
194    * @param conf configuration instance for accessing the passwords
195    * @param alias the name of the password element
196    * @param defPass the default password
197    * @return String password or default password
198    * @throws IOException
199    */
200   public static String getPassword(Configuration conf, String alias,
201       String defPass) throws IOException {
202     String passwd = null;
203     try {
204       Method m = Configuration.class.getMethod("getPassword", String.class);
205       char[] p = (char[]) m.invoke(conf, alias);
206       if (p != null) {
207         LOG.debug(String.format("Config option \"%s\" was found through" +
208         		" the Configuration getPassword method.", alias));
209         passwd = new String(p);
210       }
211       else {
212         LOG.debug(String.format(
213             "Config option \"%s\" was not found. Using provided default value",
214             alias));
215         passwd = defPass;
216       }
217     } catch (NoSuchMethodException e) {
218       // this is a version of Hadoop where the credential
219       //provider API doesn't exist yet
220       LOG.debug(String.format(
221           "Credential.getPassword method is not available." +
222           " Falling back to configuration."));
223       passwd = conf.get(alias, defPass);
224     } catch (SecurityException e) {
225       throw new IOException(e.getMessage(), e);
226     } catch (IllegalAccessException e) {
227       throw new IOException(e.getMessage(), e);
228     } catch (IllegalArgumentException e) {
229       throw new IOException(e.getMessage(), e);
230     } catch (InvocationTargetException e) {
231       throw new IOException(e.getMessage(), e);
232     }
233     return passwd;
234   }
235 
236   /** For debugging.  Dump configurations to system output as xml format.
237    * Master and RS configurations can also be dumped using
238    * http services. e.g. "curl http://master:60010/dump"
239    */
240   public static void main(String[] args) throws Exception {
241     HBaseConfiguration.create().writeXml(System.out);
242   }
243 }