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