HBASE-23892 SecureTestCluster should allow its subclasses to pass their Class referen...
[hbase.git] / hbase-common / src / main / java / org / apache / hadoop / hbase / HBaseConfiguration.java
blob67de5fb3a21b75b94f576b97e471f0f5fa3b3a89
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 package org.apache.hadoop.hbase;
20 import java.io.IOException;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.util.Map;
25 import org.apache.hadoop.conf.Configuration;
26 import org.apache.hadoop.hbase.util.VersionInfo;
27 import org.apache.hadoop.hbase.zookeeper.ZKConfig;
28 import org.apache.yetus.audience.InterfaceAudience;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
32 /**
33 * Adds HBase configuration files to a Configuration
35 @InterfaceAudience.Public
36 public class HBaseConfiguration extends Configuration {
37 private static final Logger LOG = LoggerFactory.getLogger(HBaseConfiguration.class);
39 /**
40 * Instantiating HBaseConfiguration() is deprecated. Please use
41 * HBaseConfiguration#create() to construct a plain Configuration
42 * @deprecated since 0.90.0. Please use {@link #create()} instead.
43 * @see #create()
44 * @see <a href="https://issues.apache.org/jira/browse/HBASE-2036">HBASE-2036</a>
46 @Deprecated
47 public HBaseConfiguration() {
48 //TODO:replace with private constructor, HBaseConfiguration should not extend Configuration
49 super();
50 addHbaseResources(this);
51 LOG.warn("instantiating HBaseConfiguration() is deprecated. Please use"
52 + " HBaseConfiguration#create() to construct a plain Configuration");
55 /**
56 * Instantiating HBaseConfiguration() is deprecated. Please use
57 * HBaseConfiguration#create(conf) to construct a plain Configuration
58 * @deprecated since 0.90.0. Please use {@link #create(Configuration)} instead.
59 * @see #create(Configuration)
60 * @see <a href="https://issues.apache.org/jira/browse/HBASE-2036">HBASE-2036</a>
62 @Deprecated
63 public HBaseConfiguration(final Configuration c) {
64 //TODO:replace with private constructor
65 this();
66 merge(this, c);
69 private static void checkDefaultsVersion(Configuration conf) {
70 if (conf.getBoolean("hbase.defaults.for.version.skip", Boolean.FALSE)) return;
71 String defaultsVersion = conf.get("hbase.defaults.for.version");
72 String thisVersion = VersionInfo.getVersion();
73 if (!thisVersion.equals(defaultsVersion)) {
74 throw new RuntimeException(
75 "hbase-default.xml file seems to be for an older version of HBase (" +
76 defaultsVersion + "), this version is " + thisVersion);
80 public static Configuration addHbaseResources(Configuration conf) {
81 conf.addResource("hbase-default.xml");
82 conf.addResource("hbase-site.xml");
84 checkDefaultsVersion(conf);
85 return conf;
88 /**
89 * Creates a Configuration with HBase resources
90 * @return a Configuration with HBase resources
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);
102 * @param that Configuration to clone.
103 * @return a Configuration created with the hbase-*.xml files plus
104 * the given configuration.
106 public static Configuration create(final Configuration that) {
107 Configuration conf = create();
108 merge(conf, that);
109 return conf;
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
118 public static void merge(Configuration destConf, Configuration srcConf) {
119 for (Map.Entry<String, String> e : srcConf) {
120 destConf.set(e.getKey(), e.getValue());
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.
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());
142 return newConf;
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()}.
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());
158 * @return whether to show HBase Configuration in servlet
160 public static boolean isShowConfInServlet() {
161 boolean isShowConf = false;
162 try {
163 if (Class.forName("org.apache.hadoop.conf.ConfServlet") != null) {
164 isShowConf = true;
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
173 return isShowConf;
177 * Get the password from the Configuration instance using the
178 * getPassword method if it exists. If not, then fall back to the
179 * general get method for configuration elements.
181 * @param conf configuration instance for accessing the passwords
182 * @param alias the name of the password element
183 * @param defPass the default password
184 * @return String password or default password
185 * @throws IOException
187 public static String getPassword(Configuration conf, String alias,
188 String defPass) throws IOException {
189 String passwd = null;
190 try {
191 Method m = Configuration.class.getMethod("getPassword", String.class);
192 char[] p = (char[]) m.invoke(conf, alias);
193 if (p != null) {
194 LOG.debug(String.format("Config option \"%s\" was found through" +
195 " the Configuration getPassword method.", alias));
196 passwd = new String(p);
197 } else {
198 LOG.debug(String.format(
199 "Config option \"%s\" was not found. Using provided default value",
200 alias));
201 passwd = defPass;
203 } catch (NoSuchMethodException e) {
204 // this is a version of Hadoop where the credential
205 //provider API doesn't exist yet
206 LOG.debug(String.format(
207 "Credential.getPassword method is not available." +
208 " Falling back to configuration."));
209 passwd = conf.get(alias, defPass);
210 } catch (SecurityException e) {
211 throw new IOException(e.getMessage(), e);
212 } catch (IllegalAccessException e) {
213 throw new IOException(e.getMessage(), e);
214 } catch (IllegalArgumentException e) {
215 throw new IOException(e.getMessage(), e);
216 } catch (InvocationTargetException e) {
217 throw new IOException(e.getMessage(), e);
219 return passwd;
223 * Generates a {@link Configuration} instance by applying the ZooKeeper cluster key
224 * to the base Configuration. Note that additional configuration properties may be needed
225 * for a remote cluster, so it is preferable to use
226 * {@link #createClusterConf(Configuration, String, String)}.
228 * @param baseConf the base configuration to use, containing prefixed override properties
229 * @param clusterKey the ZooKeeper quorum cluster key to apply, or {@code null} if none
231 * @return the merged configuration with override properties and cluster key applied
233 * @see #createClusterConf(Configuration, String, String)
235 public static Configuration createClusterConf(Configuration baseConf, String clusterKey)
236 throws IOException {
237 return createClusterConf(baseConf, clusterKey, null);
241 * Generates a {@link Configuration} instance by applying property overrides prefixed by
242 * a cluster profile key to the base Configuration. Override properties are extracted by
243 * the {@link #subset(Configuration, String)} method, then the merged on top of the base
244 * Configuration and returned.
246 * @param baseConf the base configuration to use, containing prefixed override properties
247 * @param clusterKey the ZooKeeper quorum cluster key to apply, or {@code null} if none
248 * @param overridePrefix the property key prefix to match for override properties,
249 * or {@code null} if none
250 * @return the merged configuration with override properties and cluster key applied
252 public static Configuration createClusterConf(Configuration baseConf, String clusterKey,
253 String overridePrefix) throws IOException {
254 Configuration clusterConf = HBaseConfiguration.create(baseConf);
255 if (clusterKey != null && !clusterKey.isEmpty()) {
256 applyClusterKeyToConf(clusterConf, clusterKey);
259 if (overridePrefix != null && !overridePrefix.isEmpty()) {
260 Configuration clusterSubset = HBaseConfiguration.subset(clusterConf, overridePrefix);
261 HBaseConfiguration.merge(clusterConf, clusterSubset);
263 return clusterConf;
267 * Apply the settings in the given key to the given configuration, this is
268 * used to communicate with distant clusters
269 * @param conf configuration object to configure
270 * @param key string that contains the 3 required configuratins
272 private static void applyClusterKeyToConf(Configuration conf, String key)
273 throws IOException {
274 ZKConfig.ZKClusterKey zkClusterKey = ZKConfig.transformClusterKey(key);
275 conf.set(HConstants.ZOOKEEPER_QUORUM, zkClusterKey.getQuorumString());
276 conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, zkClusterKey.getClientPort());
277 conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, zkClusterKey.getZnodeParent());
278 // Without the right registry, the above configs are useless. Also, we don't use setClass()
279 // here because the ConnectionRegistry* classes are not resolvable from this module.
280 // This will be broken if ZkConnectionRegistry class gets renamed or moved. Is there a better
281 // way?
282 LOG.info("Overriding client registry implementation to {}",
283 HConstants.ZK_CONNECTION_REGISTRY_CLASS);
284 conf.set(HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY,
285 HConstants.ZK_CONNECTION_REGISTRY_CLASS);
289 * For debugging. Dump configurations to system output as xml format.
290 * Master and RS configurations can also be dumped using
291 * http services. e.g. "curl http://master:16010/dump"
293 public static void main(String[] args) throws Exception {
294 HBaseConfiguration.create().writeXml(System.out);