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;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.conf.Configuration;
28  import org.apache.hadoop.hbase.classification.InterfaceAudience;
29  import org.apache.hadoop.hbase.classification.InterfaceStability;
30  import org.apache.hadoop.hbase.io.util.HeapMemorySizeUtil;
31  import org.apache.hadoop.hbase.util.VersionInfo;
32  import org.apache.hadoop.hbase.zookeeper.ZKConfig;
33  
34  /**
35   * Adds HBase configuration files to a Configuration
36   */
37  @InterfaceAudience.Public
38  @InterfaceStability.Stable
39  public class HBaseConfiguration extends Configuration {
40    private static final Log LOG = LogFactory.getLog(HBaseConfiguration.class);
41  
42    /**
43     * Instantiating HBaseConfiguration() is deprecated. Please use
44     * HBaseConfiguration#create() to construct a plain Configuration
45     * @deprecated Please use create() instead.
46     */
47    @Deprecated
48    public HBaseConfiguration() {
49      //TODO:replace with private constructor, HBaseConfiguration should not extend Configuration
50      super();
51      addHbaseResources(this);
52      LOG.warn("instantiating HBaseConfiguration() is deprecated. Please use"
53          + " HBaseConfiguration#create() to construct a plain Configuration");
54    }
55  
56    /**
57     * Instantiating HBaseConfiguration() is deprecated. Please use
58     * HBaseConfiguration#create(conf) to construct a plain Configuration
59     * @deprecated Please user create(conf) instead.
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 an older version of HBase (" +
75          defaultsVersion + "), this version is " + thisVersion);
76      }
77    }
78  
79    public static Configuration addHbaseResources(Configuration conf) {
80      conf.addResource("hbase-default.xml");
81      conf.addResource("hbase-site.xml");
82  
83      checkDefaultsVersion(conf);
84      HeapMemorySizeUtil.checkForClusterFreeMemoryLimit(conf);
85      return conf;
86    }
87  
88    /**
89     * Creates a Configuration with HBase resources
90     * @return a Configuration with HBase resources
91     */
92    public static Configuration create() {
93      Configuration conf = new Configuration();
94      // In case HBaseConfiguration is loaded from a different classloader than
95      // Configuration, conf needs to be set with appropriate class loader to resolve
96      // HBase resources.
97      conf.setClassLoader(HBaseConfiguration.class.getClassLoader());
98      return addHbaseResources(conf);
99    }
100 
101   /**
102    * @param that Configuration to clone.
103    * @return a Configuration created with the hbase-*.xml files plus
104    * the given configuration.
105    */
106   public static Configuration create(final Configuration that) {
107     Configuration conf = create();
108     merge(conf, that);
109     return conf;
110   }
111 
112   /**
113    * Merge two configurations.
114    * @param destConf the configuration that will be overwritten with items
115    *                 from the srcConf
116    * @param srcConf the source configuration
117    **/
118   public static void merge(Configuration destConf, Configuration srcConf) {
119     for (Map.Entry<String, String> e : srcConf) {
120       destConf.set(e.getKey(), e.getValue());
121     }
122   }
123 
124   /**
125    * Returns a subset of the configuration properties, matching the given key prefix.
126    * The prefix is stripped from the return keys, ie. when calling with a prefix of "myprefix",
127    * the entry "myprefix.key1 = value1" would be returned as "key1 = value1".  If an entry's
128    * key matches the prefix exactly ("myprefix = value2"), it will <strong>not</strong> be
129    * included in the results, since it would show up as an entry with an empty key.
130    */
131   public static Configuration subset(Configuration srcConf, String prefix) {
132     Configuration newConf = new Configuration(false);
133     for (Map.Entry<String, String> entry : srcConf) {
134       if (entry.getKey().startsWith(prefix)) {
135         String newKey = entry.getKey().substring(prefix.length());
136         // avoid entries that would produce an empty key
137         if (!newKey.isEmpty()) {
138           newConf.set(newKey, entry.getValue());
139         }
140       }
141     }
142     return newConf;
143   }
144 
145   /**
146    * Sets all the entries in the provided {@code Map<String, String>} as properties in the
147    * given {@code Configuration}.  Each property will have the specified prefix prepended,
148    * so that the configuration entries are keyed by {@code prefix + entry.getKey()}.
149    */
150   public static void setWithPrefix(Configuration conf, String prefix,
151                                    Iterable<Map.Entry<String, String>> properties) {
152     for (Map.Entry<String, String> entry : properties) {
153       conf.set(prefix + entry.getKey(), entry.getValue());
154     }
155   }
156 
157   /**
158    * @return whether to show HBase Configuration in servlet
159    */
160   public static boolean isShowConfInServlet() {
161     boolean isShowConf = false;
162     try {
163       if (Class.forName("org.apache.hadoop.conf.ConfServlet") != null) {
164         isShowConf = true;
165       }
166     } catch (LinkageError e) {
167        // should we handle it more aggressively in addition to log the error?
168        LOG.warn("Error thrown: ", e);
169     } catch (ClassNotFoundException ce) {
170       LOG.debug("ClassNotFound: ConfServlet");
171       // ignore
172     }
173     return isShowConf;
174   }
175 
176   /**
177    * Get the value of the <code>name</code> property as an <code>int</code>, possibly
178    * referring to the deprecated name of the configuration property.
179    * If no such property exists, the provided default value is returned,
180    * or if the specified value is not a valid <code>int</code>,
181    * then an error is thrown.
182    *
183    * @param name property name.
184    * @param deprecatedName a deprecatedName for the property to use
185    * if non-deprecated name is not used
186    * @param defaultValue default value.
187    * @throws NumberFormatException when the value is invalid
188    * @return property value as an <code>int</code>,
189    *         or <code>defaultValue</code>.
190    */
191   // TODO: developer note: This duplicates the functionality of deprecated
192   // property support in Configuration in Hadoop 2. But since Hadoop-1 does not
193   // contain these changes, we will do our own as usual. Replace these when H2 is default.
194   public static int getInt(Configuration conf, String name,
195       String deprecatedName, int defaultValue) {
196     if (conf.get(deprecatedName) != null) {
197       LOG.warn(String.format("Config option \"%s\" is deprecated. Instead, use \"%s\""
198         , deprecatedName, name));
199       return conf.getInt(deprecatedName, defaultValue);
200     } else {
201       return conf.getInt(name, defaultValue);
202     }
203   }
204 
205   /**
206    * Get the password from the Configuration instance using the
207    * getPassword method if it exists. If not, then fall back to the
208    * general get method for configuration elements.
209    *
210    * @param conf    configuration instance for accessing the passwords
211    * @param alias   the name of the password element
212    * @param defPass the default password
213    * @return String password or default password
214    * @throws IOException
215    */
216   public static String getPassword(Configuration conf, String alias,
217       String defPass) throws IOException {
218     String passwd = null;
219     try {
220       Method m = Configuration.class.getMethod("getPassword", String.class);
221       char[] p = (char[]) m.invoke(conf, alias);
222       if (p != null) {
223         LOG.debug(String.format("Config option \"%s\" was found through" +
224             " the Configuration getPassword method.", alias));
225         passwd = new String(p);
226       } else {
227         LOG.debug(String.format(
228             "Config option \"%s\" was not found. Using provided default value",
229             alias));
230         passwd = defPass;
231       }
232     } catch (NoSuchMethodException e) {
233       // this is a version of Hadoop where the credential
234       //provider API doesn't exist yet
235       LOG.debug(String.format(
236           "Credential.getPassword method is not available." +
237               " Falling back to configuration."));
238       passwd = conf.get(alias, defPass);
239     } catch (SecurityException e) {
240       throw new IOException(e.getMessage(), e);
241     } catch (IllegalAccessException e) {
242       throw new IOException(e.getMessage(), e);
243     } catch (IllegalArgumentException e) {
244       throw new IOException(e.getMessage(), e);
245     } catch (InvocationTargetException e) {
246       throw new IOException(e.getMessage(), e);
247     }
248     return passwd;
249   }
250 
251   /**
252    * Generates a {@link Configuration} instance by applying the ZooKeeper cluster key
253    * to the base Configuration.  Note that additional configuration properties may be needed
254    * for a remote cluster, so it is preferable to use
255    * {@link #createClusterConf(Configuration, String, String)}.
256    *
257    * @param baseConf the base configuration to use, containing prefixed override properties
258    * @param clusterKey the ZooKeeper quorum cluster key to apply, or {@code null} if none
259    *
260    * @return the merged configuration with override properties and cluster key applied
261    *
262    * @see #createClusterConf(Configuration, String, String)
263    */
264   public static Configuration createClusterConf(Configuration baseConf, String clusterKey)
265       throws IOException {
266     return createClusterConf(baseConf, clusterKey, null);
267   }
268 
269   /**
270    * Generates a {@link Configuration} instance by applying property overrides prefixed by
271    * a cluster profile key to the base Configuration.  Override properties are extracted by
272    * the {@link #subset(Configuration, String)} method, then the merged on top of the base
273    * Configuration and returned.
274    *
275    * @param baseConf the base configuration to use, containing prefixed override properties
276    * @param clusterKey the ZooKeeper quorum cluster key to apply, or {@code null} if none
277    * @param overridePrefix the property key prefix to match for override properties,
278    *     or {@code null} if none
279    * @return the merged configuration with override properties and cluster key applied
280    */
281   public static Configuration createClusterConf(Configuration baseConf, String clusterKey,
282                                                 String overridePrefix) throws IOException {
283     Configuration clusterConf = HBaseConfiguration.create(baseConf);
284     if (clusterKey != null && !clusterKey.isEmpty()) {
285       applyClusterKeyToConf(clusterConf, clusterKey);
286     }
287 
288     if (overridePrefix != null && !overridePrefix.isEmpty()) {
289       Configuration clusterSubset = HBaseConfiguration.subset(clusterConf, overridePrefix);
290       HBaseConfiguration.merge(clusterConf, clusterSubset);
291     }
292     return clusterConf;
293   }
294 
295   /**
296    * Apply the settings in the given key to the given configuration, this is
297    * used to communicate with distant clusters
298    * @param conf configuration object to configure
299    * @param key string that contains the 3 required configuratins
300    * @throws IOException
301    */
302   private static void applyClusterKeyToConf(Configuration conf, String key)
303       throws IOException{
304     ZKConfig.ZKClusterKey zkClusterKey = ZKConfig.transformClusterKey(key);
305     conf.set(HConstants.ZOOKEEPER_QUORUM, zkClusterKey.getQuorumString());
306     conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, zkClusterKey.getClientPort());
307     conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, zkClusterKey.getZnodeParent());
308   }
309 
310   /**
311    * For debugging.  Dump configurations to system output as xml format.
312    * Master and RS configurations can also be dumped using
313    * http services. e.g. "curl http://master:16010/dump"
314    */
315   public static void main(String[] args) throws Exception {
316     HBaseConfiguration.create().writeXml(System.out);
317   }
318 }