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