001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 019package org.apache.hadoop.conf; 020 021import com.google.common.annotations.VisibleForTesting; 022 023import java.io.BufferedInputStream; 024import java.io.DataInput; 025import java.io.DataOutput; 026import java.io.File; 027import java.io.FileInputStream; 028import java.io.IOException; 029import java.io.InputStream; 030import java.io.InputStreamReader; 031import java.io.OutputStream; 032import java.io.OutputStreamWriter; 033import java.io.Reader; 034import java.io.Writer; 035import java.lang.ref.WeakReference; 036import java.net.InetSocketAddress; 037import java.net.JarURLConnection; 038import java.net.URL; 039import java.net.URLConnection; 040import java.util.ArrayList; 041import java.util.Arrays; 042import java.util.Collection; 043import java.util.Collections; 044import java.util.Enumeration; 045import java.util.HashMap; 046import java.util.HashSet; 047import java.util.Iterator; 048import java.util.LinkedList; 049import java.util.List; 050import java.util.ListIterator; 051import java.util.Map; 052import java.util.Map.Entry; 053import java.util.Properties; 054import java.util.Set; 055import java.util.StringTokenizer; 056import java.util.WeakHashMap; 057import java.util.concurrent.ConcurrentHashMap; 058import java.util.concurrent.CopyOnWriteArrayList; 059import java.util.regex.Matcher; 060import java.util.regex.Pattern; 061import java.util.regex.PatternSyntaxException; 062import java.util.concurrent.TimeUnit; 063import java.util.concurrent.atomic.AtomicBoolean; 064import java.util.concurrent.atomic.AtomicReference; 065 066import javax.xml.parsers.DocumentBuilder; 067import javax.xml.parsers.DocumentBuilderFactory; 068import javax.xml.parsers.ParserConfigurationException; 069import javax.xml.transform.Transformer; 070import javax.xml.transform.TransformerException; 071import javax.xml.transform.TransformerFactory; 072import javax.xml.transform.dom.DOMSource; 073import javax.xml.transform.stream.StreamResult; 074 075import com.google.common.base.Charsets; 076import org.apache.commons.collections.map.UnmodifiableMap; 077import org.apache.commons.logging.Log; 078import org.apache.commons.logging.LogFactory; 079import org.apache.hadoop.classification.InterfaceAudience; 080import org.apache.hadoop.classification.InterfaceStability; 081import org.apache.hadoop.fs.CommonConfigurationKeysPublic; 082import org.apache.hadoop.fs.FileSystem; 083import org.apache.hadoop.fs.Path; 084import org.apache.hadoop.fs.CommonConfigurationKeys; 085import org.apache.hadoop.io.Writable; 086import org.apache.hadoop.io.WritableUtils; 087import org.apache.hadoop.net.NetUtils; 088import org.apache.hadoop.security.alias.CredentialProvider; 089import org.apache.hadoop.security.alias.CredentialProvider.CredentialEntry; 090import org.apache.hadoop.security.alias.CredentialProviderFactory; 091import org.apache.hadoop.util.ReflectionUtils; 092import org.apache.hadoop.util.StringInterner; 093import org.apache.hadoop.util.StringUtils; 094import org.codehaus.jackson.JsonFactory; 095import org.codehaus.jackson.JsonGenerator; 096import org.w3c.dom.Attr; 097import org.w3c.dom.DOMException; 098import org.w3c.dom.Document; 099import org.w3c.dom.Element; 100import org.w3c.dom.Node; 101import org.w3c.dom.NodeList; 102import org.w3c.dom.Text; 103import org.xml.sax.SAXException; 104 105import com.google.common.base.Preconditions; 106 107/** 108 * Provides access to configuration parameters. 109 * 110 * <h4 id="Resources">Resources</h4> 111 * 112 * <p>Configurations are specified by resources. A resource contains a set of 113 * name/value pairs as XML data. Each resource is named by either a 114 * <code>String</code> or by a {@link Path}. If named by a <code>String</code>, 115 * then the classpath is examined for a file with that name. If named by a 116 * <code>Path</code>, then the local filesystem is examined directly, without 117 * referring to the classpath. 118 * 119 * <p>Unless explicitly turned off, Hadoop by default specifies two 120 * resources, loaded in-order from the classpath: <ol> 121 * <li><tt> 122 * <a href="{@docRoot}/../hadoop-project-dist/hadoop-common/core-default.xml"> 123 * core-default.xml</a></tt>: Read-only defaults for hadoop.</li> 124 * <li><tt>core-site.xml</tt>: Site-specific configuration for a given hadoop 125 * installation.</li> 126 * </ol> 127 * Applications may add additional resources, which are loaded 128 * subsequent to these resources in the order they are added. 129 * 130 * <h4 id="FinalParams">Final Parameters</h4> 131 * 132 * <p>Configuration parameters may be declared <i>final</i>. 133 * Once a resource declares a value final, no subsequently-loaded 134 * resource can alter that value. 135 * For example, one might define a final parameter with: 136 * <tt><pre> 137 * <property> 138 * <name>dfs.hosts.include</name> 139 * <value>/etc/hadoop/conf/hosts.include</value> 140 * <b><final>true</final></b> 141 * </property></pre></tt> 142 * 143 * Administrators typically define parameters as final in 144 * <tt>core-site.xml</tt> for values that user applications may not alter. 145 * 146 * <h4 id="VariableExpansion">Variable Expansion</h4> 147 * 148 * <p>Value strings are first processed for <i>variable expansion</i>. The 149 * available properties are:<ol> 150 * <li>Other properties defined in this Configuration; and, if a name is 151 * undefined here,</li> 152 * <li>Environment variables in {@link System#getenv()} if a name starts with 153 * "env.", or</li> 154 * <li>Properties in {@link System#getProperties()}.</li> 155 * </ol> 156 * 157 * <p>For example, if a configuration resource contains the following property 158 * definitions: 159 * <tt><pre> 160 * <property> 161 * <name>basedir</name> 162 * <value>/user/${<i>user.name</i>}</value> 163 * </property> 164 * 165 * <property> 166 * <name>tempdir</name> 167 * <value>${<i>basedir</i>}/tmp</value> 168 * </property> 169 * 170 * <property> 171 * <name>otherdir</name> 172 * <value>${<i>env.BASE_DIR</i>}/other</value> 173 * </property> 174 * </pre></tt> 175 * 176 * <p>When <tt>conf.get("tempdir")</tt> is called, then <tt>${<i>basedir</i>}</tt> 177 * will be resolved to another property in this Configuration, while 178 * <tt>${<i>user.name</i>}</tt> would then ordinarily be resolved to the value 179 * of the System property with that name. 180 * <p>When <tt>conf.get("otherdir")</tt> is called, then <tt>${<i>env.BASE_DIR</i>}</tt> 181 * will be resolved to the value of the <tt>${<i>BASE_DIR</i>}</tt> environment variable. 182 * It supports <tt>${<i>env.NAME:-default</i>}</tt> and <tt>${<i>env.NAME-default</i>}</tt> notations. 183 * The former is resolved to "default" if <tt>${<i>NAME</i>}</tt> environment variable is undefined 184 * or its value is empty. 185 * The latter behaves the same way only if <tt>${<i>NAME</i>}</tt> is undefined. 186 * <p>By default, warnings will be given to any deprecated configuration 187 * parameters and these are suppressible by configuring 188 * <tt>log4j.logger.org.apache.hadoop.conf.Configuration.deprecation</tt> in 189 * log4j.properties file. 190 */ 191@InterfaceAudience.Public 192@InterfaceStability.Stable 193public class Configuration implements Iterable<Map.Entry<String,String>>, 194 Writable { 195 private static final Log LOG = 196 LogFactory.getLog(Configuration.class); 197 198 private static final Log LOG_DEPRECATION = 199 LogFactory.getLog("org.apache.hadoop.conf.Configuration.deprecation"); 200 201 private boolean quietmode = true; 202 203 private static final String DEFAULT_STRING_CHECK = 204 "testingforemptydefaultvalue"; 205 206 private boolean allowNullValueProperties = false; 207 208 private static class Resource { 209 private final Object resource; 210 private final String name; 211 212 public Resource(Object resource) { 213 this(resource, resource.toString()); 214 } 215 216 public Resource(Object resource, String name) { 217 this.resource = resource; 218 this.name = name; 219 } 220 221 public String getName(){ 222 return name; 223 } 224 225 public Object getResource() { 226 return resource; 227 } 228 229 @Override 230 public String toString() { 231 return name; 232 } 233 } 234 235 /** 236 * List of configuration resources. 237 */ 238 private ArrayList<Resource> resources = new ArrayList<Resource>(); 239 240 /** 241 * The value reported as the setting resource when a key is set 242 * by code rather than a file resource by dumpConfiguration. 243 */ 244 static final String UNKNOWN_RESOURCE = "Unknown"; 245 246 247 /** 248 * List of configuration parameters marked <b>final</b>. 249 */ 250 private Set<String> finalParameters = Collections.newSetFromMap( 251 new ConcurrentHashMap<String, Boolean>()); 252 253 private boolean loadDefaults = true; 254 255 /** 256 * Configuration objects 257 */ 258 private static final WeakHashMap<Configuration,Object> REGISTRY = 259 new WeakHashMap<Configuration,Object>(); 260 261 /** 262 * List of default Resources. Resources are loaded in the order of the list 263 * entries 264 */ 265 private static final CopyOnWriteArrayList<String> defaultResources = 266 new CopyOnWriteArrayList<String>(); 267 268 private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>> 269 CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, WeakReference<Class<?>>>>(); 270 271 /** 272 * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}. 273 */ 274 private static final Class<?> NEGATIVE_CACHE_SENTINEL = 275 NegativeCacheSentinel.class; 276 277 /** 278 * Stores the mapping of key to the resource which modifies or loads 279 * the key most recently 280 */ 281 private Map<String, String[]> updatingResource; 282 283 /** 284 * Class to keep the information about the keys which replace the deprecated 285 * ones. 286 * 287 * This class stores the new keys which replace the deprecated keys and also 288 * gives a provision to have a custom message for each of the deprecated key 289 * that is being replaced. It also provides method to get the appropriate 290 * warning message which can be logged whenever the deprecated key is used. 291 */ 292 private static class DeprecatedKeyInfo { 293 private final String[] newKeys; 294 private final String customMessage; 295 private final AtomicBoolean accessed = new AtomicBoolean(false); 296 297 DeprecatedKeyInfo(String[] newKeys, String customMessage) { 298 this.newKeys = newKeys; 299 this.customMessage = customMessage; 300 } 301 302 /** 303 * Method to provide the warning message. It gives the custom message if 304 * non-null, and default message otherwise. 305 * @param key the associated deprecated key. 306 * @return message that is to be logged when a deprecated key is used. 307 */ 308 private final String getWarningMessage(String key) { 309 String warningMessage; 310 if(customMessage == null) { 311 StringBuilder message = new StringBuilder(key); 312 String deprecatedKeySuffix = " is deprecated. Instead, use "; 313 message.append(deprecatedKeySuffix); 314 for (int i = 0; i < newKeys.length; i++) { 315 message.append(newKeys[i]); 316 if(i != newKeys.length-1) { 317 message.append(", "); 318 } 319 } 320 warningMessage = message.toString(); 321 } 322 else { 323 warningMessage = customMessage; 324 } 325 return warningMessage; 326 } 327 328 boolean getAndSetAccessed() { 329 return accessed.getAndSet(true); 330 } 331 332 public void clearAccessed() { 333 accessed.set(false); 334 } 335 } 336 337 /** 338 * A pending addition to the global set of deprecated keys. 339 */ 340 public static class DeprecationDelta { 341 private final String key; 342 private final String[] newKeys; 343 private final String customMessage; 344 345 DeprecationDelta(String key, String[] newKeys, String customMessage) { 346 Preconditions.checkNotNull(key); 347 Preconditions.checkNotNull(newKeys); 348 Preconditions.checkArgument(newKeys.length > 0); 349 this.key = key; 350 this.newKeys = newKeys; 351 this.customMessage = customMessage; 352 } 353 354 public DeprecationDelta(String key, String newKey, String customMessage) { 355 this(key, new String[] { newKey }, customMessage); 356 } 357 358 public DeprecationDelta(String key, String newKey) { 359 this(key, new String[] { newKey }, null); 360 } 361 362 public String getKey() { 363 return key; 364 } 365 366 public String[] getNewKeys() { 367 return newKeys; 368 } 369 370 public String getCustomMessage() { 371 return customMessage; 372 } 373 } 374 375 /** 376 * The set of all keys which are deprecated. 377 * 378 * DeprecationContext objects are immutable. 379 */ 380 private static class DeprecationContext { 381 /** 382 * Stores the deprecated keys, the new keys which replace the deprecated keys 383 * and custom message(if any provided). 384 */ 385 private final Map<String, DeprecatedKeyInfo> deprecatedKeyMap; 386 387 /** 388 * Stores a mapping from superseding keys to the keys which they deprecate. 389 */ 390 private final Map<String, String> reverseDeprecatedKeyMap; 391 392 /** 393 * Create a new DeprecationContext by copying a previous DeprecationContext 394 * and adding some deltas. 395 * 396 * @param other The previous deprecation context to copy, or null to start 397 * from nothing. 398 * @param deltas The deltas to apply. 399 */ 400 @SuppressWarnings("unchecked") 401 DeprecationContext(DeprecationContext other, DeprecationDelta[] deltas) { 402 HashMap<String, DeprecatedKeyInfo> newDeprecatedKeyMap = 403 new HashMap<String, DeprecatedKeyInfo>(); 404 HashMap<String, String> newReverseDeprecatedKeyMap = 405 new HashMap<String, String>(); 406 if (other != null) { 407 for (Entry<String, DeprecatedKeyInfo> entry : 408 other.deprecatedKeyMap.entrySet()) { 409 newDeprecatedKeyMap.put(entry.getKey(), entry.getValue()); 410 } 411 for (Entry<String, String> entry : 412 other.reverseDeprecatedKeyMap.entrySet()) { 413 newReverseDeprecatedKeyMap.put(entry.getKey(), entry.getValue()); 414 } 415 } 416 for (DeprecationDelta delta : deltas) { 417 if (!newDeprecatedKeyMap.containsKey(delta.getKey())) { 418 DeprecatedKeyInfo newKeyInfo = 419 new DeprecatedKeyInfo(delta.getNewKeys(), delta.getCustomMessage()); 420 newDeprecatedKeyMap.put(delta.key, newKeyInfo); 421 for (String newKey : delta.getNewKeys()) { 422 newReverseDeprecatedKeyMap.put(newKey, delta.key); 423 } 424 } 425 } 426 this.deprecatedKeyMap = 427 UnmodifiableMap.decorate(newDeprecatedKeyMap); 428 this.reverseDeprecatedKeyMap = 429 UnmodifiableMap.decorate(newReverseDeprecatedKeyMap); 430 } 431 432 Map<String, DeprecatedKeyInfo> getDeprecatedKeyMap() { 433 return deprecatedKeyMap; 434 } 435 436 Map<String, String> getReverseDeprecatedKeyMap() { 437 return reverseDeprecatedKeyMap; 438 } 439 } 440 441 private static DeprecationDelta[] defaultDeprecations = 442 new DeprecationDelta[] { 443 new DeprecationDelta("topology.script.file.name", 444 CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY), 445 new DeprecationDelta("topology.script.number.args", 446 CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_NUMBER_ARGS_KEY), 447 new DeprecationDelta("hadoop.configured.node.mapping", 448 CommonConfigurationKeys.NET_TOPOLOGY_CONFIGURED_NODE_MAPPING_KEY), 449 new DeprecationDelta("topology.node.switch.mapping.impl", 450 CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY), 451 new DeprecationDelta("dfs.df.interval", 452 CommonConfigurationKeys.FS_DF_INTERVAL_KEY), 453 new DeprecationDelta("fs.default.name", 454 CommonConfigurationKeys.FS_DEFAULT_NAME_KEY), 455 new DeprecationDelta("dfs.umaskmode", 456 CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY), 457 new DeprecationDelta("dfs.nfs.exports.allowed.hosts", 458 CommonConfigurationKeys.NFS_EXPORTS_ALLOWED_HOSTS_KEY) 459 }; 460 461 /** 462 * The global DeprecationContext. 463 */ 464 private static AtomicReference<DeprecationContext> deprecationContext = 465 new AtomicReference<DeprecationContext>( 466 new DeprecationContext(null, defaultDeprecations)); 467 468 /** 469 * Adds a set of deprecated keys to the global deprecations. 470 * 471 * This method is lockless. It works by means of creating a new 472 * DeprecationContext based on the old one, and then atomically swapping in 473 * the new context. If someone else updated the context in between us reading 474 * the old context and swapping in the new one, we try again until we win the 475 * race. 476 * 477 * @param deltas The deprecations to add. 478 */ 479 public static void addDeprecations(DeprecationDelta[] deltas) { 480 DeprecationContext prev, next; 481 do { 482 prev = deprecationContext.get(); 483 next = new DeprecationContext(prev, deltas); 484 } while (!deprecationContext.compareAndSet(prev, next)); 485 } 486 487 /** 488 * Adds the deprecated key to the global deprecation map. 489 * It does not override any existing entries in the deprecation map. 490 * This is to be used only by the developers in order to add deprecation of 491 * keys, and attempts to call this method after loading resources once, 492 * would lead to <tt>UnsupportedOperationException</tt> 493 * 494 * If a key is deprecated in favor of multiple keys, they are all treated as 495 * aliases of each other, and setting any one of them resets all the others 496 * to the new value. 497 * 498 * If you have multiple deprecation entries to add, it is more efficient to 499 * use #addDeprecations(DeprecationDelta[] deltas) instead. 500 * 501 * @param key 502 * @param newKeys 503 * @param customMessage 504 * @deprecated use {@link #addDeprecation(String key, String newKey, 505 String customMessage)} instead 506 */ 507 @Deprecated 508 public static void addDeprecation(String key, String[] newKeys, 509 String customMessage) { 510 addDeprecations(new DeprecationDelta[] { 511 new DeprecationDelta(key, newKeys, customMessage) 512 }); 513 } 514 515 /** 516 * Adds the deprecated key to the global deprecation map. 517 * It does not override any existing entries in the deprecation map. 518 * This is to be used only by the developers in order to add deprecation of 519 * keys, and attempts to call this method after loading resources once, 520 * would lead to <tt>UnsupportedOperationException</tt> 521 * 522 * If you have multiple deprecation entries to add, it is more efficient to 523 * use #addDeprecations(DeprecationDelta[] deltas) instead. 524 * 525 * @param key 526 * @param newKey 527 * @param customMessage 528 */ 529 public static void addDeprecation(String key, String newKey, 530 String customMessage) { 531 addDeprecation(key, new String[] {newKey}, customMessage); 532 } 533 534 /** 535 * Adds the deprecated key to the global deprecation map when no custom 536 * message is provided. 537 * It does not override any existing entries in the deprecation map. 538 * This is to be used only by the developers in order to add deprecation of 539 * keys, and attempts to call this method after loading resources once, 540 * would lead to <tt>UnsupportedOperationException</tt> 541 * 542 * If a key is deprecated in favor of multiple keys, they are all treated as 543 * aliases of each other, and setting any one of them resets all the others 544 * to the new value. 545 * 546 * If you have multiple deprecation entries to add, it is more efficient to 547 * use #addDeprecations(DeprecationDelta[] deltas) instead. 548 * 549 * @param key Key that is to be deprecated 550 * @param newKeys list of keys that take up the values of deprecated key 551 * @deprecated use {@link #addDeprecation(String key, String newKey)} instead 552 */ 553 @Deprecated 554 public static void addDeprecation(String key, String[] newKeys) { 555 addDeprecation(key, newKeys, null); 556 } 557 558 /** 559 * Adds the deprecated key to the global deprecation map when no custom 560 * message is provided. 561 * It does not override any existing entries in the deprecation map. 562 * This is to be used only by the developers in order to add deprecation of 563 * keys, and attempts to call this method after loading resources once, 564 * would lead to <tt>UnsupportedOperationException</tt> 565 * 566 * If you have multiple deprecation entries to add, it is more efficient to 567 * use #addDeprecations(DeprecationDelta[] deltas) instead. 568 * 569 * @param key Key that is to be deprecated 570 * @param newKey key that takes up the value of deprecated key 571 */ 572 public static void addDeprecation(String key, String newKey) { 573 addDeprecation(key, new String[] {newKey}, null); 574 } 575 576 /** 577 * checks whether the given <code>key</code> is deprecated. 578 * 579 * @param key the parameter which is to be checked for deprecation 580 * @return <code>true</code> if the key is deprecated and 581 * <code>false</code> otherwise. 582 */ 583 public static boolean isDeprecated(String key) { 584 return deprecationContext.get().getDeprecatedKeyMap().containsKey(key); 585 } 586 587 /** 588 * Sets all deprecated properties that are not currently set but have a 589 * corresponding new property that is set. Useful for iterating the 590 * properties when all deprecated properties for currently set properties 591 * need to be present. 592 */ 593 public void setDeprecatedProperties() { 594 DeprecationContext deprecations = deprecationContext.get(); 595 Properties props = getProps(); 596 Properties overlay = getOverlay(); 597 for (Map.Entry<String, DeprecatedKeyInfo> entry : 598 deprecations.getDeprecatedKeyMap().entrySet()) { 599 String depKey = entry.getKey(); 600 if (!overlay.contains(depKey)) { 601 for (String newKey : entry.getValue().newKeys) { 602 String val = overlay.getProperty(newKey); 603 if (val != null) { 604 props.setProperty(depKey, val); 605 overlay.setProperty(depKey, val); 606 break; 607 } 608 } 609 } 610 } 611 } 612 613 /** 614 * Checks for the presence of the property <code>name</code> in the 615 * deprecation map. Returns the first of the list of new keys if present 616 * in the deprecation map or the <code>name</code> itself. If the property 617 * is not presently set but the property map contains an entry for the 618 * deprecated key, the value of the deprecated key is set as the value for 619 * the provided property name. 620 * 621 * @param name the property name 622 * @return the first property in the list of properties mapping 623 * the <code>name</code> or the <code>name</code> itself. 624 */ 625 private String[] handleDeprecation(DeprecationContext deprecations, 626 String name) { 627 if (null != name) { 628 name = name.trim(); 629 } 630 ArrayList<String > names = new ArrayList<String>(); 631 if (isDeprecated(name)) { 632 DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(name); 633 if (keyInfo != null) { 634 if (!keyInfo.getAndSetAccessed()) { 635 logDeprecation(keyInfo.getWarningMessage(name)); 636 } 637 638 for (String newKey : keyInfo.newKeys) { 639 if (newKey != null) { 640 names.add(newKey); 641 } 642 } 643 } 644 } 645 if(names.size() == 0) { 646 names.add(name); 647 } 648 for(String n : names) { 649 String deprecatedKey = deprecations.getReverseDeprecatedKeyMap().get(n); 650 if (deprecatedKey != null && !getOverlay().containsKey(n) && 651 getOverlay().containsKey(deprecatedKey)) { 652 getProps().setProperty(n, getOverlay().getProperty(deprecatedKey)); 653 getOverlay().setProperty(n, getOverlay().getProperty(deprecatedKey)); 654 } 655 } 656 return names.toArray(new String[names.size()]); 657 } 658 659 private void handleDeprecation() { 660 LOG.debug("Handling deprecation for all properties in config..."); 661 DeprecationContext deprecations = deprecationContext.get(); 662 Set<Object> keys = new HashSet<Object>(); 663 keys.addAll(getProps().keySet()); 664 for (Object item: keys) { 665 LOG.debug("Handling deprecation for " + (String)item); 666 handleDeprecation(deprecations, (String)item); 667 } 668 } 669 670 static{ 671 //print deprecation warning if hadoop-site.xml is found in classpath 672 ClassLoader cL = Thread.currentThread().getContextClassLoader(); 673 if (cL == null) { 674 cL = Configuration.class.getClassLoader(); 675 } 676 if(cL.getResource("hadoop-site.xml")!=null) { 677 LOG.warn("DEPRECATED: hadoop-site.xml found in the classpath. " + 678 "Usage of hadoop-site.xml is deprecated. Instead use core-site.xml, " 679 + "mapred-site.xml and hdfs-site.xml to override properties of " + 680 "core-default.xml, mapred-default.xml and hdfs-default.xml " + 681 "respectively"); 682 } 683 addDefaultResource("core-default.xml"); 684 addDefaultResource("core-site.xml"); 685 } 686 687 private Properties properties; 688 private Properties overlay; 689 private ClassLoader classLoader; 690 { 691 classLoader = Thread.currentThread().getContextClassLoader(); 692 if (classLoader == null) { 693 classLoader = Configuration.class.getClassLoader(); 694 } 695 } 696 697 /** A new configuration. */ 698 public Configuration() { 699 this(true); 700 } 701 702 /** A new configuration where the behavior of reading from the default 703 * resources can be turned off. 704 * 705 * If the parameter {@code loadDefaults} is false, the new instance 706 * will not load resources from the default files. 707 * @param loadDefaults specifies whether to load from the default files 708 */ 709 public Configuration(boolean loadDefaults) { 710 this.loadDefaults = loadDefaults; 711 updatingResource = new ConcurrentHashMap<String, String[]>(); 712 synchronized(Configuration.class) { 713 REGISTRY.put(this, null); 714 } 715 } 716 717 /** 718 * A new configuration with the same settings cloned from another. 719 * 720 * @param other the configuration from which to clone settings. 721 */ 722 @SuppressWarnings("unchecked") 723 public Configuration(Configuration other) { 724 this.resources = (ArrayList<Resource>) other.resources.clone(); 725 synchronized(other) { 726 if (other.properties != null) { 727 this.properties = (Properties)other.properties.clone(); 728 } 729 730 if (other.overlay!=null) { 731 this.overlay = (Properties)other.overlay.clone(); 732 } 733 734 this.updatingResource = new ConcurrentHashMap<String, String[]>( 735 other.updatingResource); 736 this.finalParameters = Collections.newSetFromMap( 737 new ConcurrentHashMap<String, Boolean>()); 738 this.finalParameters.addAll(other.finalParameters); 739 } 740 741 synchronized(Configuration.class) { 742 REGISTRY.put(this, null); 743 } 744 this.classLoader = other.classLoader; 745 this.loadDefaults = other.loadDefaults; 746 setQuietMode(other.getQuietMode()); 747 } 748 749 /** 750 * Add a default resource. Resources are loaded in the order of the resources 751 * added. 752 * @param name file name. File should be present in the classpath. 753 */ 754 public static synchronized void addDefaultResource(String name) { 755 if(!defaultResources.contains(name)) { 756 defaultResources.add(name); 757 for(Configuration conf : REGISTRY.keySet()) { 758 if(conf.loadDefaults) { 759 conf.reloadConfiguration(); 760 } 761 } 762 } 763 } 764 765 /** 766 * Add a configuration resource. 767 * 768 * The properties of this resource will override properties of previously 769 * added resources, unless they were marked <a href="#Final">final</a>. 770 * 771 * @param name resource to be added, the classpath is examined for a file 772 * with that name. 773 */ 774 public void addResource(String name) { 775 addResourceObject(new Resource(name)); 776 } 777 778 /** 779 * Add a configuration resource. 780 * 781 * The properties of this resource will override properties of previously 782 * added resources, unless they were marked <a href="#Final">final</a>. 783 * 784 * @param url url of the resource to be added, the local filesystem is 785 * examined directly to find the resource, without referring to 786 * the classpath. 787 */ 788 public void addResource(URL url) { 789 addResourceObject(new Resource(url)); 790 } 791 792 /** 793 * Add a configuration resource. 794 * 795 * The properties of this resource will override properties of previously 796 * added resources, unless they were marked <a href="#Final">final</a>. 797 * 798 * @param file file-path of resource to be added, the local filesystem is 799 * examined directly to find the resource, without referring to 800 * the classpath. 801 */ 802 public void addResource(Path file) { 803 addResourceObject(new Resource(file)); 804 } 805 806 /** 807 * Add a configuration resource. 808 * 809 * The properties of this resource will override properties of previously 810 * added resources, unless they were marked <a href="#Final">final</a>. 811 * 812 * WARNING: The contents of the InputStream will be cached, by this method. 813 * So use this sparingly because it does increase the memory consumption. 814 * 815 * @param in InputStream to deserialize the object from. In will be read from 816 * when a get or set is called next. After it is read the stream will be 817 * closed. 818 */ 819 public void addResource(InputStream in) { 820 addResourceObject(new Resource(in)); 821 } 822 823 /** 824 * Add a configuration resource. 825 * 826 * The properties of this resource will override properties of previously 827 * added resources, unless they were marked <a href="#Final">final</a>. 828 * 829 * @param in InputStream to deserialize the object from. 830 * @param name the name of the resource because InputStream.toString is not 831 * very descriptive some times. 832 */ 833 public void addResource(InputStream in, String name) { 834 addResourceObject(new Resource(in, name)); 835 } 836 837 /** 838 * Add a configuration resource. 839 * 840 * The properties of this resource will override properties of previously 841 * added resources, unless they were marked <a href="#Final">final</a>. 842 * 843 * @param conf Configuration object from which to load properties 844 */ 845 public void addResource(Configuration conf) { 846 addResourceObject(new Resource(conf.getProps())); 847 } 848 849 850 851 /** 852 * Reload configuration from previously added resources. 853 * 854 * This method will clear all the configuration read from the added 855 * resources, and final parameters. This will make the resources to 856 * be read again before accessing the values. Values that are added 857 * via set methods will overlay values read from the resources. 858 */ 859 public synchronized void reloadConfiguration() { 860 properties = null; // trigger reload 861 finalParameters.clear(); // clear site-limits 862 } 863 864 private synchronized void addResourceObject(Resource resource) { 865 resources.add(resource); // add to resources 866 reloadConfiguration(); 867 } 868 869 private static final int MAX_SUBST = 20; 870 871 private static final int SUB_START_IDX = 0; 872 private static final int SUB_END_IDX = SUB_START_IDX + 1; 873 874 /** 875 * This is a manual implementation of the following regex 876 * "\\$\\{[^\\}\\$\u0020]+\\}". It can be 15x more efficient than 877 * a regex matcher as demonstrated by HADOOP-11506. This is noticeable with 878 * Hadoop apps building on the assumption Configuration#get is an O(1) 879 * hash table lookup, especially when the eval is a long string. 880 * 881 * @param eval a string that may contain variables requiring expansion. 882 * @return a 2-element int array res such that 883 * eval.substring(res[0], res[1]) is "var" for the left-most occurrence of 884 * ${var} in eval. If no variable is found -1, -1 is returned. 885 */ 886 private static int[] findSubVariable(String eval) { 887 int[] result = {-1, -1}; 888 889 int matchStart; 890 int leftBrace; 891 892 // scanning for a brace first because it's less frequent than $ 893 // that can occur in nested class names 894 // 895 match_loop: 896 for (matchStart = 1, leftBrace = eval.indexOf('{', matchStart); 897 // minimum left brace position (follows '$') 898 leftBrace > 0 899 // right brace of a smallest valid expression "${c}" 900 && leftBrace + "{c".length() < eval.length(); 901 leftBrace = eval.indexOf('{', matchStart)) { 902 int matchedLen = 0; 903 if (eval.charAt(leftBrace - 1) == '$') { 904 int subStart = leftBrace + 1; // after '{' 905 for (int i = subStart; i < eval.length(); i++) { 906 switch (eval.charAt(i)) { 907 case '}': 908 if (matchedLen > 0) { // match 909 result[SUB_START_IDX] = subStart; 910 result[SUB_END_IDX] = subStart + matchedLen; 911 break match_loop; 912 } 913 // fall through to skip 1 char 914 case ' ': 915 case '$': 916 matchStart = i + 1; 917 continue match_loop; 918 default: 919 matchedLen++; 920 } 921 } 922 // scanned from "${" to the end of eval, and no reset via ' ', '$': 923 // no match! 924 break match_loop; 925 } else { 926 // not a start of a variable 927 // 928 matchStart = leftBrace + 1; 929 } 930 } 931 return result; 932 } 933 934 /** 935 * Attempts to repeatedly expand the value {@code expr} by replacing the 936 * left-most substring of the form "${var}" in the following precedence order 937 * <ol> 938 * <li>by the value of the environment variable "var" if defined</li> 939 * <li>by the value of the Java system property "var" if defined</li> 940 * <li>by the value of the configuration key "var" if defined</li> 941 * </ol> 942 * 943 * If var is unbounded the current state of expansion "prefix${var}suffix" is 944 * returned. 945 * 946 * If a cycle is detected: replacing var1 requires replacing var2 ... requires 947 * replacing var1, i.e., the cycle is shorter than 948 * {@link Configuration#MAX_SUBST} then the original expr is returned. 949 * 950 * @param expr the literal value of a config key 951 * @return null if expr is null, otherwise the value resulting from expanding 952 * expr using the algorithm above. 953 * @throws IllegalArgumentException when more than 954 * {@link Configuration#MAX_SUBST} replacements are required 955 */ 956 private String substituteVars(String expr) { 957 if (expr == null) { 958 return null; 959 } 960 String eval = expr; 961 Set<String> evalSet = null; 962 for(int s = 0; s < MAX_SUBST; s++) { 963 final int[] varBounds = findSubVariable(eval); 964 if (varBounds[SUB_START_IDX] == -1) { 965 return eval; 966 } 967 final String var = eval.substring(varBounds[SUB_START_IDX], 968 varBounds[SUB_END_IDX]); 969 String val = null; 970 try { 971 if (var.startsWith("env.") && 4 < var.length()) { 972 String v = var.substring(4); 973 int i = 0; 974 for (; i < v.length(); i++) { 975 char c = v.charAt(i); 976 if (c == ':' && i < v.length() - 1 && v.charAt(i + 1) == '-') { 977 val = getenv(v.substring(0, i)); 978 if (val == null || val.length() == 0) { 979 val = v.substring(i + 2); 980 } 981 break; 982 } else if (c == '-') { 983 val = getenv(v.substring(0, i)); 984 if (val == null) { 985 val = v.substring(i + 1); 986 } 987 break; 988 } 989 } 990 if (i == v.length()) { 991 val = getenv(v); 992 } 993 } else { 994 val = getProperty(var); 995 } 996 } catch(SecurityException se) { 997 LOG.warn("Unexpected SecurityException in Configuration", se); 998 } 999 if (val == null) { 1000 val = getRaw(var); 1001 } 1002 if (val == null) { 1003 return eval; // return literal ${var}: var is unbound 1004 } 1005 1006 // prevent recursive resolution 1007 // 1008 final int dollar = varBounds[SUB_START_IDX] - "${".length(); 1009 final int afterRightBrace = varBounds[SUB_END_IDX] + "}".length(); 1010 final String refVar = eval.substring(dollar, afterRightBrace); 1011 if (evalSet == null) { 1012 evalSet = new HashSet<String>(); 1013 } 1014 if (!evalSet.add(refVar)) { 1015 return expr; // return original expression if there is a loop 1016 } 1017 1018 // substitute 1019 eval = eval.substring(0, dollar) 1020 + val 1021 + eval.substring(afterRightBrace); 1022 } 1023 throw new IllegalStateException("Variable substitution depth too large: " 1024 + MAX_SUBST + " " + expr); 1025 } 1026 1027 String getenv(String name) { 1028 return System.getenv(name); 1029 } 1030 1031 String getProperty(String key) { 1032 return System.getProperty(key); 1033 } 1034 1035 /** 1036 * Get the value of the <code>name</code> property, <code>null</code> if 1037 * no such property exists. If the key is deprecated, it returns the value of 1038 * the first key which replaces the deprecated key and is not null. 1039 * 1040 * Values are processed for <a href="#VariableExpansion">variable expansion</a> 1041 * before being returned. 1042 * 1043 * @param name the property name, will be trimmed before get value. 1044 * @return the value of the <code>name</code> or its replacing property, 1045 * or null if no such property exists. 1046 */ 1047 public String get(String name) { 1048 String[] names = handleDeprecation(deprecationContext.get(), name); 1049 String result = null; 1050 for(String n : names) { 1051 result = substituteVars(getProps().getProperty(n)); 1052 } 1053 return result; 1054 } 1055 1056 /** 1057 * Set Configuration to allow keys without values during setup. Intended 1058 * for use during testing. 1059 * 1060 * @param val If true, will allow Configuration to store keys without values 1061 */ 1062 @VisibleForTesting 1063 public void setAllowNullValueProperties( boolean val ) { 1064 this.allowNullValueProperties = val; 1065 } 1066 1067 /** 1068 * Return existence of the <code>name</code> property, but only for 1069 * names which have no valid value, usually non-existent or commented 1070 * out in XML. 1071 * 1072 * @param name the property name 1073 * @return true if the property <code>name</code> exists without value 1074 */ 1075 @VisibleForTesting 1076 public boolean onlyKeyExists(String name) { 1077 String[] names = handleDeprecation(deprecationContext.get(), name); 1078 for(String n : names) { 1079 if ( getProps().getProperty(n,DEFAULT_STRING_CHECK) 1080 .equals(DEFAULT_STRING_CHECK) ) { 1081 return true; 1082 } 1083 } 1084 return false; 1085 } 1086 1087 /** 1088 * Get the value of the <code>name</code> property as a trimmed <code>String</code>, 1089 * <code>null</code> if no such property exists. 1090 * If the key is deprecated, it returns the value of 1091 * the first key which replaces the deprecated key and is not null 1092 * 1093 * Values are processed for <a href="#VariableExpansion">variable expansion</a> 1094 * before being returned. 1095 * 1096 * @param name the property name. 1097 * @return the value of the <code>name</code> or its replacing property, 1098 * or null if no such property exists. 1099 */ 1100 public String getTrimmed(String name) { 1101 String value = get(name); 1102 1103 if (null == value) { 1104 return null; 1105 } else { 1106 return value.trim(); 1107 } 1108 } 1109 1110 /** 1111 * Get the value of the <code>name</code> property as a trimmed <code>String</code>, 1112 * <code>defaultValue</code> if no such property exists. 1113 * See @{Configuration#getTrimmed} for more details. 1114 * 1115 * @param name the property name. 1116 * @param defaultValue the property default value. 1117 * @return the value of the <code>name</code> or defaultValue 1118 * if it is not set. 1119 */ 1120 public String getTrimmed(String name, String defaultValue) { 1121 String ret = getTrimmed(name); 1122 return ret == null ? defaultValue : ret; 1123 } 1124 1125 /** 1126 * Get the value of the <code>name</code> property, without doing 1127 * <a href="#VariableExpansion">variable expansion</a>.If the key is 1128 * deprecated, it returns the value of the first key which replaces 1129 * the deprecated key and is not null. 1130 * 1131 * @param name the property name. 1132 * @return the value of the <code>name</code> property or 1133 * its replacing property and null if no such property exists. 1134 */ 1135 public String getRaw(String name) { 1136 String[] names = handleDeprecation(deprecationContext.get(), name); 1137 String result = null; 1138 for(String n : names) { 1139 result = getProps().getProperty(n); 1140 } 1141 return result; 1142 } 1143 1144 /** 1145 * Returns alternative names (non-deprecated keys or previously-set deprecated keys) 1146 * for a given non-deprecated key. 1147 * If the given key is deprecated, return null. 1148 * 1149 * @param name property name. 1150 * @return alternative names. 1151 */ 1152 private String[] getAlternativeNames(String name) { 1153 String altNames[] = null; 1154 DeprecatedKeyInfo keyInfo = null; 1155 DeprecationContext cur = deprecationContext.get(); 1156 String depKey = cur.getReverseDeprecatedKeyMap().get(name); 1157 if(depKey != null) { 1158 keyInfo = cur.getDeprecatedKeyMap().get(depKey); 1159 if(keyInfo.newKeys.length > 0) { 1160 if(getProps().containsKey(depKey)) { 1161 //if deprecated key is previously set explicitly 1162 List<String> list = new ArrayList<String>(); 1163 list.addAll(Arrays.asList(keyInfo.newKeys)); 1164 list.add(depKey); 1165 altNames = list.toArray(new String[list.size()]); 1166 } 1167 else { 1168 altNames = keyInfo.newKeys; 1169 } 1170 } 1171 } 1172 return altNames; 1173 } 1174 1175 /** 1176 * Set the <code>value</code> of the <code>name</code> property. If 1177 * <code>name</code> is deprecated or there is a deprecated name associated to it, 1178 * it sets the value to both names. Name will be trimmed before put into 1179 * configuration. 1180 * 1181 * @param name property name. 1182 * @param value property value. 1183 */ 1184 public void set(String name, String value) { 1185 set(name, value, null); 1186 } 1187 1188 /** 1189 * Set the <code>value</code> of the <code>name</code> property. If 1190 * <code>name</code> is deprecated, it also sets the <code>value</code> to 1191 * the keys that replace the deprecated key. Name will be trimmed before put 1192 * into configuration. 1193 * 1194 * @param name property name. 1195 * @param value property value. 1196 * @param source the place that this configuration value came from 1197 * (For debugging). 1198 * @throws IllegalArgumentException when the value or name is null. 1199 */ 1200 public void set(String name, String value, String source) { 1201 Preconditions.checkArgument( 1202 name != null, 1203 "Property name must not be null"); 1204 Preconditions.checkArgument( 1205 value != null, 1206 "The value of property " + name + " must not be null"); 1207 name = name.trim(); 1208 DeprecationContext deprecations = deprecationContext.get(); 1209 if (deprecations.getDeprecatedKeyMap().isEmpty()) { 1210 getProps(); 1211 } 1212 getOverlay().setProperty(name, value); 1213 getProps().setProperty(name, value); 1214 String newSource = (source == null ? "programmatically" : source); 1215 1216 if (!isDeprecated(name)) { 1217 updatingResource.put(name, new String[] {newSource}); 1218 String[] altNames = getAlternativeNames(name); 1219 if(altNames != null) { 1220 for(String n: altNames) { 1221 if(!n.equals(name)) { 1222 getOverlay().setProperty(n, value); 1223 getProps().setProperty(n, value); 1224 updatingResource.put(n, new String[] {newSource}); 1225 } 1226 } 1227 } 1228 } 1229 else { 1230 String[] names = handleDeprecation(deprecationContext.get(), name); 1231 String altSource = "because " + name + " is deprecated"; 1232 for(String n : names) { 1233 getOverlay().setProperty(n, value); 1234 getProps().setProperty(n, value); 1235 updatingResource.put(n, new String[] {altSource}); 1236 } 1237 } 1238 } 1239 1240 @VisibleForTesting 1241 void logDeprecation(String message) { 1242 LOG_DEPRECATION.info(message); 1243 } 1244 1245 /** 1246 * Unset a previously set property. 1247 */ 1248 public synchronized void unset(String name) { 1249 String[] names = null; 1250 if (!isDeprecated(name)) { 1251 names = getAlternativeNames(name); 1252 if(names == null) { 1253 names = new String[]{name}; 1254 } 1255 } 1256 else { 1257 names = handleDeprecation(deprecationContext.get(), name); 1258 } 1259 1260 for(String n: names) { 1261 getOverlay().remove(n); 1262 getProps().remove(n); 1263 } 1264 } 1265 1266 /** 1267 * Sets a property if it is currently unset. 1268 * @param name the property name 1269 * @param value the new value 1270 */ 1271 public synchronized void setIfUnset(String name, String value) { 1272 if (get(name) == null) { 1273 set(name, value); 1274 } 1275 } 1276 1277 private synchronized Properties getOverlay() { 1278 if (overlay==null){ 1279 overlay=new Properties(); 1280 } 1281 return overlay; 1282 } 1283 1284 /** 1285 * Get the value of the <code>name</code>. If the key is deprecated, 1286 * it returns the value of the first key which replaces the deprecated key 1287 * and is not null. 1288 * If no such property exists, 1289 * then <code>defaultValue</code> is returned. 1290 * 1291 * @param name property name, will be trimmed before get value. 1292 * @param defaultValue default value. 1293 * @return property value, or <code>defaultValue</code> if the property 1294 * doesn't exist. 1295 */ 1296 public String get(String name, String defaultValue) { 1297 String[] names = handleDeprecation(deprecationContext.get(), name); 1298 String result = null; 1299 for(String n : names) { 1300 result = substituteVars(getProps().getProperty(n, defaultValue)); 1301 } 1302 return result; 1303 } 1304 1305 /** 1306 * Get the value of the <code>name</code> property as an <code>int</code>. 1307 * 1308 * If no such property exists, the provided default value is returned, 1309 * or if the specified value is not a valid <code>int</code>, 1310 * then an error is thrown. 1311 * 1312 * @param name property name. 1313 * @param defaultValue default value. 1314 * @throws NumberFormatException when the value is invalid 1315 * @return property value as an <code>int</code>, 1316 * or <code>defaultValue</code>. 1317 */ 1318 public int getInt(String name, int defaultValue) { 1319 String valueString = getTrimmed(name); 1320 if (valueString == null) 1321 return defaultValue; 1322 String hexString = getHexDigits(valueString); 1323 if (hexString != null) { 1324 return Integer.parseInt(hexString, 16); 1325 } 1326 return Integer.parseInt(valueString); 1327 } 1328 1329 /** 1330 * Get the value of the <code>name</code> property as a set of comma-delimited 1331 * <code>int</code> values. 1332 * 1333 * If no such property exists, an empty array is returned. 1334 * 1335 * @param name property name 1336 * @return property value interpreted as an array of comma-delimited 1337 * <code>int</code> values 1338 */ 1339 public int[] getInts(String name) { 1340 String[] strings = getTrimmedStrings(name); 1341 int[] ints = new int[strings.length]; 1342 for (int i = 0; i < strings.length; i++) { 1343 ints[i] = Integer.parseInt(strings[i]); 1344 } 1345 return ints; 1346 } 1347 1348 /** 1349 * Set the value of the <code>name</code> property to an <code>int</code>. 1350 * 1351 * @param name property name. 1352 * @param value <code>int</code> value of the property. 1353 */ 1354 public void setInt(String name, int value) { 1355 set(name, Integer.toString(value)); 1356 } 1357 1358 1359 /** 1360 * Get the value of the <code>name</code> property as a <code>long</code>. 1361 * If no such property exists, the provided default value is returned, 1362 * or if the specified value is not a valid <code>long</code>, 1363 * then an error is thrown. 1364 * 1365 * @param name property name. 1366 * @param defaultValue default value. 1367 * @throws NumberFormatException when the value is invalid 1368 * @return property value as a <code>long</code>, 1369 * or <code>defaultValue</code>. 1370 */ 1371 public long getLong(String name, long defaultValue) { 1372 String valueString = getTrimmed(name); 1373 if (valueString == null) 1374 return defaultValue; 1375 String hexString = getHexDigits(valueString); 1376 if (hexString != null) { 1377 return Long.parseLong(hexString, 16); 1378 } 1379 return Long.parseLong(valueString); 1380 } 1381 1382 /** 1383 * Get the value of the <code>name</code> property as a <code>long</code> or 1384 * human readable format. If no such property exists, the provided default 1385 * value is returned, or if the specified value is not a valid 1386 * <code>long</code> or human readable format, then an error is thrown. You 1387 * can use the following suffix (case insensitive): k(kilo), m(mega), g(giga), 1388 * t(tera), p(peta), e(exa) 1389 * 1390 * @param name property name. 1391 * @param defaultValue default value. 1392 * @throws NumberFormatException when the value is invalid 1393 * @return property value as a <code>long</code>, 1394 * or <code>defaultValue</code>. 1395 */ 1396 public long getLongBytes(String name, long defaultValue) { 1397 String valueString = getTrimmed(name); 1398 if (valueString == null) 1399 return defaultValue; 1400 return StringUtils.TraditionalBinaryPrefix.string2long(valueString); 1401 } 1402 1403 private String getHexDigits(String value) { 1404 boolean negative = false; 1405 String str = value; 1406 String hexString = null; 1407 if (value.startsWith("-")) { 1408 negative = true; 1409 str = value.substring(1); 1410 } 1411 if (str.startsWith("0x") || str.startsWith("0X")) { 1412 hexString = str.substring(2); 1413 if (negative) { 1414 hexString = "-" + hexString; 1415 } 1416 return hexString; 1417 } 1418 return null; 1419 } 1420 1421 /** 1422 * Set the value of the <code>name</code> property to a <code>long</code>. 1423 * 1424 * @param name property name. 1425 * @param value <code>long</code> value of the property. 1426 */ 1427 public void setLong(String name, long value) { 1428 set(name, Long.toString(value)); 1429 } 1430 1431 /** 1432 * Get the value of the <code>name</code> property as a <code>float</code>. 1433 * If no such property exists, the provided default value is returned, 1434 * or if the specified value is not a valid <code>float</code>, 1435 * then an error is thrown. 1436 * 1437 * @param name property name. 1438 * @param defaultValue default value. 1439 * @throws NumberFormatException when the value is invalid 1440 * @return property value as a <code>float</code>, 1441 * or <code>defaultValue</code>. 1442 */ 1443 public float getFloat(String name, float defaultValue) { 1444 String valueString = getTrimmed(name); 1445 if (valueString == null) 1446 return defaultValue; 1447 return Float.parseFloat(valueString); 1448 } 1449 1450 /** 1451 * Set the value of the <code>name</code> property to a <code>float</code>. 1452 * 1453 * @param name property name. 1454 * @param value property value. 1455 */ 1456 public void setFloat(String name, float value) { 1457 set(name,Float.toString(value)); 1458 } 1459 1460 /** 1461 * Get the value of the <code>name</code> property as a <code>double</code>. 1462 * If no such property exists, the provided default value is returned, 1463 * or if the specified value is not a valid <code>double</code>, 1464 * then an error is thrown. 1465 * 1466 * @param name property name. 1467 * @param defaultValue default value. 1468 * @throws NumberFormatException when the value is invalid 1469 * @return property value as a <code>double</code>, 1470 * or <code>defaultValue</code>. 1471 */ 1472 public double getDouble(String name, double defaultValue) { 1473 String valueString = getTrimmed(name); 1474 if (valueString == null) 1475 return defaultValue; 1476 return Double.parseDouble(valueString); 1477 } 1478 1479 /** 1480 * Set the value of the <code>name</code> property to a <code>double</code>. 1481 * 1482 * @param name property name. 1483 * @param value property value. 1484 */ 1485 public void setDouble(String name, double value) { 1486 set(name,Double.toString(value)); 1487 } 1488 1489 /** 1490 * Get the value of the <code>name</code> property as a <code>boolean</code>. 1491 * If no such property is specified, or if the specified value is not a valid 1492 * <code>boolean</code>, then <code>defaultValue</code> is returned. 1493 * 1494 * @param name property name. 1495 * @param defaultValue default value. 1496 * @return property value as a <code>boolean</code>, 1497 * or <code>defaultValue</code>. 1498 */ 1499 public boolean getBoolean(String name, boolean defaultValue) { 1500 String valueString = getTrimmed(name); 1501 if (null == valueString || valueString.isEmpty()) { 1502 return defaultValue; 1503 } 1504 1505 if (StringUtils.equalsIgnoreCase("true", valueString)) 1506 return true; 1507 else if (StringUtils.equalsIgnoreCase("false", valueString)) 1508 return false; 1509 else return defaultValue; 1510 } 1511 1512 /** 1513 * Set the value of the <code>name</code> property to a <code>boolean</code>. 1514 * 1515 * @param name property name. 1516 * @param value <code>boolean</code> value of the property. 1517 */ 1518 public void setBoolean(String name, boolean value) { 1519 set(name, Boolean.toString(value)); 1520 } 1521 1522 /** 1523 * Set the given property, if it is currently unset. 1524 * @param name property name 1525 * @param value new value 1526 */ 1527 public void setBooleanIfUnset(String name, boolean value) { 1528 setIfUnset(name, Boolean.toString(value)); 1529 } 1530 1531 /** 1532 * Set the value of the <code>name</code> property to the given type. This 1533 * is equivalent to <code>set(<name>, value.toString())</code>. 1534 * @param name property name 1535 * @param value new value 1536 */ 1537 public <T extends Enum<T>> void setEnum(String name, T value) { 1538 set(name, value.toString()); 1539 } 1540 1541 /** 1542 * Return value matching this enumerated type. 1543 * Note that the returned value is trimmed by this method. 1544 * @param name Property name 1545 * @param defaultValue Value returned if no mapping exists 1546 * @throws IllegalArgumentException If mapping is illegal for the type 1547 * provided 1548 */ 1549 public <T extends Enum<T>> T getEnum(String name, T defaultValue) { 1550 final String val = getTrimmed(name); 1551 return null == val 1552 ? defaultValue 1553 : Enum.valueOf(defaultValue.getDeclaringClass(), val); 1554 } 1555 1556 enum ParsedTimeDuration { 1557 NS { 1558 TimeUnit unit() { return TimeUnit.NANOSECONDS; } 1559 String suffix() { return "ns"; } 1560 }, 1561 US { 1562 TimeUnit unit() { return TimeUnit.MICROSECONDS; } 1563 String suffix() { return "us"; } 1564 }, 1565 MS { 1566 TimeUnit unit() { return TimeUnit.MILLISECONDS; } 1567 String suffix() { return "ms"; } 1568 }, 1569 S { 1570 TimeUnit unit() { return TimeUnit.SECONDS; } 1571 String suffix() { return "s"; } 1572 }, 1573 M { 1574 TimeUnit unit() { return TimeUnit.MINUTES; } 1575 String suffix() { return "m"; } 1576 }, 1577 H { 1578 TimeUnit unit() { return TimeUnit.HOURS; } 1579 String suffix() { return "h"; } 1580 }, 1581 D { 1582 TimeUnit unit() { return TimeUnit.DAYS; } 1583 String suffix() { return "d"; } 1584 }; 1585 abstract TimeUnit unit(); 1586 abstract String suffix(); 1587 static ParsedTimeDuration unitFor(String s) { 1588 for (ParsedTimeDuration ptd : values()) { 1589 // iteration order is in decl order, so SECONDS matched last 1590 if (s.endsWith(ptd.suffix())) { 1591 return ptd; 1592 } 1593 } 1594 return null; 1595 } 1596 static ParsedTimeDuration unitFor(TimeUnit unit) { 1597 for (ParsedTimeDuration ptd : values()) { 1598 if (ptd.unit() == unit) { 1599 return ptd; 1600 } 1601 } 1602 return null; 1603 } 1604 } 1605 1606 /** 1607 * Set the value of <code>name</code> to the given time duration. This 1608 * is equivalent to <code>set(<name>, value + <time suffix>)</code>. 1609 * @param name Property name 1610 * @param value Time duration 1611 * @param unit Unit of time 1612 */ 1613 public void setTimeDuration(String name, long value, TimeUnit unit) { 1614 set(name, value + ParsedTimeDuration.unitFor(unit).suffix()); 1615 } 1616 1617 /** 1618 * Return time duration in the given time unit. Valid units are encoded in 1619 * properties as suffixes: nanoseconds (ns), microseconds (us), milliseconds 1620 * (ms), seconds (s), minutes (m), hours (h), and days (d). 1621 * @param name Property name 1622 * @param defaultValue Value returned if no mapping exists. 1623 * @param unit Unit to convert the stored property, if it exists. 1624 * @throws NumberFormatException If the property stripped of its unit is not 1625 * a number 1626 */ 1627 public long getTimeDuration(String name, long defaultValue, TimeUnit unit) { 1628 String vStr = get(name); 1629 if (null == vStr) { 1630 return defaultValue; 1631 } else { 1632 return getTimeDurationHelper(name, vStr, unit); 1633 } 1634 } 1635 1636 public long getTimeDuration(String name, String defaultValue, TimeUnit unit) { 1637 String vStr = get(name); 1638 if (null == vStr) { 1639 return getTimeDurationHelper(name, defaultValue, unit); 1640 } else { 1641 return getTimeDurationHelper(name, vStr, unit); 1642 } 1643 } 1644 1645 private long getTimeDurationHelper(String name, String vStr, TimeUnit unit) { 1646 vStr = vStr.trim(); 1647 vStr = StringUtils.toLowerCase(vStr); 1648 ParsedTimeDuration vUnit = ParsedTimeDuration.unitFor(vStr); 1649 if (null == vUnit) { 1650 logDeprecation("No unit for " + name + "(" + vStr + ") assuming " + unit); 1651 vUnit = ParsedTimeDuration.unitFor(unit); 1652 } else { 1653 vStr = vStr.substring(0, vStr.lastIndexOf(vUnit.suffix())); 1654 } 1655 1656 long raw = Long.parseLong(vStr); 1657 long converted = unit.convert(raw, vUnit.unit()); 1658 if (vUnit.unit().convert(converted, unit) < raw) { 1659 logDeprecation("Possible loss of precision converting " + vStr 1660 + vUnit.suffix() + " to " + unit + " for " + name); 1661 } 1662 return converted; 1663 } 1664 1665 public long[] getTimeDurations(String name, TimeUnit unit) { 1666 String[] strings = getTrimmedStrings(name); 1667 long[] durations = new long[strings.length]; 1668 for (int i = 0; i < strings.length; i++) { 1669 durations[i] = getTimeDurationHelper(name, strings[i], unit); 1670 } 1671 return durations; 1672 } 1673 1674 /** 1675 * Get the value of the <code>name</code> property as a <code>Pattern</code>. 1676 * If no such property is specified, or if the specified value is not a valid 1677 * <code>Pattern</code>, then <code>DefaultValue</code> is returned. 1678 * Note that the returned value is NOT trimmed by this method. 1679 * 1680 * @param name property name 1681 * @param defaultValue default value 1682 * @return property value as a compiled Pattern, or defaultValue 1683 */ 1684 public Pattern getPattern(String name, Pattern defaultValue) { 1685 String valString = get(name); 1686 if (null == valString || valString.isEmpty()) { 1687 return defaultValue; 1688 } 1689 try { 1690 return Pattern.compile(valString); 1691 } catch (PatternSyntaxException pse) { 1692 LOG.warn("Regular expression '" + valString + "' for property '" + 1693 name + "' not valid. Using default", pse); 1694 return defaultValue; 1695 } 1696 } 1697 1698 /** 1699 * Set the given property to <code>Pattern</code>. 1700 * If the pattern is passed as null, sets the empty pattern which results in 1701 * further calls to getPattern(...) returning the default value. 1702 * 1703 * @param name property name 1704 * @param pattern new value 1705 */ 1706 public void setPattern(String name, Pattern pattern) { 1707 assert pattern != null : "Pattern cannot be null"; 1708 set(name, pattern.pattern()); 1709 } 1710 1711 /** 1712 * Gets information about why a property was set. Typically this is the 1713 * path to the resource objects (file, URL, etc.) the property came from, but 1714 * it can also indicate that it was set programmatically, or because of the 1715 * command line. 1716 * 1717 * @param name - The property name to get the source of. 1718 * @return null - If the property or its source wasn't found. Otherwise, 1719 * returns a list of the sources of the resource. The older sources are 1720 * the first ones in the list. So for example if a configuration is set from 1721 * the command line, and then written out to a file that is read back in the 1722 * first entry would indicate that it was set from the command line, while 1723 * the second one would indicate the file that the new configuration was read 1724 * in from. 1725 */ 1726 @InterfaceStability.Unstable 1727 public synchronized String[] getPropertySources(String name) { 1728 if (properties == null) { 1729 // If properties is null, it means a resource was newly added 1730 // but the props were cleared so as to load it upon future 1731 // requests. So lets force a load by asking a properties list. 1732 getProps(); 1733 } 1734 // Return a null right away if our properties still 1735 // haven't loaded or the resource mapping isn't defined 1736 if (properties == null || updatingResource == null) { 1737 return null; 1738 } else { 1739 String[] source = updatingResource.get(name); 1740 if(source == null) { 1741 return null; 1742 } else { 1743 return Arrays.copyOf(source, source.length); 1744 } 1745 } 1746 } 1747 1748 /** 1749 * A class that represents a set of positive integer ranges. It parses 1750 * strings of the form: "2-3,5,7-" where ranges are separated by comma and 1751 * the lower/upper bounds are separated by dash. Either the lower or upper 1752 * bound may be omitted meaning all values up to or over. So the string 1753 * above means 2, 3, 5, and 7, 8, 9, ... 1754 */ 1755 public static class IntegerRanges implements Iterable<Integer>{ 1756 private static class Range { 1757 int start; 1758 int end; 1759 } 1760 1761 private static class RangeNumberIterator implements Iterator<Integer> { 1762 Iterator<Range> internal; 1763 int at; 1764 int end; 1765 1766 public RangeNumberIterator(List<Range> ranges) { 1767 if (ranges != null) { 1768 internal = ranges.iterator(); 1769 } 1770 at = -1; 1771 end = -2; 1772 } 1773 1774 @Override 1775 public boolean hasNext() { 1776 if (at <= end) { 1777 return true; 1778 } else if (internal != null){ 1779 return internal.hasNext(); 1780 } 1781 return false; 1782 } 1783 1784 @Override 1785 public Integer next() { 1786 if (at <= end) { 1787 at++; 1788 return at - 1; 1789 } else if (internal != null){ 1790 Range found = internal.next(); 1791 if (found != null) { 1792 at = found.start; 1793 end = found.end; 1794 at++; 1795 return at - 1; 1796 } 1797 } 1798 return null; 1799 } 1800 1801 @Override 1802 public void remove() { 1803 throw new UnsupportedOperationException(); 1804 } 1805 }; 1806 1807 List<Range> ranges = new ArrayList<Range>(); 1808 1809 public IntegerRanges() { 1810 } 1811 1812 public IntegerRanges(String newValue) { 1813 StringTokenizer itr = new StringTokenizer(newValue, ","); 1814 while (itr.hasMoreTokens()) { 1815 String rng = itr.nextToken().trim(); 1816 String[] parts = rng.split("-", 3); 1817 if (parts.length < 1 || parts.length > 2) { 1818 throw new IllegalArgumentException("integer range badly formed: " + 1819 rng); 1820 } 1821 Range r = new Range(); 1822 r.start = convertToInt(parts[0], 0); 1823 if (parts.length == 2) { 1824 r.end = convertToInt(parts[1], Integer.MAX_VALUE); 1825 } else { 1826 r.end = r.start; 1827 } 1828 if (r.start > r.end) { 1829 throw new IllegalArgumentException("IntegerRange from " + r.start + 1830 " to " + r.end + " is invalid"); 1831 } 1832 ranges.add(r); 1833 } 1834 } 1835 1836 /** 1837 * Convert a string to an int treating empty strings as the default value. 1838 * @param value the string value 1839 * @param defaultValue the value for if the string is empty 1840 * @return the desired integer 1841 */ 1842 private static int convertToInt(String value, int defaultValue) { 1843 String trim = value.trim(); 1844 if (trim.length() == 0) { 1845 return defaultValue; 1846 } 1847 return Integer.parseInt(trim); 1848 } 1849 1850 /** 1851 * Is the given value in the set of ranges 1852 * @param value the value to check 1853 * @return is the value in the ranges? 1854 */ 1855 public boolean isIncluded(int value) { 1856 for(Range r: ranges) { 1857 if (r.start <= value && value <= r.end) { 1858 return true; 1859 } 1860 } 1861 return false; 1862 } 1863 1864 /** 1865 * @return true if there are no values in this range, else false. 1866 */ 1867 public boolean isEmpty() { 1868 return ranges == null || ranges.isEmpty(); 1869 } 1870 1871 @Override 1872 public String toString() { 1873 StringBuilder result = new StringBuilder(); 1874 boolean first = true; 1875 for(Range r: ranges) { 1876 if (first) { 1877 first = false; 1878 } else { 1879 result.append(','); 1880 } 1881 result.append(r.start); 1882 result.append('-'); 1883 result.append(r.end); 1884 } 1885 return result.toString(); 1886 } 1887 1888 @Override 1889 public Iterator<Integer> iterator() { 1890 return new RangeNumberIterator(ranges); 1891 } 1892 1893 } 1894 1895 /** 1896 * Parse the given attribute as a set of integer ranges 1897 * @param name the attribute name 1898 * @param defaultValue the default value if it is not set 1899 * @return a new set of ranges from the configured value 1900 */ 1901 public IntegerRanges getRange(String name, String defaultValue) { 1902 return new IntegerRanges(get(name, defaultValue)); 1903 } 1904 1905 /** 1906 * Get the comma delimited values of the <code>name</code> property as 1907 * a collection of <code>String</code>s. 1908 * If no such property is specified then empty collection is returned. 1909 * <p> 1910 * This is an optimized version of {@link #getStrings(String)} 1911 * 1912 * @param name property name. 1913 * @return property value as a collection of <code>String</code>s. 1914 */ 1915 public Collection<String> getStringCollection(String name) { 1916 String valueString = get(name); 1917 return StringUtils.getStringCollection(valueString); 1918 } 1919 1920 /** 1921 * Get the comma delimited values of the <code>name</code> property as 1922 * an array of <code>String</code>s. 1923 * If no such property is specified then <code>null</code> is returned. 1924 * 1925 * @param name property name. 1926 * @return property value as an array of <code>String</code>s, 1927 * or <code>null</code>. 1928 */ 1929 public String[] getStrings(String name) { 1930 String valueString = get(name); 1931 return StringUtils.getStrings(valueString); 1932 } 1933 1934 /** 1935 * Get the comma delimited values of the <code>name</code> property as 1936 * an array of <code>String</code>s. 1937 * If no such property is specified then default value is returned. 1938 * 1939 * @param name property name. 1940 * @param defaultValue The default value 1941 * @return property value as an array of <code>String</code>s, 1942 * or default value. 1943 */ 1944 public String[] getStrings(String name, String... defaultValue) { 1945 String valueString = get(name); 1946 if (valueString == null) { 1947 return defaultValue; 1948 } else { 1949 return StringUtils.getStrings(valueString); 1950 } 1951 } 1952 1953 /** 1954 * Get the comma delimited values of the <code>name</code> property as 1955 * a collection of <code>String</code>s, trimmed of the leading and trailing whitespace. 1956 * If no such property is specified then empty <code>Collection</code> is returned. 1957 * 1958 * @param name property name. 1959 * @return property value as a collection of <code>String</code>s, or empty <code>Collection</code> 1960 */ 1961 public Collection<String> getTrimmedStringCollection(String name) { 1962 String valueString = get(name); 1963 if (null == valueString) { 1964 Collection<String> empty = new ArrayList<String>(); 1965 return empty; 1966 } 1967 return StringUtils.getTrimmedStringCollection(valueString); 1968 } 1969 1970 /** 1971 * Get the comma delimited values of the <code>name</code> property as 1972 * an array of <code>String</code>s, trimmed of the leading and trailing whitespace. 1973 * If no such property is specified then an empty array is returned. 1974 * 1975 * @param name property name. 1976 * @return property value as an array of trimmed <code>String</code>s, 1977 * or empty array. 1978 */ 1979 public String[] getTrimmedStrings(String name) { 1980 String valueString = get(name); 1981 return StringUtils.getTrimmedStrings(valueString); 1982 } 1983 1984 /** 1985 * Get the comma delimited values of the <code>name</code> property as 1986 * an array of <code>String</code>s, trimmed of the leading and trailing whitespace. 1987 * If no such property is specified then default value is returned. 1988 * 1989 * @param name property name. 1990 * @param defaultValue The default value 1991 * @return property value as an array of trimmed <code>String</code>s, 1992 * or default value. 1993 */ 1994 public String[] getTrimmedStrings(String name, String... defaultValue) { 1995 String valueString = get(name); 1996 if (null == valueString) { 1997 return defaultValue; 1998 } else { 1999 return StringUtils.getTrimmedStrings(valueString); 2000 } 2001 } 2002 2003 /** 2004 * Set the array of string values for the <code>name</code> property as 2005 * as comma delimited values. 2006 * 2007 * @param name property name. 2008 * @param values The values 2009 */ 2010 public void setStrings(String name, String... values) { 2011 set(name, StringUtils.arrayToString(values)); 2012 } 2013 2014 /** 2015 * Get the value for a known password configuration element. 2016 * In order to enable the elimination of clear text passwords in config, 2017 * this method attempts to resolve the property name as an alias through 2018 * the CredentialProvider API and conditionally fallsback to config. 2019 * @param name property name 2020 * @return password 2021 */ 2022 public char[] getPassword(String name) throws IOException { 2023 char[] pass = null; 2024 2025 pass = getPasswordFromCredentialProviders(name); 2026 2027 if (pass == null) { 2028 pass = getPasswordFromConfig(name); 2029 } 2030 2031 return pass; 2032 } 2033 2034 /** 2035 * Try and resolve the provided element name as a credential provider 2036 * alias. 2037 * @param name alias of the provisioned credential 2038 * @return password or null if not found 2039 * @throws IOException 2040 */ 2041 protected char[] getPasswordFromCredentialProviders(String name) 2042 throws IOException { 2043 char[] pass = null; 2044 try { 2045 List<CredentialProvider> providers = 2046 CredentialProviderFactory.getProviders(this); 2047 2048 if (providers != null) { 2049 for (CredentialProvider provider : providers) { 2050 try { 2051 CredentialEntry entry = provider.getCredentialEntry(name); 2052 if (entry != null) { 2053 pass = entry.getCredential(); 2054 break; 2055 } 2056 } 2057 catch (IOException ioe) { 2058 throw new IOException("Can't get key " + name + " from key provider" + 2059 "of type: " + provider.getClass().getName() + ".", ioe); 2060 } 2061 } 2062 } 2063 } 2064 catch (IOException ioe) { 2065 throw new IOException("Configuration problem with provider path.", ioe); 2066 } 2067 2068 return pass; 2069 } 2070 2071 /** 2072 * Fallback to clear text passwords in configuration. 2073 * @param name 2074 * @return clear text password or null 2075 */ 2076 protected char[] getPasswordFromConfig(String name) { 2077 char[] pass = null; 2078 if (getBoolean(CredentialProvider.CLEAR_TEXT_FALLBACK, 2079 CommonConfigurationKeysPublic. 2080 HADOOP_SECURITY_CREDENTIAL_CLEAR_TEXT_FALLBACK_DEFAULT)) { 2081 String passStr = get(name); 2082 if (passStr != null) { 2083 pass = passStr.toCharArray(); 2084 } 2085 } 2086 return pass; 2087 } 2088 2089 /** 2090 * Get the socket address for <code>hostProperty</code> as a 2091 * <code>InetSocketAddress</code>. If <code>hostProperty</code> is 2092 * <code>null</code>, <code>addressProperty</code> will be used. This 2093 * is useful for cases where we want to differentiate between host 2094 * bind address and address clients should use to establish connection. 2095 * 2096 * @param hostProperty bind host property name. 2097 * @param addressProperty address property name. 2098 * @param defaultAddressValue the default value 2099 * @param defaultPort the default port 2100 * @return InetSocketAddress 2101 */ 2102 public InetSocketAddress getSocketAddr( 2103 String hostProperty, 2104 String addressProperty, 2105 String defaultAddressValue, 2106 int defaultPort) { 2107 2108 InetSocketAddress bindAddr = getSocketAddr( 2109 addressProperty, defaultAddressValue, defaultPort); 2110 2111 final String host = get(hostProperty); 2112 2113 if (host == null || host.isEmpty()) { 2114 return bindAddr; 2115 } 2116 2117 return NetUtils.createSocketAddr( 2118 host, bindAddr.getPort(), hostProperty); 2119 } 2120 2121 /** 2122 * Get the socket address for <code>name</code> property as a 2123 * <code>InetSocketAddress</code>. 2124 * @param name property name. 2125 * @param defaultAddress the default value 2126 * @param defaultPort the default port 2127 * @return InetSocketAddress 2128 */ 2129 public InetSocketAddress getSocketAddr( 2130 String name, String defaultAddress, int defaultPort) { 2131 final String address = getTrimmed(name, defaultAddress); 2132 return NetUtils.createSocketAddr(address, defaultPort, name); 2133 } 2134 2135 /** 2136 * Set the socket address for the <code>name</code> property as 2137 * a <code>host:port</code>. 2138 */ 2139 public void setSocketAddr(String name, InetSocketAddress addr) { 2140 set(name, NetUtils.getHostPortString(addr)); 2141 } 2142 2143 /** 2144 * Set the socket address a client can use to connect for the 2145 * <code>name</code> property as a <code>host:port</code>. The wildcard 2146 * address is replaced with the local host's address. If the host and address 2147 * properties are configured the host component of the address will be combined 2148 * with the port component of the addr to generate the address. This is to allow 2149 * optional control over which host name is used in multi-home bind-host 2150 * cases where a host can have multiple names 2151 * @param hostProperty the bind-host configuration name 2152 * @param addressProperty the service address configuration name 2153 * @param defaultAddressValue the service default address configuration value 2154 * @param addr InetSocketAddress of the service listener 2155 * @return InetSocketAddress for clients to connect 2156 */ 2157 public InetSocketAddress updateConnectAddr( 2158 String hostProperty, 2159 String addressProperty, 2160 String defaultAddressValue, 2161 InetSocketAddress addr) { 2162 2163 final String host = get(hostProperty); 2164 final String connectHostPort = getTrimmed(addressProperty, defaultAddressValue); 2165 2166 if (host == null || host.isEmpty() || connectHostPort == null || connectHostPort.isEmpty()) { 2167 //not our case, fall back to original logic 2168 return updateConnectAddr(addressProperty, addr); 2169 } 2170 2171 final String connectHost = connectHostPort.split(":")[0]; 2172 // Create connect address using client address hostname and server port. 2173 return updateConnectAddr(addressProperty, NetUtils.createSocketAddrForHost( 2174 connectHost, addr.getPort())); 2175 } 2176 2177 /** 2178 * Set the socket address a client can use to connect for the 2179 * <code>name</code> property as a <code>host:port</code>. The wildcard 2180 * address is replaced with the local host's address. 2181 * @param name property name. 2182 * @param addr InetSocketAddress of a listener to store in the given property 2183 * @return InetSocketAddress for clients to connect 2184 */ 2185 public InetSocketAddress updateConnectAddr(String name, 2186 InetSocketAddress addr) { 2187 final InetSocketAddress connectAddr = NetUtils.getConnectAddress(addr); 2188 setSocketAddr(name, connectAddr); 2189 return connectAddr; 2190 } 2191 2192 /** 2193 * Load a class by name. 2194 * 2195 * @param name the class name. 2196 * @return the class object. 2197 * @throws ClassNotFoundException if the class is not found. 2198 */ 2199 public Class<?> getClassByName(String name) throws ClassNotFoundException { 2200 Class<?> ret = getClassByNameOrNull(name); 2201 if (ret == null) { 2202 throw new ClassNotFoundException("Class " + name + " not found"); 2203 } 2204 return ret; 2205 } 2206 2207 /** 2208 * Load a class by name, returning null rather than throwing an exception 2209 * if it couldn't be loaded. This is to avoid the overhead of creating 2210 * an exception. 2211 * 2212 * @param name the class name 2213 * @return the class object, or null if it could not be found. 2214 */ 2215 public Class<?> getClassByNameOrNull(String name) { 2216 Map<String, WeakReference<Class<?>>> map; 2217 2218 synchronized (CACHE_CLASSES) { 2219 map = CACHE_CLASSES.get(classLoader); 2220 if (map == null) { 2221 map = Collections.synchronizedMap( 2222 new WeakHashMap<String, WeakReference<Class<?>>>()); 2223 CACHE_CLASSES.put(classLoader, map); 2224 } 2225 } 2226 2227 Class<?> clazz = null; 2228 WeakReference<Class<?>> ref = map.get(name); 2229 if (ref != null) { 2230 clazz = ref.get(); 2231 } 2232 2233 if (clazz == null) { 2234 try { 2235 clazz = Class.forName(name, true, classLoader); 2236 } catch (ClassNotFoundException e) { 2237 // Leave a marker that the class isn't found 2238 map.put(name, new WeakReference<Class<?>>(NEGATIVE_CACHE_SENTINEL)); 2239 return null; 2240 } 2241 // two putters can race here, but they'll put the same class 2242 map.put(name, new WeakReference<Class<?>>(clazz)); 2243 return clazz; 2244 } else if (clazz == NEGATIVE_CACHE_SENTINEL) { 2245 return null; // not found 2246 } else { 2247 // cache hit 2248 return clazz; 2249 } 2250 } 2251 2252 /** 2253 * Get the value of the <code>name</code> property 2254 * as an array of <code>Class</code>. 2255 * The value of the property specifies a list of comma separated class names. 2256 * If no such property is specified, then <code>defaultValue</code> is 2257 * returned. 2258 * 2259 * @param name the property name. 2260 * @param defaultValue default value. 2261 * @return property value as a <code>Class[]</code>, 2262 * or <code>defaultValue</code>. 2263 */ 2264 public Class<?>[] getClasses(String name, Class<?> ... defaultValue) { 2265 String valueString = getRaw(name); 2266 if (null == valueString) { 2267 return defaultValue; 2268 } 2269 String[] classnames = getTrimmedStrings(name); 2270 try { 2271 Class<?>[] classes = new Class<?>[classnames.length]; 2272 for(int i = 0; i < classnames.length; i++) { 2273 classes[i] = getClassByName(classnames[i]); 2274 } 2275 return classes; 2276 } catch (ClassNotFoundException e) { 2277 throw new RuntimeException(e); 2278 } 2279 } 2280 2281 /** 2282 * Get the value of the <code>name</code> property as a <code>Class</code>. 2283 * If no such property is specified, then <code>defaultValue</code> is 2284 * returned. 2285 * 2286 * @param name the class name. 2287 * @param defaultValue default value. 2288 * @return property value as a <code>Class</code>, 2289 * or <code>defaultValue</code>. 2290 */ 2291 public Class<?> getClass(String name, Class<?> defaultValue) { 2292 String valueString = getTrimmed(name); 2293 if (valueString == null) 2294 return defaultValue; 2295 try { 2296 return getClassByName(valueString); 2297 } catch (ClassNotFoundException e) { 2298 throw new RuntimeException(e); 2299 } 2300 } 2301 2302 /** 2303 * Get the value of the <code>name</code> property as a <code>Class</code> 2304 * implementing the interface specified by <code>xface</code>. 2305 * 2306 * If no such property is specified, then <code>defaultValue</code> is 2307 * returned. 2308 * 2309 * An exception is thrown if the returned class does not implement the named 2310 * interface. 2311 * 2312 * @param name the class name. 2313 * @param defaultValue default value. 2314 * @param xface the interface implemented by the named class. 2315 * @return property value as a <code>Class</code>, 2316 * or <code>defaultValue</code>. 2317 */ 2318 public <U> Class<? extends U> getClass(String name, 2319 Class<? extends U> defaultValue, 2320 Class<U> xface) { 2321 try { 2322 Class<?> theClass = getClass(name, defaultValue); 2323 if (theClass != null && !xface.isAssignableFrom(theClass)) 2324 throw new RuntimeException(theClass+" not "+xface.getName()); 2325 else if (theClass != null) 2326 return theClass.asSubclass(xface); 2327 else 2328 return null; 2329 } catch (Exception e) { 2330 throw new RuntimeException(e); 2331 } 2332 } 2333 2334 /** 2335 * Get the value of the <code>name</code> property as a <code>List</code> 2336 * of objects implementing the interface specified by <code>xface</code>. 2337 * 2338 * An exception is thrown if any of the classes does not exist, or if it does 2339 * not implement the named interface. 2340 * 2341 * @param name the property name. 2342 * @param xface the interface implemented by the classes named by 2343 * <code>name</code>. 2344 * @return a <code>List</code> of objects implementing <code>xface</code>. 2345 */ 2346 @SuppressWarnings("unchecked") 2347 public <U> List<U> getInstances(String name, Class<U> xface) { 2348 List<U> ret = new ArrayList<U>(); 2349 Class<?>[] classes = getClasses(name); 2350 for (Class<?> cl: classes) { 2351 if (!xface.isAssignableFrom(cl)) { 2352 throw new RuntimeException(cl + " does not implement " + xface); 2353 } 2354 ret.add((U)ReflectionUtils.newInstance(cl, this)); 2355 } 2356 return ret; 2357 } 2358 2359 /** 2360 * Set the value of the <code>name</code> property to the name of a 2361 * <code>theClass</code> implementing the given interface <code>xface</code>. 2362 * 2363 * An exception is thrown if <code>theClass</code> does not implement the 2364 * interface <code>xface</code>. 2365 * 2366 * @param name property name. 2367 * @param theClass property value. 2368 * @param xface the interface implemented by the named class. 2369 */ 2370 public void setClass(String name, Class<?> theClass, Class<?> xface) { 2371 if (!xface.isAssignableFrom(theClass)) 2372 throw new RuntimeException(theClass+" not "+xface.getName()); 2373 set(name, theClass.getName()); 2374 } 2375 2376 /** 2377 * Get a local file under a directory named by <i>dirsProp</i> with 2378 * the given <i>path</i>. If <i>dirsProp</i> contains multiple directories, 2379 * then one is chosen based on <i>path</i>'s hash code. If the selected 2380 * directory does not exist, an attempt is made to create it. 2381 * 2382 * @param dirsProp directory in which to locate the file. 2383 * @param path file-path. 2384 * @return local file under the directory with the given path. 2385 */ 2386 public Path getLocalPath(String dirsProp, String path) 2387 throws IOException { 2388 String[] dirs = getTrimmedStrings(dirsProp); 2389 int hashCode = path.hashCode(); 2390 FileSystem fs = FileSystem.getLocal(this); 2391 for (int i = 0; i < dirs.length; i++) { // try each local dir 2392 int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length; 2393 Path file = new Path(dirs[index], path); 2394 Path dir = file.getParent(); 2395 if (fs.mkdirs(dir) || fs.exists(dir)) { 2396 return file; 2397 } 2398 } 2399 LOG.warn("Could not make " + path + 2400 " in local directories from " + dirsProp); 2401 for(int i=0; i < dirs.length; i++) { 2402 int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length; 2403 LOG.warn(dirsProp + "[" + index + "]=" + dirs[index]); 2404 } 2405 throw new IOException("No valid local directories in property: "+dirsProp); 2406 } 2407 2408 /** 2409 * Get a local file name under a directory named in <i>dirsProp</i> with 2410 * the given <i>path</i>. If <i>dirsProp</i> contains multiple directories, 2411 * then one is chosen based on <i>path</i>'s hash code. If the selected 2412 * directory does not exist, an attempt is made to create it. 2413 * 2414 * @param dirsProp directory in which to locate the file. 2415 * @param path file-path. 2416 * @return local file under the directory with the given path. 2417 */ 2418 public File getFile(String dirsProp, String path) 2419 throws IOException { 2420 String[] dirs = getTrimmedStrings(dirsProp); 2421 int hashCode = path.hashCode(); 2422 for (int i = 0; i < dirs.length; i++) { // try each local dir 2423 int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length; 2424 File file = new File(dirs[index], path); 2425 File dir = file.getParentFile(); 2426 if (dir.exists() || dir.mkdirs()) { 2427 return file; 2428 } 2429 } 2430 throw new IOException("No valid local directories in property: "+dirsProp); 2431 } 2432 2433 /** 2434 * Get the {@link URL} for the named resource. 2435 * 2436 * @param name resource name. 2437 * @return the url for the named resource. 2438 */ 2439 public URL getResource(String name) { 2440 return classLoader.getResource(name); 2441 } 2442 2443 /** 2444 * Get an input stream attached to the configuration resource with the 2445 * given <code>name</code>. 2446 * 2447 * @param name configuration resource name. 2448 * @return an input stream attached to the resource. 2449 */ 2450 public InputStream getConfResourceAsInputStream(String name) { 2451 try { 2452 URL url= getResource(name); 2453 2454 if (url == null) { 2455 LOG.info(name + " not found"); 2456 return null; 2457 } else { 2458 LOG.info("found resource " + name + " at " + url); 2459 } 2460 2461 return url.openStream(); 2462 } catch (Exception e) { 2463 return null; 2464 } 2465 } 2466 2467 /** 2468 * Get a {@link Reader} attached to the configuration resource with the 2469 * given <code>name</code>. 2470 * 2471 * @param name configuration resource name. 2472 * @return a reader attached to the resource. 2473 */ 2474 public Reader getConfResourceAsReader(String name) { 2475 try { 2476 URL url= getResource(name); 2477 2478 if (url == null) { 2479 LOG.info(name + " not found"); 2480 return null; 2481 } else { 2482 LOG.info("found resource " + name + " at " + url); 2483 } 2484 2485 return new InputStreamReader(url.openStream(), Charsets.UTF_8); 2486 } catch (Exception e) { 2487 return null; 2488 } 2489 } 2490 2491 /** 2492 * Get the set of parameters marked final. 2493 * 2494 * @return final parameter set. 2495 */ 2496 public Set<String> getFinalParameters() { 2497 Set<String> setFinalParams = Collections.newSetFromMap( 2498 new ConcurrentHashMap<String, Boolean>()); 2499 setFinalParams.addAll(finalParameters); 2500 return setFinalParams; 2501 } 2502 2503 protected synchronized Properties getProps() { 2504 if (properties == null) { 2505 properties = new Properties(); 2506 Map<String, String[]> backup = 2507 new ConcurrentHashMap<String, String[]>(updatingResource); 2508 loadResources(properties, resources, quietmode); 2509 2510 if (overlay != null) { 2511 properties.putAll(overlay); 2512 for (Map.Entry<Object,Object> item: overlay.entrySet()) { 2513 String key = (String)item.getKey(); 2514 String[] source = backup.get(key); 2515 if(source != null) { 2516 updatingResource.put(key, source); 2517 } 2518 } 2519 } 2520 } 2521 return properties; 2522 } 2523 2524 /** 2525 * Return the number of keys in the configuration. 2526 * 2527 * @return number of keys in the configuration. 2528 */ 2529 public int size() { 2530 return getProps().size(); 2531 } 2532 2533 /** 2534 * Clears all keys from the configuration. 2535 */ 2536 public void clear() { 2537 getProps().clear(); 2538 getOverlay().clear(); 2539 } 2540 2541 /** 2542 * Get an {@link Iterator} to go through the list of <code>String</code> 2543 * key-value pairs in the configuration. 2544 * 2545 * @return an iterator over the entries. 2546 */ 2547 @Override 2548 public Iterator<Map.Entry<String, String>> iterator() { 2549 // Get a copy of just the string to string pairs. After the old object 2550 // methods that allow non-strings to be put into configurations are removed, 2551 // we could replace properties with a Map<String,String> and get rid of this 2552 // code. 2553 Map<String,String> result = new HashMap<String,String>(); 2554 for(Map.Entry<Object,Object> item: getProps().entrySet()) { 2555 if (item.getKey() instanceof String && 2556 item.getValue() instanceof String) { 2557 result.put((String) item.getKey(), (String) item.getValue()); 2558 } 2559 } 2560 return result.entrySet().iterator(); 2561 } 2562 2563 /** 2564 * Constructs a mapping of configuration and includes all properties that 2565 * start with the specified configuration prefix. Property names in the 2566 * mapping are trimmed to remove the configuration prefix. 2567 * 2568 * @param confPrefix configuration prefix 2569 * @return mapping of configuration properties with prefix stripped 2570 */ 2571 public Map<String, String> getPropsWithPrefix(String confPrefix) { 2572 Map<String, String> configMap = new HashMap<>(); 2573 for (Map.Entry<String, String> entry : this) { 2574 String name = entry.getKey(); 2575 if (name.startsWith(confPrefix)) { 2576 String value = this.get(name); 2577 name = name.substring(confPrefix.length()); 2578 configMap.put(name, value); 2579 } 2580 } 2581 return configMap; 2582 } 2583 2584 private Document parse(DocumentBuilder builder, URL url) 2585 throws IOException, SAXException { 2586 if (!quietmode) { 2587 if (LOG.isDebugEnabled()) { 2588 LOG.debug("parsing URL " + url); 2589 } 2590 } 2591 if (url == null) { 2592 return null; 2593 } 2594 2595 URLConnection connection = url.openConnection(); 2596 if (connection instanceof JarURLConnection) { 2597 // Disable caching for JarURLConnection to avoid sharing JarFile 2598 // with other users. 2599 connection.setUseCaches(false); 2600 } 2601 return parse(builder, connection.getInputStream(), url.toString()); 2602 } 2603 2604 private Document parse(DocumentBuilder builder, InputStream is, 2605 String systemId) throws IOException, SAXException { 2606 if (!quietmode) { 2607 LOG.debug("parsing input stream " + is); 2608 } 2609 if (is == null) { 2610 return null; 2611 } 2612 try { 2613 return (systemId == null) ? builder.parse(is) : builder.parse(is, 2614 systemId); 2615 } finally { 2616 is.close(); 2617 } 2618 } 2619 2620 private void loadResources(Properties properties, 2621 ArrayList<Resource> resources, 2622 boolean quiet) { 2623 if(loadDefaults) { 2624 for (String resource : defaultResources) { 2625 loadResource(properties, new Resource(resource), quiet); 2626 } 2627 2628 //support the hadoop-site.xml as a deprecated case 2629 if(getResource("hadoop-site.xml")!=null) { 2630 loadResource(properties, new Resource("hadoop-site.xml"), quiet); 2631 } 2632 } 2633 2634 for (int i = 0; i < resources.size(); i++) { 2635 Resource ret = loadResource(properties, resources.get(i), quiet); 2636 if (ret != null) { 2637 resources.set(i, ret); 2638 } 2639 } 2640 } 2641 2642 private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) { 2643 String name = UNKNOWN_RESOURCE; 2644 try { 2645 Object resource = wrapper.getResource(); 2646 name = wrapper.getName(); 2647 2648 DocumentBuilderFactory docBuilderFactory 2649 = DocumentBuilderFactory.newInstance(); 2650 //ignore all comments inside the xml file 2651 docBuilderFactory.setIgnoringComments(true); 2652 2653 //allow includes in the xml file 2654 docBuilderFactory.setNamespaceAware(true); 2655 try { 2656 docBuilderFactory.setXIncludeAware(true); 2657 } catch (UnsupportedOperationException e) { 2658 LOG.error("Failed to set setXIncludeAware(true) for parser " 2659 + docBuilderFactory 2660 + ":" + e, 2661 e); 2662 } 2663 DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); 2664 Document doc = null; 2665 Element root = null; 2666 boolean returnCachedProperties = false; 2667 2668 if (resource instanceof URL) { // an URL resource 2669 doc = parse(builder, (URL)resource); 2670 } else if (resource instanceof String) { // a CLASSPATH resource 2671 URL url = getResource((String)resource); 2672 doc = parse(builder, url); 2673 } else if (resource instanceof Path) { // a file resource 2674 // Can't use FileSystem API or we get an infinite loop 2675 // since FileSystem uses Configuration API. Use java.io.File instead. 2676 File file = new File(((Path)resource).toUri().getPath()) 2677 .getAbsoluteFile(); 2678 if (file.exists()) { 2679 if (!quiet) { 2680 LOG.debug("parsing File " + file); 2681 } 2682 doc = parse(builder, new BufferedInputStream( 2683 new FileInputStream(file)), ((Path)resource).toString()); 2684 } 2685 } else if (resource instanceof InputStream) { 2686 doc = parse(builder, (InputStream) resource, null); 2687 returnCachedProperties = true; 2688 } else if (resource instanceof Properties) { 2689 overlay(properties, (Properties)resource); 2690 } else if (resource instanceof Element) { 2691 root = (Element)resource; 2692 } 2693 2694 if (root == null) { 2695 if (doc == null) { 2696 if (quiet) { 2697 return null; 2698 } 2699 throw new RuntimeException(resource + " not found"); 2700 } 2701 root = doc.getDocumentElement(); 2702 } 2703 Properties toAddTo = properties; 2704 if(returnCachedProperties) { 2705 toAddTo = new Properties(); 2706 } 2707 if (!"configuration".equals(root.getTagName())) 2708 LOG.fatal("bad conf file: top-level element not <configuration>"); 2709 NodeList props = root.getChildNodes(); 2710 DeprecationContext deprecations = deprecationContext.get(); 2711 for (int i = 0; i < props.getLength(); i++) { 2712 Node propNode = props.item(i); 2713 if (!(propNode instanceof Element)) 2714 continue; 2715 Element prop = (Element)propNode; 2716 if ("configuration".equals(prop.getTagName())) { 2717 loadResource(toAddTo, new Resource(prop, name), quiet); 2718 continue; 2719 } 2720 if (!"property".equals(prop.getTagName())) 2721 LOG.warn("bad conf file: element not <property>"); 2722 2723 String attr = null; 2724 String value = null; 2725 boolean finalParameter = false; 2726 LinkedList<String> source = new LinkedList<String>(); 2727 2728 Attr propAttr = prop.getAttributeNode("name"); 2729 if (propAttr != null) 2730 attr = StringInterner.weakIntern(propAttr.getValue()); 2731 propAttr = prop.getAttributeNode("value"); 2732 if (propAttr != null) 2733 value = StringInterner.weakIntern(propAttr.getValue()); 2734 propAttr = prop.getAttributeNode("final"); 2735 if (propAttr != null) 2736 finalParameter = "true".equals(propAttr.getValue()); 2737 propAttr = prop.getAttributeNode("source"); 2738 if (propAttr != null) 2739 source.add(StringInterner.weakIntern(propAttr.getValue())); 2740 2741 NodeList fields = prop.getChildNodes(); 2742 for (int j = 0; j < fields.getLength(); j++) { 2743 Node fieldNode = fields.item(j); 2744 if (!(fieldNode instanceof Element)) 2745 continue; 2746 Element field = (Element)fieldNode; 2747 if ("name".equals(field.getTagName()) && field.hasChildNodes()) 2748 attr = StringInterner.weakIntern( 2749 ((Text)field.getFirstChild()).getData().trim()); 2750 if ("value".equals(field.getTagName()) && field.hasChildNodes()) 2751 value = StringInterner.weakIntern( 2752 ((Text)field.getFirstChild()).getData()); 2753 if ("final".equals(field.getTagName()) && field.hasChildNodes()) 2754 finalParameter = "true".equals(((Text)field.getFirstChild()).getData()); 2755 if ("source".equals(field.getTagName()) && field.hasChildNodes()) 2756 source.add(StringInterner.weakIntern( 2757 ((Text)field.getFirstChild()).getData())); 2758 } 2759 source.add(name); 2760 2761 // Ignore this parameter if it has already been marked as 'final' 2762 if (attr != null) { 2763 if (deprecations.getDeprecatedKeyMap().containsKey(attr)) { 2764 DeprecatedKeyInfo keyInfo = 2765 deprecations.getDeprecatedKeyMap().get(attr); 2766 keyInfo.clearAccessed(); 2767 for (String key:keyInfo.newKeys) { 2768 // update new keys with deprecated key's value 2769 loadProperty(toAddTo, name, key, value, finalParameter, 2770 source.toArray(new String[source.size()])); 2771 } 2772 } 2773 else { 2774 loadProperty(toAddTo, name, attr, value, finalParameter, 2775 source.toArray(new String[source.size()])); 2776 } 2777 } 2778 } 2779 2780 if (returnCachedProperties) { 2781 overlay(properties, toAddTo); 2782 return new Resource(toAddTo, name); 2783 } 2784 return null; 2785 } catch (IOException e) { 2786 LOG.fatal("error parsing conf " + name, e); 2787 throw new RuntimeException(e); 2788 } catch (DOMException e) { 2789 LOG.fatal("error parsing conf " + name, e); 2790 throw new RuntimeException(e); 2791 } catch (SAXException e) { 2792 LOG.fatal("error parsing conf " + name, e); 2793 throw new RuntimeException(e); 2794 } catch (ParserConfigurationException e) { 2795 LOG.fatal("error parsing conf " + name , e); 2796 throw new RuntimeException(e); 2797 } 2798 } 2799 2800 private void overlay(Properties to, Properties from) { 2801 for (Entry<Object, Object> entry: from.entrySet()) { 2802 to.put(entry.getKey(), entry.getValue()); 2803 } 2804 } 2805 2806 private void loadProperty(Properties properties, String name, String attr, 2807 String value, boolean finalParameter, String[] source) { 2808 if (value != null || allowNullValueProperties) { 2809 if (value == null) { 2810 value = DEFAULT_STRING_CHECK; 2811 } 2812 if (!finalParameters.contains(attr)) { 2813 properties.setProperty(attr, value); 2814 if(source != null) { 2815 updatingResource.put(attr, source); 2816 } 2817 } else if (!value.equals(properties.getProperty(attr))) { 2818 LOG.warn(name+":an attempt to override final parameter: "+attr 2819 +"; Ignoring."); 2820 } 2821 } 2822 if (finalParameter && attr != null) { 2823 finalParameters.add(attr); 2824 } 2825 } 2826 2827 /** 2828 * Write out the non-default properties in this configuration to the given 2829 * {@link OutputStream} using UTF-8 encoding. 2830 * 2831 * @param out the output stream to write to. 2832 */ 2833 public void writeXml(OutputStream out) throws IOException { 2834 writeXml(new OutputStreamWriter(out, "UTF-8")); 2835 } 2836 2837 /** 2838 * Write out the non-default properties in this configuration to the given 2839 * {@link Writer}. 2840 * 2841 * @param out the writer to write to. 2842 */ 2843 public void writeXml(Writer out) throws IOException { 2844 Document doc = asXmlDocument(); 2845 2846 try { 2847 DOMSource source = new DOMSource(doc); 2848 StreamResult result = new StreamResult(out); 2849 TransformerFactory transFactory = TransformerFactory.newInstance(); 2850 Transformer transformer = transFactory.newTransformer(); 2851 2852 // Important to not hold Configuration log while writing result, since 2853 // 'out' may be an HDFS stream which needs to lock this configuration 2854 // from another thread. 2855 transformer.transform(source, result); 2856 } catch (TransformerException te) { 2857 throw new IOException(te); 2858 } 2859 } 2860 2861 /** 2862 * Return the XML DOM corresponding to this Configuration. 2863 */ 2864 private synchronized Document asXmlDocument() throws IOException { 2865 Document doc; 2866 try { 2867 doc = 2868 DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); 2869 } catch (ParserConfigurationException pe) { 2870 throw new IOException(pe); 2871 } 2872 Element conf = doc.createElement("configuration"); 2873 doc.appendChild(conf); 2874 conf.appendChild(doc.createTextNode("\n")); 2875 handleDeprecation(); //ensure properties is set and deprecation is handled 2876 for (Enumeration<Object> e = properties.keys(); e.hasMoreElements();) { 2877 String name = (String)e.nextElement(); 2878 Object object = properties.get(name); 2879 String value = null; 2880 if (object instanceof String) { 2881 value = (String) object; 2882 }else { 2883 continue; 2884 } 2885 Element propNode = doc.createElement("property"); 2886 conf.appendChild(propNode); 2887 2888 Element nameNode = doc.createElement("name"); 2889 nameNode.appendChild(doc.createTextNode(name)); 2890 propNode.appendChild(nameNode); 2891 2892 Element valueNode = doc.createElement("value"); 2893 valueNode.appendChild(doc.createTextNode(value)); 2894 propNode.appendChild(valueNode); 2895 2896 if (updatingResource != null) { 2897 String[] sources = updatingResource.get(name); 2898 if(sources != null) { 2899 for(String s : sources) { 2900 Element sourceNode = doc.createElement("source"); 2901 sourceNode.appendChild(doc.createTextNode(s)); 2902 propNode.appendChild(sourceNode); 2903 } 2904 } 2905 } 2906 2907 conf.appendChild(doc.createTextNode("\n")); 2908 } 2909 return doc; 2910 } 2911 2912 /** 2913 * Writes out all the parameters and their properties (final and resource) to 2914 * the given {@link Writer} 2915 * The format of the output would be 2916 * { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2, 2917 * key2.isFinal,key2.resource}... ] } 2918 * It does not output the parameters of the configuration object which is 2919 * loaded from an input stream. 2920 * @param out the Writer to write to 2921 * @throws IOException 2922 */ 2923 public static void dumpConfiguration(Configuration config, 2924 Writer out) throws IOException { 2925 JsonFactory dumpFactory = new JsonFactory(); 2926 JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out); 2927 dumpGenerator.writeStartObject(); 2928 dumpGenerator.writeFieldName("properties"); 2929 dumpGenerator.writeStartArray(); 2930 dumpGenerator.flush(); 2931 synchronized (config) { 2932 for (Map.Entry<Object,Object> item: config.getProps().entrySet()) { 2933 dumpGenerator.writeStartObject(); 2934 dumpGenerator.writeStringField("key", (String) item.getKey()); 2935 dumpGenerator.writeStringField("value", 2936 config.get((String) item.getKey())); 2937 dumpGenerator.writeBooleanField("isFinal", 2938 config.finalParameters.contains(item.getKey())); 2939 String[] resources = config.updatingResource.get(item.getKey()); 2940 String resource = UNKNOWN_RESOURCE; 2941 if(resources != null && resources.length > 0) { 2942 resource = resources[0]; 2943 } 2944 dumpGenerator.writeStringField("resource", resource); 2945 dumpGenerator.writeEndObject(); 2946 } 2947 } 2948 dumpGenerator.writeEndArray(); 2949 dumpGenerator.writeEndObject(); 2950 dumpGenerator.flush(); 2951 } 2952 2953 /** 2954 * Get the {@link ClassLoader} for this job. 2955 * 2956 * @return the correct class loader. 2957 */ 2958 public ClassLoader getClassLoader() { 2959 return classLoader; 2960 } 2961 2962 /** 2963 * Set the class loader that will be used to load the various objects. 2964 * 2965 * @param classLoader the new class loader. 2966 */ 2967 public void setClassLoader(ClassLoader classLoader) { 2968 this.classLoader = classLoader; 2969 } 2970 2971 @Override 2972 public String toString() { 2973 StringBuilder sb = new StringBuilder(); 2974 sb.append("Configuration: "); 2975 if(loadDefaults) { 2976 toString(defaultResources, sb); 2977 if(resources.size()>0) { 2978 sb.append(", "); 2979 } 2980 } 2981 toString(resources, sb); 2982 return sb.toString(); 2983 } 2984 2985 private <T> void toString(List<T> resources, StringBuilder sb) { 2986 ListIterator<T> i = resources.listIterator(); 2987 while (i.hasNext()) { 2988 if (i.nextIndex() != 0) { 2989 sb.append(", "); 2990 } 2991 sb.append(i.next()); 2992 } 2993 } 2994 2995 /** 2996 * Set the quietness-mode. 2997 * 2998 * In the quiet-mode, error and informational messages might not be logged. 2999 * 3000 * @param quietmode <code>true</code> to set quiet-mode on, <code>false</code> 3001 * to turn it off. 3002 */ 3003 public synchronized void setQuietMode(boolean quietmode) { 3004 this.quietmode = quietmode; 3005 } 3006 3007 synchronized boolean getQuietMode() { 3008 return this.quietmode; 3009 } 3010 3011 /** For debugging. List non-default properties to the terminal and exit. */ 3012 public static void main(String[] args) throws Exception { 3013 new Configuration().writeXml(System.out); 3014 } 3015 3016 @Override 3017 public void readFields(DataInput in) throws IOException { 3018 clear(); 3019 int size = WritableUtils.readVInt(in); 3020 for(int i=0; i < size; ++i) { 3021 String key = org.apache.hadoop.io.Text.readString(in); 3022 String value = org.apache.hadoop.io.Text.readString(in); 3023 set(key, value); 3024 String sources[] = WritableUtils.readCompressedStringArray(in); 3025 if(sources != null) { 3026 updatingResource.put(key, sources); 3027 } 3028 } 3029 } 3030 3031 //@Override 3032 @Override 3033 public void write(DataOutput out) throws IOException { 3034 Properties props = getProps(); 3035 WritableUtils.writeVInt(out, props.size()); 3036 for(Map.Entry<Object, Object> item: props.entrySet()) { 3037 org.apache.hadoop.io.Text.writeString(out, (String) item.getKey()); 3038 org.apache.hadoop.io.Text.writeString(out, (String) item.getValue()); 3039 WritableUtils.writeCompressedStringArray(out, 3040 updatingResource.get(item.getKey())); 3041 } 3042 } 3043 3044 /** 3045 * get keys matching the the regex 3046 * @param regex 3047 * @return Map<String,String> with matching keys 3048 */ 3049 public Map<String,String> getValByRegex(String regex) { 3050 Pattern p = Pattern.compile(regex); 3051 3052 Map<String,String> result = new HashMap<String,String>(); 3053 Matcher m; 3054 3055 for(Map.Entry<Object,Object> item: getProps().entrySet()) { 3056 if (item.getKey() instanceof String && 3057 item.getValue() instanceof String) { 3058 m = p.matcher((String)item.getKey()); 3059 if(m.find()) { // match 3060 result.put((String) item.getKey(), 3061 substituteVars(getProps().getProperty((String) item.getKey()))); 3062 } 3063 } 3064 } 3065 return result; 3066 } 3067 3068 /** 3069 * A unique class which is used as a sentinel value in the caching 3070 * for getClassByName. {@link Configuration#getClassByNameOrNull(String)} 3071 */ 3072 private static abstract class NegativeCacheSentinel {} 3073 3074 public static void dumpDeprecatedKeys() { 3075 DeprecationContext deprecations = deprecationContext.get(); 3076 for (Map.Entry<String, DeprecatedKeyInfo> entry : 3077 deprecations.getDeprecatedKeyMap().entrySet()) { 3078 StringBuilder newKeys = new StringBuilder(); 3079 for (String newKey : entry.getValue().newKeys) { 3080 newKeys.append(newKey).append("\t"); 3081 } 3082 System.out.println(entry.getKey() + "\t" + newKeys.toString()); 3083 } 3084 } 3085 3086 /** 3087 * Returns whether or not a deprecated name has been warned. If the name is not 3088 * deprecated then always return false 3089 */ 3090 public static boolean hasWarnedDeprecation(String name) { 3091 DeprecationContext deprecations = deprecationContext.get(); 3092 if(deprecations.getDeprecatedKeyMap().containsKey(name)) { 3093 if(deprecations.getDeprecatedKeyMap().get(name).accessed.get()) { 3094 return true; 3095 } 3096 } 3097 return false; 3098 } 3099}