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    
019    package org.apache.hadoop.hdfs;
020    
021    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX;
022    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_NAMENODE_ID_KEY;
023    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_BACKUP_ADDRESS_KEY;
024    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTPS_ADDRESS_DEFAULT;
025    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTPS_ADDRESS_KEY;
026    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_DEFAULT;
027    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY;
028    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY;
029    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY;
030    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY;
031    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMESERVICES;
032    import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMESERVICE_ID;
033    
034    import java.io.IOException;
035    import java.io.PrintStream;
036    import java.io.UnsupportedEncodingException;
037    import java.net.InetSocketAddress;
038    import java.net.URI;
039    import java.net.URISyntaxException;
040    import java.security.SecureRandom;
041    import java.util.Collection;
042    import java.util.Collections;
043    import java.util.Comparator;
044    import java.util.HashMap;
045    import java.util.HashSet;
046    import java.util.List;
047    import java.util.Map;
048    import java.util.Random;
049    import java.util.Set;
050    import java.util.concurrent.TimeUnit;
051    
052    import javax.net.SocketFactory;
053    
054    import org.apache.commons.cli.CommandLine;
055    import org.apache.commons.cli.CommandLineParser;
056    import org.apache.commons.cli.Option;
057    import org.apache.commons.cli.Options;
058    import org.apache.commons.cli.ParseException;
059    import org.apache.commons.cli.PosixParser;
060    import org.apache.commons.logging.Log;
061    import org.apache.commons.logging.LogFactory;
062    import org.apache.hadoop.HadoopIllegalArgumentException;
063    import org.apache.hadoop.classification.InterfaceAudience;
064    import org.apache.hadoop.conf.Configuration;
065    import org.apache.hadoop.fs.BlockLocation;
066    import org.apache.hadoop.fs.FileSystem;
067    import org.apache.hadoop.fs.Path;
068    import org.apache.hadoop.hdfs.protocol.AlreadyBeingCreatedException;
069    import org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol;
070    import org.apache.hadoop.hdfs.protocol.DatanodeID;
071    import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
072    import org.apache.hadoop.hdfs.protocol.HdfsConstants;
073    import org.apache.hadoop.hdfs.protocol.LocatedBlock;
074    import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
075    import org.apache.hadoop.hdfs.protocolPB.ClientDatanodeProtocolTranslatorPB;
076    import org.apache.hadoop.hdfs.server.namenode.NameNode;
077    import org.apache.hadoop.io.retry.RetryPolicies;
078    import org.apache.hadoop.io.retry.RetryPolicy;
079    import org.apache.hadoop.io.retry.RetryProxy;
080    import org.apache.hadoop.ipc.ProtobufRpcEngine;
081    import org.apache.hadoop.ipc.RPC;
082    import org.apache.hadoop.net.NetUtils;
083    import org.apache.hadoop.net.NodeBase;
084    import org.apache.hadoop.security.SecurityUtil;
085    import org.apache.hadoop.security.UserGroupInformation;
086    import org.apache.hadoop.util.StringUtils;
087    import org.apache.hadoop.util.ToolRunner;
088    
089    import com.google.common.base.Charsets;
090    import com.google.common.base.Joiner;
091    import com.google.common.base.Preconditions;
092    import com.google.common.collect.Lists;
093    import com.google.common.collect.Maps;
094    import com.google.protobuf.BlockingService;
095    
096    @InterfaceAudience.Private
097    public class DFSUtil {
098      public static final Log LOG = LogFactory.getLog(DFSUtil.class.getName());
099      
100      private DFSUtil() { /* Hidden constructor */ }
101      private static final ThreadLocal<Random> RANDOM = new ThreadLocal<Random>() {
102        @Override
103        protected Random initialValue() {
104          return new Random();
105        }
106      };
107      
108      private static final ThreadLocal<SecureRandom> SECURE_RANDOM = new ThreadLocal<SecureRandom>() {
109        @Override
110        protected SecureRandom initialValue() {
111          return new SecureRandom();
112        }
113      };
114    
115      /** @return a pseudo random number generator. */
116      public static Random getRandom() {
117        return RANDOM.get();
118      }
119      
120      /** @return a pseudo secure random number generator. */
121      public static SecureRandom getSecureRandom() {
122        return SECURE_RANDOM.get();
123      }
124    
125      /**
126       * Compartor for sorting DataNodeInfo[] based on decommissioned states.
127       * Decommissioned nodes are moved to the end of the array on sorting with
128       * this compartor.
129       */
130      public static final Comparator<DatanodeInfo> DECOM_COMPARATOR = 
131        new Comparator<DatanodeInfo>() {
132          @Override
133          public int compare(DatanodeInfo a, DatanodeInfo b) {
134            return a.isDecommissioned() == b.isDecommissioned() ? 0 : 
135              a.isDecommissioned() ? 1 : -1;
136          }
137        };
138        
139          
140      /**
141       * Comparator for sorting DataNodeInfo[] based on decommissioned/stale states.
142       * Decommissioned/stale nodes are moved to the end of the array on sorting
143       * with this comparator.
144       */ 
145      @InterfaceAudience.Private 
146      public static class DecomStaleComparator implements Comparator<DatanodeInfo> {
147        private long staleInterval;
148    
149        /**
150         * Constructor of DecomStaleComparator
151         * 
152         * @param interval
153         *          The time interval for marking datanodes as stale is passed from
154         *          outside, since the interval may be changed dynamically
155         */
156        public DecomStaleComparator(long interval) {
157          this.staleInterval = interval;
158        }
159    
160        @Override
161        public int compare(DatanodeInfo a, DatanodeInfo b) {
162          // Decommissioned nodes will still be moved to the end of the list
163          if (a.isDecommissioned()) {
164            return b.isDecommissioned() ? 0 : 1;
165          } else if (b.isDecommissioned()) {
166            return -1;
167          }
168          // Stale nodes will be moved behind the normal nodes
169          boolean aStale = a.isStale(staleInterval);
170          boolean bStale = b.isStale(staleInterval);
171          return aStale == bStale ? 0 : (aStale ? 1 : -1);
172        }
173      }    
174        
175      /**
176       * Address matcher for matching an address to local address
177       */
178      static final AddressMatcher LOCAL_ADDRESS_MATCHER = new AddressMatcher() {
179        @Override
180        public boolean match(InetSocketAddress s) {
181          return NetUtils.isLocalAddress(s.getAddress());
182        };
183      };
184      
185      /**
186       * Whether the pathname is valid.  Currently prohibits relative paths, 
187       * names which contain a ":" or "//", or other non-canonical paths.
188       */
189      public static boolean isValidName(String src) {
190        // Path must be absolute.
191        if (!src.startsWith(Path.SEPARATOR)) {
192          return false;
193        }
194          
195        // Check for ".." "." ":" "/"
196        String[] components = StringUtils.split(src, '/');
197        for (int i = 0; i < components.length; i++) {
198          String element = components[i];
199          if (element.equals("..") || 
200              element.equals(".")  ||
201              (element.indexOf(":") >= 0)  ||
202              (element.indexOf("/") >= 0)) {
203            return false;
204          }
205          
206          // The string may start or end with a /, but not have
207          // "//" in the middle.
208          if (element.isEmpty() && i != components.length - 1 &&
209              i != 0) {
210            return false;
211          }
212        }
213        return true;
214      }
215    
216      /**
217       * Converts a byte array to a string using UTF8 encoding.
218       */
219      public static String bytes2String(byte[] bytes) {
220        try {
221          return new String(bytes, "UTF8");
222        } catch(UnsupportedEncodingException e) {
223          assert false : "UTF8 encoding is not supported ";
224        }
225        return null;
226      }
227    
228      /**
229       * Converts a string to a byte array using UTF8 encoding.
230       */
231      public static byte[] string2Bytes(String str) {
232        return str.getBytes(Charsets.UTF_8);
233      }
234    
235      /**
236       * Given a list of path components returns a path as a UTF8 String
237       */
238      public static String byteArray2String(byte[][] pathComponents) {
239        if (pathComponents.length == 0)
240          return "";
241        if (pathComponents.length == 1 && pathComponents[0].length == 0) {
242          return Path.SEPARATOR;
243        }
244        StringBuilder result = new StringBuilder();
245        for (int i = 0; i < pathComponents.length; i++) {
246          result.append(new String(pathComponents[i], Charsets.UTF_8));
247          if (i < pathComponents.length - 1) {
248            result.append(Path.SEPARATOR_CHAR);
249          }
250        }
251        return result.toString();
252      }
253    
254      /**
255       * Splits the array of bytes into array of arrays of bytes
256       * on byte separator
257       * @param bytes the array of bytes to split
258       * @param separator the delimiting byte
259       */
260      public static byte[][] bytes2byteArray(byte[] bytes, byte separator) {
261        return bytes2byteArray(bytes, bytes.length, separator);
262      }
263    
264      /**
265       * Splits first len bytes in bytes to array of arrays of bytes
266       * on byte separator
267       * @param bytes the byte array to split
268       * @param len the number of bytes to split
269       * @param separator the delimiting byte
270       */
271      public static byte[][] bytes2byteArray(byte[] bytes,
272                                             int len,
273                                             byte separator) {
274        assert len <= bytes.length;
275        int splits = 0;
276        if (len == 0) {
277          return new byte[][]{null};
278        }
279        // Count the splits. Omit multiple separators and the last one
280        for (int i = 0; i < len; i++) {
281          if (bytes[i] == separator) {
282            splits++;
283          }
284        }
285        int last = len - 1;
286        while (last > -1 && bytes[last--] == separator) {
287          splits--;
288        }
289        if (splits == 0 && bytes[0] == separator) {
290          return new byte[][]{null};
291        }
292        splits++;
293        byte[][] result = new byte[splits][];
294        int startIndex = 0;
295        int nextIndex = 0;
296        int index = 0;
297        // Build the splits
298        while (index < splits) {
299          while (nextIndex < len && bytes[nextIndex] != separator) {
300            nextIndex++;
301          }
302          result[index] = new byte[nextIndex - startIndex];
303          System.arraycopy(bytes, startIndex, result[index], 0, nextIndex
304                  - startIndex);
305          index++;
306          startIndex = nextIndex + 1;
307          nextIndex = startIndex;
308        }
309        return result;
310      }
311      
312      /**
313       * Convert a LocatedBlocks to BlockLocations[]
314       * @param blocks a LocatedBlocks
315       * @return an array of BlockLocations
316       */
317      public static BlockLocation[] locatedBlocks2Locations(LocatedBlocks blocks) {
318        if (blocks == null) {
319          return new BlockLocation[0];
320        }
321        return locatedBlocks2Locations(blocks.getLocatedBlocks());
322      }
323      
324      /**
325       * Convert a List<LocatedBlock> to BlockLocation[]
326       * @param blocks A List<LocatedBlock> to be converted
327       * @return converted array of BlockLocation
328       */
329      public static BlockLocation[] locatedBlocks2Locations(List<LocatedBlock> blocks) {
330        if (blocks == null) {
331          return new BlockLocation[0];
332        }
333        int nrBlocks = blocks.size();
334        BlockLocation[] blkLocations = new BlockLocation[nrBlocks];
335        if (nrBlocks == 0) {
336          return blkLocations;
337        }
338        int idx = 0;
339        for (LocatedBlock blk : blocks) {
340          assert idx < nrBlocks : "Incorrect index";
341          DatanodeInfo[] locations = blk.getLocations();
342          String[] hosts = new String[locations.length];
343          String[] xferAddrs = new String[locations.length];
344          String[] racks = new String[locations.length];
345          for (int hCnt = 0; hCnt < locations.length; hCnt++) {
346            hosts[hCnt] = locations[hCnt].getHostName();
347            xferAddrs[hCnt] = locations[hCnt].getXferAddr();
348            NodeBase node = new NodeBase(xferAddrs[hCnt], 
349                                         locations[hCnt].getNetworkLocation());
350            racks[hCnt] = node.toString();
351          }
352          blkLocations[idx] = new BlockLocation(xferAddrs, hosts, racks,
353                                                blk.getStartOffset(),
354                                                blk.getBlockSize(),
355                                                blk.isCorrupt());
356          idx++;
357        }
358        return blkLocations;
359      }
360    
361      /**
362       * Returns collection of nameservice Ids from the configuration.
363       * @param conf configuration
364       * @return collection of nameservice Ids, or null if not specified
365       */
366      public static Collection<String> getNameServiceIds(Configuration conf) {
367        return conf.getTrimmedStringCollection(DFS_NAMESERVICES);
368      }
369    
370      /**
371       * @return <code>coll</code> if it is non-null and non-empty. Otherwise,
372       * returns a list with a single null value.
373       */
374      private static Collection<String> emptyAsSingletonNull(Collection<String> coll) {
375        if (coll == null || coll.isEmpty()) {
376          return Collections.singletonList(null);
377        } else {
378          return coll;
379        }
380      }
381      
382      /**
383       * Namenode HighAvailability related configuration.
384       * Returns collection of namenode Ids from the configuration. One logical id
385       * for each namenode in the in the HA setup.
386       * 
387       * @param conf configuration
388       * @param nsId the nameservice ID to look at, or null for non-federated 
389       * @return collection of namenode Ids
390       */
391      public static Collection<String> getNameNodeIds(Configuration conf, String nsId) {
392        String key = addSuffix(DFS_HA_NAMENODES_KEY_PREFIX, nsId);
393        return conf.getTrimmedStringCollection(key);
394      }
395      
396      /**
397       * Given a list of keys in the order of preference, returns a value
398       * for the key in the given order from the configuration.
399       * @param defaultValue default value to return, when key was not found
400       * @param keySuffix suffix to add to the key, if it is not null
401       * @param conf Configuration
402       * @param keys list of keys in the order of preference
403       * @return value of the key or default if a key was not found in configuration
404       */
405      private static String getConfValue(String defaultValue, String keySuffix,
406          Configuration conf, String... keys) {
407        String value = null;
408        for (String key : keys) {
409          key = addSuffix(key, keySuffix);
410          value = conf.get(key);
411          if (value != null) {
412            break;
413          }
414        }
415        if (value == null) {
416          value = defaultValue;
417        }
418        return value;
419      }
420      
421      /** Add non empty and non null suffix to a key */
422      private static String addSuffix(String key, String suffix) {
423        if (suffix == null || suffix.isEmpty()) {
424          return key;
425        }
426        assert !suffix.startsWith(".") :
427          "suffix '" + suffix + "' should not already have '.' prepended.";
428        return key + "." + suffix;
429      }
430      
431      /** Concatenate list of suffix strings '.' separated */
432      private static String concatSuffixes(String... suffixes) {
433        if (suffixes == null) {
434          return null;
435        }
436        return Joiner.on(".").skipNulls().join(suffixes);
437      }
438      
439      /**
440       * Return configuration key of format key.suffix1.suffix2...suffixN
441       */
442      public static String addKeySuffixes(String key, String... suffixes) {
443        String keySuffix = concatSuffixes(suffixes);
444        return addSuffix(key, keySuffix);
445      }
446      
447      /**
448       * Returns the configured address for all NameNodes in the cluster.
449       * @param conf configuration
450       * @param defaultAddress default address to return in case key is not found.
451       * @param keys Set of keys to look for in the order of preference
452       * @return a map(nameserviceId to map(namenodeId to InetSocketAddress))
453       */
454      private static Map<String, Map<String, InetSocketAddress>>
455        getAddresses(Configuration conf,
456          String defaultAddress, String... keys) {
457        Collection<String> nameserviceIds = getNameServiceIds(conf);
458        
459        // Look for configurations of the form <key>[.<nameserviceId>][.<namenodeId>]
460        // across all of the configured nameservices and namenodes.
461        Map<String, Map<String, InetSocketAddress>> ret = Maps.newHashMap();
462        for (String nsId : emptyAsSingletonNull(nameserviceIds)) {
463          Map<String, InetSocketAddress> isas =
464            getAddressesForNameserviceId(conf, nsId, defaultAddress, keys);
465          if (!isas.isEmpty()) {
466            ret.put(nsId, isas);
467          }
468        }
469        return ret;
470      }
471    
472      private static Map<String, InetSocketAddress> getAddressesForNameserviceId(
473          Configuration conf, String nsId, String defaultValue,
474          String[] keys) {
475        Collection<String> nnIds = getNameNodeIds(conf, nsId);
476        Map<String, InetSocketAddress> ret = Maps.newHashMap();
477        for (String nnId : emptyAsSingletonNull(nnIds)) {
478          String suffix = concatSuffixes(nsId, nnId);
479          String address = getConfValue(defaultValue, suffix, conf, keys);
480          if (address != null) {
481            InetSocketAddress isa = NetUtils.createSocketAddr(address);
482            ret.put(nnId, isa);
483          }
484        }
485        return ret;
486      }
487    
488      /**
489       * @return a collection of all configured NN Kerberos principals.
490       */
491      public static Set<String> getAllNnPrincipals(Configuration conf) throws IOException {
492        Set<String> principals = new HashSet<String>();
493        for (String nsId : DFSUtil.getNameServiceIds(conf)) {
494          if (HAUtil.isHAEnabled(conf, nsId)) {
495            for (String nnId : DFSUtil.getNameNodeIds(conf, nsId)) {
496              Configuration confForNn = new Configuration(conf);
497              NameNode.initializeGenericKeys(confForNn, nsId, nnId);
498              String principal = SecurityUtil.getServerPrincipal(confForNn
499                  .get(DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY),
500                  NameNode.getAddress(confForNn).getHostName());
501              principals.add(principal);
502            }
503          } else {
504            Configuration confForNn = new Configuration(conf);
505            NameNode.initializeGenericKeys(confForNn, nsId, null);
506            String principal = SecurityUtil.getServerPrincipal(confForNn
507                .get(DFSConfigKeys.DFS_NAMENODE_USER_NAME_KEY),
508                NameNode.getAddress(confForNn).getHostName());
509            principals.add(principal);
510          }
511        }
512    
513        return principals;
514      }
515    
516      /**
517       * Returns list of InetSocketAddress corresponding to HA NN RPC addresses from
518       * the configuration.
519       * 
520       * @param conf configuration
521       * @return list of InetSocketAddresses
522       */
523      public static Map<String, Map<String, InetSocketAddress>> getHaNnRpcAddresses(
524          Configuration conf) {
525        return getAddresses(conf, null, DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY);
526      }
527      
528      /**
529       * Returns list of InetSocketAddress corresponding to  backup node rpc 
530       * addresses from the configuration.
531       * 
532       * @param conf configuration
533       * @return list of InetSocketAddresses
534       * @throws IOException on error
535       */
536      public static Map<String, Map<String, InetSocketAddress>> getBackupNodeAddresses(
537          Configuration conf) throws IOException {
538        Map<String, Map<String, InetSocketAddress>> addressList = getAddresses(conf,
539            null, DFS_NAMENODE_BACKUP_ADDRESS_KEY);
540        if (addressList.isEmpty()) {
541          throw new IOException("Incorrect configuration: backup node address "
542              + DFS_NAMENODE_BACKUP_ADDRESS_KEY + " is not configured.");
543        }
544        return addressList;
545      }
546    
547      /**
548       * Returns list of InetSocketAddresses of corresponding to secondary namenode
549       * http addresses from the configuration.
550       * 
551       * @param conf configuration
552       * @return list of InetSocketAddresses
553       * @throws IOException on error
554       */
555      public static Map<String, Map<String, InetSocketAddress>> getSecondaryNameNodeAddresses(
556          Configuration conf) throws IOException {
557        Map<String, Map<String, InetSocketAddress>> addressList = getAddresses(conf, null,
558            DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY);
559        if (addressList.isEmpty()) {
560          throw new IOException("Incorrect configuration: secondary namenode address "
561              + DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY + " is not configured.");
562        }
563        return addressList;
564      }
565    
566      /**
567       * Returns list of InetSocketAddresses corresponding to namenodes from the
568       * configuration. Note this is to be used by datanodes to get the list of
569       * namenode addresses to talk to.
570       * 
571       * Returns namenode address specifically configured for datanodes (using
572       * service ports), if found. If not, regular RPC address configured for other
573       * clients is returned.
574       * 
575       * @param conf configuration
576       * @return list of InetSocketAddress
577       * @throws IOException on error
578       */
579      public static Map<String, Map<String, InetSocketAddress>> getNNServiceRpcAddresses(
580          Configuration conf) throws IOException {
581        // Use default address as fall back
582        String defaultAddress;
583        try {
584          defaultAddress = NetUtils.getHostPortString(NameNode.getAddress(conf));
585        } catch (IllegalArgumentException e) {
586          defaultAddress = null;
587        }
588        
589        Map<String, Map<String, InetSocketAddress>> addressList =
590          getAddresses(conf, defaultAddress,
591            DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY, DFS_NAMENODE_RPC_ADDRESS_KEY);
592        if (addressList.isEmpty()) {
593          throw new IOException("Incorrect configuration: namenode address "
594              + DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY + " or "  
595              + DFS_NAMENODE_RPC_ADDRESS_KEY
596              + " is not configured.");
597        }
598        return addressList;
599      }
600      
601      /**
602       * Flatten the given map, as returned by other functions in this class,
603       * into a flat list of {@link ConfiguredNNAddress} instances.
604       */
605      public static List<ConfiguredNNAddress> flattenAddressMap(
606          Map<String, Map<String, InetSocketAddress>> map) {
607        List<ConfiguredNNAddress> ret = Lists.newArrayList();
608        
609        for (Map.Entry<String, Map<String, InetSocketAddress>> entry :
610          map.entrySet()) {
611          String nsId = entry.getKey();
612          Map<String, InetSocketAddress> nnMap = entry.getValue();
613          for (Map.Entry<String, InetSocketAddress> e2 : nnMap.entrySet()) {
614            String nnId = e2.getKey();
615            InetSocketAddress addr = e2.getValue();
616            
617            ret.add(new ConfiguredNNAddress(nsId, nnId, addr));
618          }
619        }
620        return ret;
621      }
622    
623      /**
624       * Format the given map, as returned by other functions in this class,
625       * into a string suitable for debugging display. The format of this string
626       * should not be considered an interface, and is liable to change.
627       */
628      public static String addressMapToString(
629          Map<String, Map<String, InetSocketAddress>> map) {
630        StringBuilder b = new StringBuilder();
631        for (Map.Entry<String, Map<String, InetSocketAddress>> entry :
632             map.entrySet()) {
633          String nsId = entry.getKey();
634          Map<String, InetSocketAddress> nnMap = entry.getValue();
635          b.append("Nameservice <").append(nsId).append(">:").append("\n");
636          for (Map.Entry<String, InetSocketAddress> e2 : nnMap.entrySet()) {
637            b.append("  NN ID ").append(e2.getKey())
638              .append(" => ").append(e2.getValue()).append("\n");
639          }
640        }
641        return b.toString();
642      }
643      
644      public static String nnAddressesAsString(Configuration conf) {
645        Map<String, Map<String, InetSocketAddress>> addresses =
646          getHaNnRpcAddresses(conf);
647        return addressMapToString(addresses);
648      }
649    
650      /**
651       * Represent one of the NameNodes configured in the cluster.
652       */
653      public static class ConfiguredNNAddress {
654        private final String nameserviceId;
655        private final String namenodeId;
656        private final InetSocketAddress addr;
657    
658        private ConfiguredNNAddress(String nameserviceId, String namenodeId,
659            InetSocketAddress addr) {
660          this.nameserviceId = nameserviceId;
661          this.namenodeId = namenodeId;
662          this.addr = addr;
663        }
664    
665        public String getNameserviceId() {
666          return nameserviceId;
667        }
668    
669        public String getNamenodeId() {
670          return namenodeId;
671        }
672    
673        public InetSocketAddress getAddress() {
674          return addr;
675        }
676        
677        @Override
678        public String toString() {
679          return "ConfiguredNNAddress[nsId=" + nameserviceId + ";" +
680            "nnId=" + namenodeId + ";addr=" + addr + "]";
681        }
682      }
683      
684      /**
685       * Get a URI for each configured nameservice. If a nameservice is
686       * HA-enabled, then the logical URI of the nameservice is returned. If the
687       * nameservice is not HA-enabled, then a URI corresponding to an RPC address
688       * of the single NN for that nameservice is returned, preferring the service
689       * RPC address over the client RPC address.
690       * 
691       * @param conf configuration
692       * @return a collection of all configured NN URIs, preferring service
693       *         addresses
694       */
695      public static Collection<URI> getNsServiceRpcUris(Configuration conf) {
696        return getNameServiceUris(conf,
697            DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY,
698            DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY);
699      }
700    
701      /**
702       * Get a URI for each configured nameservice. If a nameservice is
703       * HA-enabled, then the logical URI of the nameservice is returned. If the
704       * nameservice is not HA-enabled, then a URI corresponding to the address of
705       * the single NN for that nameservice is returned.
706       * 
707       * @param conf configuration
708       * @param keys configuration keys to try in order to get the URI for non-HA
709       *        nameservices
710       * @return a collection of all configured NN URIs
711       */
712      public static Collection<URI> getNameServiceUris(Configuration conf,
713          String... keys) {
714        Set<URI> ret = new HashSet<URI>();
715        
716        // We're passed multiple possible configuration keys for any given NN or HA
717        // nameservice, and search the config in order of these keys. In order to
718        // make sure that a later config lookup (e.g. fs.defaultFS) doesn't add a
719        // URI for a config key for which we've already found a preferred entry, we
720        // keep track of non-preferred keys here.
721        Set<URI> nonPreferredUris = new HashSet<URI>();
722        
723        for (String nsId : getNameServiceIds(conf)) {
724          if (HAUtil.isHAEnabled(conf, nsId)) {
725            // Add the logical URI of the nameservice.
726            try {
727              ret.add(new URI(HdfsConstants.HDFS_URI_SCHEME + "://" + nsId));
728            } catch (URISyntaxException ue) {
729              throw new IllegalArgumentException(ue);
730            }
731          } else {
732            // Add the URI corresponding to the address of the NN.
733            boolean uriFound = false;
734            for (String key : keys) {
735              String addr = conf.get(concatSuffixes(key, nsId));
736              if (addr != null) {
737                URI uri = createUri(HdfsConstants.HDFS_URI_SCHEME,
738                    NetUtils.createSocketAddr(addr));
739                if (!uriFound) {
740                  uriFound = true;
741                  ret.add(uri);
742                } else {
743                  nonPreferredUris.add(uri);
744                }
745              }
746            }
747          }
748        }
749        
750        // Add the generic configuration keys.
751        boolean uriFound = false;
752        for (String key : keys) {
753          String addr = conf.get(key);
754          if (addr != null) {
755            URI uri = createUri("hdfs", NetUtils.createSocketAddr(addr));
756            if (!uriFound) {
757              uriFound = true;
758              ret.add(uri);
759            } else {
760              nonPreferredUris.add(uri);
761            }
762          }
763        }
764        
765        // Add the default URI if it is an HDFS URI.
766        URI defaultUri = FileSystem.getDefaultUri(conf);
767        // checks if defaultUri is ip:port format
768        // and convert it to hostname:port format
769        if (defaultUri != null && (defaultUri.getPort() != -1)) {
770          defaultUri = createUri(defaultUri.getScheme(),
771              NetUtils.createSocketAddr(defaultUri.getHost(), 
772                  defaultUri.getPort()));
773        }
774        if (defaultUri != null &&
775            HdfsConstants.HDFS_URI_SCHEME.equals(defaultUri.getScheme()) &&
776            !nonPreferredUris.contains(defaultUri)) {
777          ret.add(defaultUri);
778        }
779        
780        return ret;
781      }
782    
783      /**
784       * Given the InetSocketAddress this method returns the nameservice Id
785       * corresponding to the key with matching address, by doing a reverse 
786       * lookup on the list of nameservices until it finds a match.
787       * 
788       * Since the process of resolving URIs to Addresses is slightly expensive,
789       * this utility method should not be used in performance-critical routines.
790       * 
791       * @param conf - configuration
792       * @param address - InetSocketAddress for configured communication with NN.
793       *     Configured addresses are typically given as URIs, but we may have to
794       *     compare against a URI typed in by a human, or the server name may be
795       *     aliased, so we compare unambiguous InetSocketAddresses instead of just
796       *     comparing URI substrings.
797       * @param keys - list of configured communication parameters that should
798       *     be checked for matches.  For example, to compare against RPC addresses,
799       *     provide the list DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY,
800       *     DFS_NAMENODE_RPC_ADDRESS_KEY.  Use the generic parameter keys,
801       *     not the NameServiceId-suffixed keys.
802       * @return nameserviceId, or null if no match found
803       */
804      public static String getNameServiceIdFromAddress(final Configuration conf, 
805          final InetSocketAddress address, String... keys) {
806        // Configuration with a single namenode and no nameserviceId
807        String[] ids = getSuffixIDs(conf, address, keys);
808        return (ids != null) ? ids[0] : null;
809      }
810      
811      /**
812       * return server http or https address from the configuration for a
813       * given namenode rpc address.
814       * @param conf
815       * @param namenodeAddr - namenode RPC address
816       * @param httpsAddress -If true, and if security is enabled, returns server 
817       *                      https address. If false, returns server http address.
818       * @return server http or https address
819       * @throws IOException 
820       */
821      public static String getInfoServer(InetSocketAddress namenodeAddr,
822          Configuration conf, boolean httpsAddress) throws IOException {
823        boolean securityOn = UserGroupInformation.isSecurityEnabled();
824        String httpAddressKey = (securityOn && httpsAddress) ? 
825            DFS_NAMENODE_HTTPS_ADDRESS_KEY : DFS_NAMENODE_HTTP_ADDRESS_KEY;
826        String httpAddressDefault = (securityOn && httpsAddress) ? 
827            DFS_NAMENODE_HTTPS_ADDRESS_DEFAULT : DFS_NAMENODE_HTTP_ADDRESS_DEFAULT;
828          
829        String suffixes[];
830        if (namenodeAddr != null) {
831          // if non-default namenode, try reverse look up 
832          // the nameServiceID if it is available
833          suffixes = getSuffixIDs(conf, namenodeAddr,
834              DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY,
835              DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY);
836        } else {
837          suffixes = new String[2];
838        }
839        String configuredInfoAddr = getSuffixedConf(conf, httpAddressKey,
840            httpAddressDefault, suffixes);
841        if (namenodeAddr != null) {
842          return substituteForWildcardAddress(configuredInfoAddr,
843              namenodeAddr.getHostName());
844        } else {
845          return configuredInfoAddr;
846        }
847      }
848      
849    
850      /**
851       * Substitute a default host in the case that an address has been configured
852       * with a wildcard. This is used, for example, when determining the HTTP
853       * address of the NN -- if it's configured to bind to 0.0.0.0, we want to
854       * substitute the hostname from the filesystem URI rather than trying to
855       * connect to 0.0.0.0.
856       * @param configuredAddress the address found in the configuration
857       * @param defaultHost the host to substitute with, if configuredAddress
858       * is a local/wildcard address.
859       * @return the substituted address
860       * @throws IOException if it is a wildcard address and security is enabled
861       */
862      public static String substituteForWildcardAddress(String configuredAddress,
863          String defaultHost) throws IOException {
864        InetSocketAddress sockAddr = NetUtils.createSocketAddr(configuredAddress);
865        InetSocketAddress defaultSockAddr = NetUtils.createSocketAddr(defaultHost
866            + ":0");
867        if (sockAddr.getAddress().isAnyLocalAddress()) {
868          if (UserGroupInformation.isSecurityEnabled() &&
869              defaultSockAddr.getAddress().isAnyLocalAddress()) {
870            throw new IOException("Cannot use a wildcard address with security. " +
871                "Must explicitly set bind address for Kerberos");
872          }
873          return defaultHost + ":" + sockAddr.getPort();
874        } else {
875          return configuredAddress;
876        }
877      }
878      
879      private static String getSuffixedConf(Configuration conf,
880          String key, String defaultVal, String[] suffixes) {
881        String ret = conf.get(DFSUtil.addKeySuffixes(key, suffixes));
882        if (ret != null) {
883          return ret;
884        }
885        return conf.get(key, defaultVal);
886      }
887      
888      /**
889       * Sets the node specific setting into generic configuration key. Looks up
890       * value of "key.nameserviceId.namenodeId" and if found sets that value into 
891       * generic key in the conf. If this is not found, falls back to
892       * "key.nameserviceId" and then the unmodified key.
893       *
894       * Note that this only modifies the runtime conf.
895       * 
896       * @param conf
897       *          Configuration object to lookup specific key and to set the value
898       *          to the key passed. Note the conf object is modified.
899       * @param nameserviceId
900       *          nameservice Id to construct the node specific key. Pass null if
901       *          federation is not configuration.
902       * @param nnId
903       *          namenode Id to construct the node specific key. Pass null if
904       *          HA is not configured.
905       * @param keys
906       *          The key for which node specific value is looked up
907       */
908      public static void setGenericConf(Configuration conf,
909          String nameserviceId, String nnId, String... keys) {
910        for (String key : keys) {
911          String value = conf.get(addKeySuffixes(key, nameserviceId, nnId));
912          if (value != null) {
913            conf.set(key, value);
914            continue;
915          }
916          value = conf.get(addKeySuffixes(key, nameserviceId));
917          if (value != null) {
918            conf.set(key, value);
919          }
920        }
921      }
922      
923      /** Return used as percentage of capacity */
924      public static float getPercentUsed(long used, long capacity) {
925        return capacity <= 0 ? 100 : (used * 100.0f)/capacity; 
926      }
927      
928      /** Return remaining as percentage of capacity */
929      public static float getPercentRemaining(long remaining, long capacity) {
930        return capacity <= 0 ? 0 : (remaining * 100.0f)/capacity; 
931      }
932    
933      /** Convert percentage to a string. */
934      public static String percent2String(double percentage) {
935        return StringUtils.format("%.2f%%", percentage);
936      }
937    
938      /**
939       * Round bytes to GiB (gibibyte)
940       * @param bytes number of bytes
941       * @return number of GiB
942       */
943      public static int roundBytesToGB(long bytes) {
944        return Math.round((float)bytes/ 1024 / 1024 / 1024);
945      }
946      
947      /** Create a {@link ClientDatanodeProtocol} proxy */
948      public static ClientDatanodeProtocol createClientDatanodeProtocolProxy(
949          DatanodeID datanodeid, Configuration conf, int socketTimeout,
950          boolean connectToDnViaHostname, LocatedBlock locatedBlock) throws IOException {
951        return new ClientDatanodeProtocolTranslatorPB(datanodeid, conf, socketTimeout,
952            connectToDnViaHostname, locatedBlock);
953      }
954      
955      /** Create {@link ClientDatanodeProtocol} proxy using kerberos ticket */
956      static ClientDatanodeProtocol createClientDatanodeProtocolProxy(
957          DatanodeID datanodeid, Configuration conf, int socketTimeout,
958          boolean connectToDnViaHostname) throws IOException {
959        return new ClientDatanodeProtocolTranslatorPB(
960            datanodeid, conf, socketTimeout, connectToDnViaHostname);
961      }
962      
963      /** Create a {@link ClientDatanodeProtocol} proxy */
964      public static ClientDatanodeProtocol createClientDatanodeProtocolProxy(
965          InetSocketAddress addr, UserGroupInformation ticket, Configuration conf,
966          SocketFactory factory) throws IOException {
967        return new ClientDatanodeProtocolTranslatorPB(addr, ticket, conf, factory);
968      }
969    
970      /**
971       * Get nameservice Id for the {@link NameNode} based on namenode RPC address
972       * matching the local node address.
973       */
974      public static String getNamenodeNameServiceId(Configuration conf) {
975        return getNameServiceId(conf, DFS_NAMENODE_RPC_ADDRESS_KEY);
976      }
977      
978      /**
979       * Get nameservice Id for the BackupNode based on backup node RPC address
980       * matching the local node address.
981       */
982      public static String getBackupNameServiceId(Configuration conf) {
983        return getNameServiceId(conf, DFS_NAMENODE_BACKUP_ADDRESS_KEY);
984      }
985      
986      /**
987       * Get nameservice Id for the secondary node based on secondary http address
988       * matching the local node address.
989       */
990      public static String getSecondaryNameServiceId(Configuration conf) {
991        return getNameServiceId(conf, DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY);
992      }
993      
994      /**
995       * Get the nameservice Id by matching the {@code addressKey} with the
996       * the address of the local node. 
997       * 
998       * If {@link DFSConfigKeys#DFS_NAMESERVICE_ID} is not specifically
999       * configured, and more than one nameservice Id is configured, this method 
1000       * determines the nameservice Id by matching the local node's address with the
1001       * configured addresses. When a match is found, it returns the nameservice Id
1002       * from the corresponding configuration key.
1003       * 
1004       * @param conf Configuration
1005       * @param addressKey configuration key to get the address.
1006       * @return nameservice Id on success, null if federation is not configured.
1007       * @throws HadoopIllegalArgumentException on error
1008       */
1009      private static String getNameServiceId(Configuration conf, String addressKey) {
1010        String nameserviceId = conf.get(DFS_NAMESERVICE_ID);
1011        if (nameserviceId != null) {
1012          return nameserviceId;
1013        }
1014        Collection<String> nsIds = getNameServiceIds(conf);
1015        if (1 == nsIds.size()) {
1016          return nsIds.toArray(new String[1])[0];
1017        }
1018        String nnId = conf.get(DFS_HA_NAMENODE_ID_KEY);
1019        
1020        return getSuffixIDs(conf, addressKey, null, nnId, LOCAL_ADDRESS_MATCHER)[0];
1021      }
1022      
1023      /**
1024       * Returns nameservice Id and namenode Id when the local host matches the
1025       * configuration parameter {@code addressKey}.<nameservice Id>.<namenode Id>
1026       * 
1027       * @param conf Configuration
1028       * @param addressKey configuration key corresponding to the address.
1029       * @param knownNsId only look at configs for the given nameservice, if not-null
1030       * @param knownNNId only look at configs for the given namenode, if not null
1031       * @param matcher matching criteria for matching the address
1032       * @return Array with nameservice Id and namenode Id on success. First element
1033       *         in the array is nameservice Id and second element is namenode Id.
1034       *         Null value indicates that the configuration does not have the the
1035       *         Id.
1036       * @throws HadoopIllegalArgumentException on error
1037       */
1038      static String[] getSuffixIDs(final Configuration conf, final String addressKey,
1039          String knownNsId, String knownNNId,
1040          final AddressMatcher matcher) {
1041        String nameserviceId = null;
1042        String namenodeId = null;
1043        int found = 0;
1044        
1045        Collection<String> nsIds = getNameServiceIds(conf);
1046        for (String nsId : emptyAsSingletonNull(nsIds)) {
1047          if (knownNsId != null && !knownNsId.equals(nsId)) {
1048            continue;
1049          }
1050          
1051          Collection<String> nnIds = getNameNodeIds(conf, nsId);
1052          for (String nnId : emptyAsSingletonNull(nnIds)) {
1053            if (LOG.isTraceEnabled()) {
1054              LOG.trace(String.format("addressKey: %s nsId: %s nnId: %s",
1055                  addressKey, nsId, nnId));
1056            }
1057            if (knownNNId != null && !knownNNId.equals(nnId)) {
1058              continue;
1059            }
1060            String key = addKeySuffixes(addressKey, nsId, nnId);
1061            String addr = conf.get(key);
1062            if (addr == null) {
1063              continue;
1064            }
1065            InetSocketAddress s = null;
1066            try {
1067              s = NetUtils.createSocketAddr(addr);
1068            } catch (Exception e) {
1069              LOG.warn("Exception in creating socket address " + addr, e);
1070              continue;
1071            }
1072            if (!s.isUnresolved() && matcher.match(s)) {
1073              nameserviceId = nsId;
1074              namenodeId = nnId;
1075              found++;
1076            }
1077          }
1078        }
1079        if (found > 1) { // Only one address must match the local address
1080          String msg = "Configuration has multiple addresses that match "
1081              + "local node's address. Please configure the system with "
1082              + DFS_NAMESERVICE_ID + " and "
1083              + DFS_HA_NAMENODE_ID_KEY;
1084          throw new HadoopIllegalArgumentException(msg);
1085        }
1086        return new String[] { nameserviceId, namenodeId };
1087      }
1088      
1089      /**
1090       * For given set of {@code keys} adds nameservice Id and or namenode Id
1091       * and returns {nameserviceId, namenodeId} when address match is found.
1092       * @see #getSuffixIDs(Configuration, String, AddressMatcher)
1093       */
1094      static String[] getSuffixIDs(final Configuration conf,
1095          final InetSocketAddress address, final String... keys) {
1096        AddressMatcher matcher = new AddressMatcher() {
1097         @Override
1098          public boolean match(InetSocketAddress s) {
1099            return address.equals(s);
1100          } 
1101        };
1102        
1103        for (String key : keys) {
1104          String[] ids = getSuffixIDs(conf, key, null, null, matcher);
1105          if (ids != null && (ids [0] != null || ids[1] != null)) {
1106            return ids;
1107          }
1108        }
1109        return null;
1110      }
1111      
1112      private interface AddressMatcher {
1113        public boolean match(InetSocketAddress s);
1114      }
1115    
1116      /** Create a URI from the scheme and address */
1117      public static URI createUri(String scheme, InetSocketAddress address) {
1118        try {
1119          return new URI(scheme, null, address.getHostName(), address.getPort(),
1120              null, null, null);
1121        } catch (URISyntaxException ue) {
1122          throw new IllegalArgumentException(ue);
1123        }
1124      }
1125      
1126      /**
1127       * Add protobuf based protocol to the {@link org.apache.hadoop.ipc.RPC.Server}
1128       * @param conf configuration
1129       * @param protocol Protocol interface
1130       * @param service service that implements the protocol
1131       * @param server RPC server to which the protocol & implementation is added to
1132       * @throws IOException
1133       */
1134      public static void addPBProtocol(Configuration conf, Class<?> protocol,
1135          BlockingService service, RPC.Server server) throws IOException {
1136        RPC.setProtocolEngine(conf, protocol, ProtobufRpcEngine.class);
1137        server.addProtocol(RPC.RpcKind.RPC_PROTOCOL_BUFFER, protocol, service);
1138      }
1139    
1140      /**
1141       * Map a logical namenode ID to its service address. Use the given
1142       * nameservice if specified, or the configured one if none is given.
1143       *
1144       * @param conf Configuration
1145       * @param nsId which nameservice nnId is a part of, optional
1146       * @param nnId the namenode ID to get the service addr for
1147       * @return the service addr, null if it could not be determined
1148       */
1149      public static String getNamenodeServiceAddr(final Configuration conf,
1150          String nsId, String nnId) {
1151    
1152        if (nsId == null) {
1153          nsId = getOnlyNameServiceIdOrNull(conf);
1154        }
1155    
1156        String serviceAddrKey = concatSuffixes(
1157            DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY, nsId, nnId);
1158    
1159        String addrKey = concatSuffixes(
1160            DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY, nsId, nnId);
1161    
1162        String serviceRpcAddr = conf.get(serviceAddrKey);
1163        if (serviceRpcAddr == null) {
1164          serviceRpcAddr = conf.get(addrKey);
1165        }
1166        return serviceRpcAddr;
1167      }
1168    
1169      /**
1170       * If the configuration refers to only a single nameservice, return the
1171       * name of that nameservice. If it refers to 0 or more than 1, return null.
1172       */
1173      public static String getOnlyNameServiceIdOrNull(Configuration conf) {
1174        Collection<String> nsIds = getNameServiceIds(conf);
1175        if (1 == nsIds.size()) {
1176          return nsIds.toArray(new String[1])[0];
1177        } else {
1178          // No nameservice ID was given and more than one is configured
1179          return null;
1180        }
1181      }
1182      
1183      public static Options helpOptions = new Options();
1184      public static Option helpOpt = new Option("h", "help", false,
1185          "get help information");
1186    
1187      static {
1188        helpOptions.addOption(helpOpt);
1189      }
1190    
1191      /**
1192       * Parse the arguments for commands
1193       * 
1194       * @param args the argument to be parsed
1195       * @param helpDescription help information to be printed out
1196       * @param out Printer
1197       * @param printGenericCommandUsage whether to print the 
1198       *              generic command usage defined in ToolRunner
1199       * @return true when the argument matches help option, false if not
1200       */
1201      public static boolean parseHelpArgument(String[] args,
1202          String helpDescription, PrintStream out, boolean printGenericCommandUsage) {
1203        if (args.length == 1) {
1204          try {
1205            CommandLineParser parser = new PosixParser();
1206            CommandLine cmdLine = parser.parse(helpOptions, args);
1207            if (cmdLine.hasOption(helpOpt.getOpt())
1208                || cmdLine.hasOption(helpOpt.getLongOpt())) {
1209              // should print out the help information
1210              out.println(helpDescription + "\n");
1211              if (printGenericCommandUsage) {
1212                ToolRunner.printGenericCommandUsage(out);
1213              }
1214              return true;
1215            }
1216          } catch (ParseException pe) {
1217            return false;
1218          }
1219        }
1220        return false;
1221      }
1222      
1223      /**
1224       * Get DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION from configuration.
1225       * 
1226       * @param conf Configuration
1227       * @return Value of DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION
1228       */
1229      public static float getInvalidateWorkPctPerIteration(Configuration conf) {
1230        float blocksInvalidateWorkPct = conf.getFloat(
1231            DFSConfigKeys.DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION,
1232            DFSConfigKeys.DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION_DEFAULT);
1233        Preconditions.checkArgument(
1234            (blocksInvalidateWorkPct > 0 && blocksInvalidateWorkPct <= 1.0f),
1235            DFSConfigKeys.DFS_NAMENODE_INVALIDATE_WORK_PCT_PER_ITERATION +
1236            " = '" + blocksInvalidateWorkPct + "' is invalid. " +
1237            "It should be a positive, non-zero float value, not greater than 1.0f, " +
1238            "to indicate a percentage.");
1239        return blocksInvalidateWorkPct;
1240      }
1241    
1242      /**
1243       * Get DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION from
1244       * configuration.
1245       * 
1246       * @param conf Configuration
1247       * @return Value of DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION
1248       */
1249      public static int getReplWorkMultiplier(Configuration conf) {
1250        int blocksReplWorkMultiplier = conf.getInt(
1251                DFSConfigKeys.DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION,
1252                DFSConfigKeys.DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION_DEFAULT);
1253        Preconditions.checkArgument(
1254            (blocksReplWorkMultiplier > 0),
1255            DFSConfigKeys.DFS_NAMENODE_REPLICATION_WORK_MULTIPLIER_PER_ITERATION +
1256            " = '" + blocksReplWorkMultiplier + "' is invalid. " +
1257            "It should be a positive, non-zero integer value.");
1258        return blocksReplWorkMultiplier;
1259      }
1260      
1261      /**
1262       * Get SPNEGO keytab Key from configuration
1263       * 
1264       * @param conf
1265       *          Configuration
1266       * @param defaultKey
1267       * @return DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY if the key is not empty
1268       *         else return defaultKey
1269       */
1270      public static String getSpnegoKeytabKey(Configuration conf, String defaultKey) {
1271        String value = 
1272            conf.get(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY);
1273        return (value == null || value.isEmpty()) ?
1274            defaultKey : DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY;
1275      }
1276    }