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 referring to
182 * the deprecated name of the configuration property. If no such property exists, the provided
183 * default value is returned, or if the specified value is not a valid <code>int</code>, then an
184 * error is thrown.
185 * @param name property name.
186 * @param deprecatedName a deprecatedName for the property to use if non-deprecated name is not
187 * used
188 * @param defaultValue default value.
189 * @throws NumberFormatException when the value is invalid
190 * @return property value as an <code>int</code>, or <code>defaultValue</code>.
191 * @deprecated it will be removed in 3.0.0. Use
192 * {@link Configuration#addDeprecation(String, String)} instead.
193 */
194 @Deprecated
195 public static int getInt(Configuration conf, String name,
196 String deprecatedName, int defaultValue) {
197 if (conf.get(deprecatedName) != null) {
198 LOG.warn(String.format("Config option \"%s\" is deprecated. Instead, use \"%s\""
199 , deprecatedName, name));
200 return conf.getInt(deprecatedName, defaultValue);
201 } else {
202 return conf.getInt(name, defaultValue);
203 }
204 }
205
206 /**
207 * Get the password from the Configuration instance using the
208 * getPassword method if it exists. If not, then fall back to the
209 * general get method for configuration elements.
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 }
227 else {
228 LOG.debug(String.format(
229 "Config option \"%s\" was not found. Using provided default value",
230 alias));
231 passwd = defPass;
232 }
233 } catch (NoSuchMethodException e) {
234 // this is a version of Hadoop where the credential
235 //provider API doesn't exist yet
236 LOG.debug(String.format(
237 "Credential.getPassword method is not available." +
238 " Falling back to configuration."));
239 passwd = conf.get(alias, defPass);
240 } catch (SecurityException e) {
241 throw new IOException(e.getMessage(), e);
242 } catch (IllegalAccessException e) {
243 throw new IOException(e.getMessage(), e);
244 } catch (IllegalArgumentException e) {
245 throw new IOException(e.getMessage(), e);
246 } catch (InvocationTargetException e) {
247 throw new IOException(e.getMessage(), e);
248 }
249 return passwd;
250 }
251
252 /**
253 * Generates a {@link Configuration} instance by applying the ZooKeeper cluster key
254 * to the base Configuration. Note that additional configuration properties may be needed
255 * for a remote cluster, so it is preferable to use
256 * {@link #createClusterConf(Configuration, String, String)}.
257 *
258 * @param baseConf the base configuration to use, containing prefixed override properties
259 * @param clusterKey the ZooKeeper quorum cluster key to apply, or {@code null} if none
260 *
261 * @return the merged configuration with override properties and cluster key applied
262 *
263 * @see #createClusterConf(Configuration, String, String)
264 */
265 public static Configuration createClusterConf(Configuration baseConf, String clusterKey)
266 throws IOException {
267 return createClusterConf(baseConf, clusterKey, null);
268 }
269
270 /**
271 * Generates a {@link Configuration} instance by applying property overrides prefixed by
272 * a cluster profile key to the base Configuration. Override properties are extracted by
273 * the {@link #subset(Configuration, String)} method, then the merged on top of the base
274 * Configuration and returned.
275 *
276 * @param baseConf the base configuration to use, containing prefixed override properties
277 * @param clusterKey the ZooKeeper quorum cluster key to apply, or {@code null} if none
278 * @param overridePrefix the property key prefix to match for override properties,
279 * or {@code null} if none
280 * @return the merged configuration with override properties and cluster key applied
281 */
282 public static Configuration createClusterConf(Configuration baseConf, String clusterKey,
283 String overridePrefix) throws IOException {
284 Configuration clusterConf = HBaseConfiguration.create(baseConf);
285 if (clusterKey != null && !clusterKey.isEmpty()) {
286 applyClusterKeyToConf(clusterConf, clusterKey);
287 }
288
289 if (overridePrefix != null && !overridePrefix.isEmpty()) {
290 Configuration clusterSubset = HBaseConfiguration.subset(clusterConf, overridePrefix);
291 HBaseConfiguration.merge(clusterConf, clusterSubset);
292 }
293 return clusterConf;
294 }
295
296 /**
297 * Apply the settings in the given key to the given configuration, this is
298 * used to communicate with distant clusters
299 * @param conf configuration object to configure
300 * @param key string that contains the 3 required configuratins
301 * @throws IOException
302 */
303 private static void applyClusterKeyToConf(Configuration conf, String key)
304 throws IOException{
305 ZKConfig.ZKClusterKey zkClusterKey = ZKConfig.transformClusterKey(key);
306 conf.set(HConstants.ZOOKEEPER_QUORUM, zkClusterKey.getQuorumString());
307 conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, zkClusterKey.getClientPort());
308 conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, zkClusterKey.getZnodeParent());
309 }
310
311 /**
312 * For debugging. Dump configurations to system output as xml format.
313 * Master and RS configurations can also be dumped using
314 * http services. e.g. "curl http://master:16010/dump"
315 */
316 public static void main(String[] args) throws Exception {
317 HBaseConfiguration.create().writeXml(System.out);
318 }
319 }