View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.util;
20  
21  import com.google.common.annotations.VisibleForTesting;
22  import com.google.common.base.Throwables;
23  import com.google.common.collect.Iterators;
24  import com.google.common.collect.Lists;
25  import com.google.common.primitives.Ints;
26  
27  import edu.umd.cs.findbugs.annotations.CheckForNull;
28  
29  import java.io.ByteArrayInputStream;
30  import java.io.DataInputStream;
31  import java.io.EOFException;
32  import java.io.FileNotFoundException;
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.InterruptedIOException;
36  import java.lang.reflect.InvocationTargetException;
37  import java.lang.reflect.Method;
38  import java.net.InetSocketAddress;
39  import java.net.URI;
40  import java.net.URISyntaxException;
41  import java.util.ArrayList;
42  import java.util.Arrays;
43  import java.util.Collections;
44  import java.util.HashMap;
45  import java.util.Iterator;
46  import java.util.LinkedList;
47  import java.util.List;
48  import java.util.Locale;
49  import java.util.Map;
50  import java.util.Vector;
51  import java.util.concurrent.ArrayBlockingQueue;
52  import java.util.concurrent.ConcurrentHashMap;
53  import java.util.concurrent.ExecutionException;
54  import java.util.concurrent.ExecutorService;
55  import java.util.concurrent.Future;
56  import java.util.concurrent.FutureTask;
57  import java.util.concurrent.ThreadPoolExecutor;
58  import java.util.concurrent.TimeUnit;
59  import java.util.regex.Pattern;
60  
61  import org.apache.commons.logging.Log;
62  import org.apache.commons.logging.LogFactory;
63  import org.apache.hadoop.HadoopIllegalArgumentException;
64  import org.apache.hadoop.conf.Configuration;
65  import org.apache.hadoop.fs.BlockLocation;
66  import org.apache.hadoop.fs.FSDataInputStream;
67  import org.apache.hadoop.fs.FSDataOutputStream;
68  import org.apache.hadoop.fs.FileStatus;
69  import org.apache.hadoop.fs.FileSystem;
70  import org.apache.hadoop.fs.LocatedFileStatus;
71  import org.apache.hadoop.fs.Path;
72  import org.apache.hadoop.fs.PathFilter;
73  import org.apache.hadoop.fs.RemoteIterator;
74  import org.apache.hadoop.fs.permission.FsAction;
75  import org.apache.hadoop.fs.permission.FsPermission;
76  import org.apache.hadoop.hbase.ClusterId;
77  import org.apache.hadoop.hbase.HColumnDescriptor;
78  import org.apache.hadoop.hbase.HConstants;
79  import org.apache.hadoop.hbase.HDFSBlocksDistribution;
80  import org.apache.hadoop.hbase.HRegionInfo;
81  import org.apache.hadoop.hbase.RemoteExceptionHandler;
82  import org.apache.hadoop.hbase.TableName;
83  import org.apache.hadoop.hbase.classification.InterfaceAudience;
84  import org.apache.hadoop.hbase.exceptions.DeserializationException;
85  import org.apache.hadoop.hbase.fs.HFileSystem;
86  import org.apache.hadoop.hbase.io.HFileLink;
87  import org.apache.hadoop.hbase.master.HMaster;
88  import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
89  import org.apache.hadoop.hbase.security.AccessDeniedException;
90  import org.apache.hadoop.hbase.util.HBaseFsck.ErrorReporter;
91  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
92  import org.apache.hadoop.hbase.protobuf.generated.FSProtos;
93  import org.apache.hadoop.hdfs.DistributedFileSystem;
94  import org.apache.hadoop.io.IOUtils;
95  import org.apache.hadoop.io.SequenceFile;
96  import org.apache.hadoop.ipc.RemoteException;
97  import org.apache.hadoop.security.UserGroupInformation;
98  import org.apache.hadoop.util.Progressable;
99  import org.apache.hadoop.util.ReflectionUtils;
100 import org.apache.hadoop.util.StringUtils;
101 
102 
103 import static org.apache.hadoop.hbase.HConstants.HBASE_DIR;
104 
105 /**
106  * Utility methods for interacting with the underlying file system.
107  */
108 @InterfaceAudience.Private
109 public abstract class FSUtils {
110   private static final Log LOG = LogFactory.getLog(FSUtils.class);
111 
112   /** Full access permissions (starting point for a umask) */
113   public static final String FULL_RWX_PERMISSIONS = "777";
114   private static final String THREAD_POOLSIZE = "hbase.client.localityCheck.threadPoolSize";
115   private static final int DEFAULT_THREAD_POOLSIZE = 2;
116 
117   /** Set to true on Windows platforms */
118   public static final boolean WINDOWS = System.getProperty("os.name").startsWith("Windows");
119 
120   protected FSUtils() {
121     super();
122   }
123 
124   /**
125    * Sets storage policy for given path according to config setting.
126    * If the passed path is a directory, we'll set the storage policy for all files
127    * created in the future in said directory. Note that this change in storage
128    * policy takes place at the HDFS level; it will persist beyond this RS's lifecycle.
129    * If we're running on a version of HDFS that doesn't support the given storage policy
130    * (or storage policies at all), then we'll issue a log message and continue.
131    *
132    * See http://hadoop.apache.org/docs/r2.6.0/hadoop-project-dist/hadoop-hdfs/ArchivalStorage.html
133    *
134    * @param fs We only do anything if an instance of DistributedFileSystem
135    * @param conf used to look up storage policy with given key; not modified.
136    * @param path the Path whose storage policy is to be set
137    * @param policyKey e.g. HConstants.WAL_STORAGE_POLICY
138    * @param defaultPolicy usually should be the policy NONE to delegate to HDFS
139    */
140   public static void setStoragePolicy(final FileSystem fs, final Configuration conf,
141       final Path path, final String policyKey, final String defaultPolicy) {
142     String storagePolicy = conf.get(policyKey, defaultPolicy).toUpperCase(Locale.ROOT);
143     if (storagePolicy.equals(defaultPolicy)) {
144       if (LOG.isTraceEnabled()) {
145         LOG.trace("default policy of " + defaultPolicy + " requested, exiting early.");
146       }
147       return;
148     }
149     if (fs instanceof DistributedFileSystem) {
150       DistributedFileSystem dfs = (DistributedFileSystem)fs;
151       // Once our minimum supported Hadoop version is 2.6.0 we can remove reflection.
152       Class<? extends DistributedFileSystem> dfsClass = dfs.getClass();
153       Method m = null;
154       try {
155         m = dfsClass.getDeclaredMethod("setStoragePolicy",
156             new Class<?>[] { Path.class, String.class });
157         m.setAccessible(true);
158       } catch (NoSuchMethodException e) {
159         LOG.info("FileSystem doesn't support"
160             + " setStoragePolicy; --HDFS-6584 not available");
161       } catch (SecurityException e) {
162         LOG.info("Doesn't have access to setStoragePolicy on "
163             + "FileSystems --HDFS-6584 not available", e);
164         m = null; // could happen on setAccessible()
165       }
166       if (m != null) {
167         try {
168           m.invoke(dfs, path, storagePolicy);
169           LOG.info("set " + storagePolicy + " for " + path);
170         } catch (Exception e) {
171           // check for lack of HDFS-7228
172           boolean probablyBadPolicy = false;
173           if (e instanceof InvocationTargetException) {
174             final Throwable exception = e.getCause();
175             if (exception instanceof RemoteException &&
176                 HadoopIllegalArgumentException.class.getName().equals(
177                     ((RemoteException)exception).getClassName())) {
178               LOG.warn("Given storage policy, '" + storagePolicy + "', was rejected and probably " +
179                   "isn't a valid policy for the version of Hadoop you're running. I.e. if you're " +
180                   "trying to use SSD related policies then you're likely missing HDFS-7228. For " +
181                   "more information see the 'ArchivalStorage' docs for your Hadoop release.");
182               LOG.debug("More information about the invalid storage policy.", exception);
183               probablyBadPolicy = true;
184             }
185           }
186           if (!probablyBadPolicy) {
187             // This swallows FNFE, should we be throwing it? seems more likely to indicate dev
188             // misuse than a runtime problem with HDFS.
189             LOG.warn("Unable to set " + storagePolicy + " for " + path, e);
190           }
191         }
192       }
193     } else {
194       LOG.info("FileSystem isn't an instance of DistributedFileSystem; presuming it doesn't " +
195           "support setStoragePolicy.");
196     }
197   }
198 
199   /**
200    * @return True is <code>fs</code> is instance of DistributedFileSystem
201    * @throws IOException
202    */
203   public static boolean isDistributedFileSystem(final FileSystem fs) throws IOException {
204     FileSystem fileSystem = fs;
205     // If passed an instance of HFileSystem, it fails instanceof DistributedFileSystem.
206     // Check its backing fs for dfs-ness.
207     if (fs instanceof HFileSystem) {
208       fileSystem = ((HFileSystem)fs).getBackingFs();
209     }
210     return fileSystem instanceof DistributedFileSystem;
211   }
212  
213   /**
214    * Compare of path component. Does not consider schema; i.e. if schemas
215    * different but <code>path</code> starts with <code>rootPath</code>,
216    * then the function returns true
217    * @param rootPath
218    * @param path
219    * @return True if <code>path</code> starts with <code>rootPath</code>
220    */
221   public static boolean isStartingWithPath(final Path rootPath, final String path) {
222     String uriRootPath = rootPath.toUri().getPath();
223     String tailUriPath = (new Path(path)).toUri().getPath();
224     return tailUriPath.startsWith(uriRootPath);
225   }
226 
227   /**
228    * Compare path component of the Path URI; e.g. if hdfs://a/b/c and /a/b/c, it will compare the
229    * '/a/b/c' part. Does not consider schema; i.e. if schemas different but path or subpath matches,
230    * the two will equate.
231    * @param pathToSearch Path we will be trying to match.
232    * @param pathTail
233    * @return True if <code>pathTail</code> is tail on the path of <code>pathToSearch</code>
234    */
235   public static boolean isMatchingTail(final Path pathToSearch, String pathTail) {
236     return isMatchingTail(pathToSearch, new Path(pathTail));
237   }
238 
239   /**
240    * Compare path component of the Path URI; e.g. if hdfs://a/b/c and /a/b/c, it will compare the
241    * '/a/b/c' part. If you passed in 'hdfs://a/b/c and b/c, it would return true.  Does not consider
242    * schema; i.e. if schemas different but path or subpath matches, the two will equate.
243    * @param pathToSearch Path we will be trying to match.
244    * @param pathTail
245    * @return True if <code>pathTail</code> is tail on the path of <code>pathToSearch</code>
246    */
247   public static boolean isMatchingTail(final Path pathToSearch, final Path pathTail) {
248     if (pathToSearch.depth() != pathTail.depth()) return false;
249     Path tailPath = pathTail;
250     String tailName;
251     Path toSearch = pathToSearch;
252     String toSearchName;
253     boolean result = false;
254     do {
255       tailName = tailPath.getName();
256       if (tailName == null || tailName.length() <= 0) {
257         result = true;
258         break;
259       }
260       toSearchName = toSearch.getName();
261       if (toSearchName == null || toSearchName.length() <= 0) break;
262       // Move up a parent on each path for next go around.  Path doesn't let us go off the end.
263       tailPath = tailPath.getParent();
264       toSearch = toSearch.getParent();
265     } while(tailName.equals(toSearchName));
266     return result;
267   }
268 
269   public static FSUtils getInstance(FileSystem fs, Configuration conf) {
270     String scheme = fs.getUri().getScheme();
271     if (scheme == null) {
272       LOG.warn("Could not find scheme for uri " +
273           fs.getUri() + ", default to hdfs");
274       scheme = "hdfs";
275     }
276     Class<?> fsUtilsClass = conf.getClass("hbase.fsutil." +
277         scheme + ".impl", FSHDFSUtils.class); // Default to HDFS impl
278     FSUtils fsUtils = (FSUtils)ReflectionUtils.newInstance(fsUtilsClass, conf);
279     return fsUtils;
280   }
281 
282   /**
283    * Delete if exists.
284    * @param fs filesystem object
285    * @param dir directory to delete
286    * @return True if deleted <code>dir</code>
287    * @throws IOException e
288    */
289   public static boolean deleteDirectory(final FileSystem fs, final Path dir)
290   throws IOException {
291     return fs.exists(dir) && fs.delete(dir, true);
292   }
293 
294   /**
295    * Delete the region directory if exists.
296    * @param conf
297    * @param hri
298    * @return True if deleted the region directory.
299    * @throws IOException
300    */
301   public static boolean deleteRegionDir(final Configuration conf, final HRegionInfo hri)
302   throws IOException {
303     Path rootDir = getRootDir(conf);
304     FileSystem fs = rootDir.getFileSystem(conf);
305     return deleteDirectory(fs,
306       new Path(getTableDir(rootDir, hri.getTable()), hri.getEncodedName()));
307   }
308 
309   /**
310    * Return the number of bytes that large input files should be optimally
311    * be split into to minimize i/o time.
312    *
313    * use reflection to search for getDefaultBlockSize(Path f)
314    * if the method doesn't exist, fall back to using getDefaultBlockSize()
315    *
316    * @param fs filesystem object
317    * @return the default block size for the path's filesystem
318    * @throws IOException e
319    */
320   public static long getDefaultBlockSize(final FileSystem fs, final Path path) throws IOException {
321     Method m = null;
322     Class<? extends FileSystem> cls = fs.getClass();
323     try {
324       m = cls.getMethod("getDefaultBlockSize", new Class<?>[] { Path.class });
325     } catch (NoSuchMethodException e) {
326       LOG.info("FileSystem doesn't support getDefaultBlockSize");
327     } catch (SecurityException e) {
328       LOG.info("Doesn't have access to getDefaultBlockSize on FileSystems", e);
329       m = null; // could happen on setAccessible()
330     }
331     if (m == null) {
332       return fs.getDefaultBlockSize(path);
333     } else {
334       try {
335         Object ret = m.invoke(fs, path);
336         return ((Long)ret).longValue();
337       } catch (Exception e) {
338         throw new IOException(e);
339       }
340     }
341   }
342 
343   /*
344    * Get the default replication.
345    *
346    * use reflection to search for getDefaultReplication(Path f)
347    * if the method doesn't exist, fall back to using getDefaultReplication()
348    *
349    * @param fs filesystem object
350    * @param f path of file
351    * @return default replication for the path's filesystem
352    * @throws IOException e
353    */
354   public static short getDefaultReplication(final FileSystem fs, final Path path) throws IOException {
355     Method m = null;
356     Class<? extends FileSystem> cls = fs.getClass();
357     try {
358       m = cls.getMethod("getDefaultReplication", new Class<?>[] { Path.class });
359     } catch (NoSuchMethodException e) {
360       LOG.info("FileSystem doesn't support getDefaultReplication");
361     } catch (SecurityException e) {
362       LOG.info("Doesn't have access to getDefaultReplication on FileSystems", e);
363       m = null; // could happen on setAccessible()
364     }
365     if (m == null) {
366       return fs.getDefaultReplication(path);
367     } else {
368       try {
369         Object ret = m.invoke(fs, path);
370         return ((Number)ret).shortValue();
371       } catch (Exception e) {
372         throw new IOException(e);
373       }
374     }
375   }
376 
377   /**
378    * Returns the default buffer size to use during writes.
379    *
380    * The size of the buffer should probably be a multiple of hardware
381    * page size (4096 on Intel x86), and it determines how much data is
382    * buffered during read and write operations.
383    *
384    * @param fs filesystem object
385    * @return default buffer size to use during writes
386    */
387   public static int getDefaultBufferSize(final FileSystem fs) {
388     return fs.getConf().getInt("io.file.buffer.size", 4096);
389   }
390 
391   /**
392    * Create the specified file on the filesystem. By default, this will:
393    * <ol>
394    * <li>overwrite the file if it exists</li>
395    * <li>apply the umask in the configuration (if it is enabled)</li>
396    * <li>use the fs configured buffer size (or 4096 if not set)</li>
397    * <li>use the configured column family replication or default replication if
398    * {@link HColumnDescriptor#DEFAULT_DFS_REPLICATION}</li>
399    * <li>use the default block size</li>
400    * <li>not track progress</li>
401    * </ol>
402    * @param conf configurations
403    * @param fs {@link FileSystem} on which to write the file
404    * @param path {@link Path} to the file to write
405    * @param perm permissions
406    * @param favoredNodes
407    * @return output stream to the created file
408    * @throws IOException if the file cannot be created
409    */
410   public static FSDataOutputStream create(Configuration conf, FileSystem fs, Path path,
411       FsPermission perm, InetSocketAddress[] favoredNodes) throws IOException {
412     if (fs instanceof HFileSystem) {
413       FileSystem backingFs = ((HFileSystem)fs).getBackingFs();
414       if (backingFs instanceof DistributedFileSystem) {
415         // Try to use the favoredNodes version via reflection to allow backwards-
416         // compatibility.
417         short replication = Short.parseShort(conf.get(HColumnDescriptor.DFS_REPLICATION,
418           String.valueOf(HColumnDescriptor.DEFAULT_DFS_REPLICATION)));
419         try {
420           return (FSDataOutputStream) (DistributedFileSystem.class.getDeclaredMethod("create",
421             Path.class, FsPermission.class, boolean.class, int.class, short.class, long.class,
422             Progressable.class, InetSocketAddress[].class).invoke(backingFs, path, perm, true,
423             getDefaultBufferSize(backingFs),
424             replication > 0 ? replication : getDefaultReplication(backingFs, path),
425             getDefaultBlockSize(backingFs, path), null, favoredNodes));
426         } catch (InvocationTargetException ite) {
427           // Function was properly called, but threw it's own exception.
428           throw new IOException(ite.getCause());
429         } catch (NoSuchMethodException e) {
430           LOG.debug("DFS Client does not support most favored nodes create; using default create");
431           if (LOG.isTraceEnabled()) LOG.trace("Ignoring; use default create", e);
432         } catch (IllegalArgumentException e) {
433           LOG.debug("Ignoring (most likely Reflection related exception) " + e);
434         } catch (SecurityException e) {
435           LOG.debug("Ignoring (most likely Reflection related exception) " + e);
436         } catch (IllegalAccessException e) {
437           LOG.debug("Ignoring (most likely Reflection related exception) " + e);
438         }
439       }
440     }
441     return create(fs, path, perm, true);
442   }
443 
444   /**
445    * Create the specified file on the filesystem. By default, this will:
446    * <ol>
447    * <li>apply the umask in the configuration (if it is enabled)</li>
448    * <li>use the fs configured buffer size (or 4096 if not set)</li>
449    * <li>use the default replication</li>
450    * <li>use the default block size</li>
451    * <li>not track progress</li>
452    * </ol>
453    *
454    * @param fs {@link FileSystem} on which to write the file
455    * @param path {@link Path} to the file to write
456    * @param perm
457    * @param overwrite Whether or not the created file should be overwritten.
458    * @return output stream to the created file
459    * @throws IOException if the file cannot be created
460    */
461   public static FSDataOutputStream create(FileSystem fs, Path path,
462       FsPermission perm, boolean overwrite) throws IOException {
463     if (LOG.isTraceEnabled()) {
464       LOG.trace("Creating file=" + path + " with permission=" + perm + ", overwrite=" + overwrite);
465     }
466     return fs.create(path, perm, overwrite, getDefaultBufferSize(fs),
467         getDefaultReplication(fs, path), getDefaultBlockSize(fs, path), null);
468   }
469 
470   /**
471    * Get the file permissions specified in the configuration, if they are
472    * enabled.
473    *
474    * @param fs filesystem that the file will be created on.
475    * @param conf configuration to read for determining if permissions are
476    *          enabled and which to use
477    * @param permssionConfKey property key in the configuration to use when
478    *          finding the permission
479    * @return the permission to use when creating a new file on the fs. If
480    *         special permissions are not specified in the configuration, then
481    *         the default permissions on the the fs will be returned.
482    */
483   public static FsPermission getFilePermissions(final FileSystem fs,
484       final Configuration conf, final String permssionConfKey) {
485     boolean enablePermissions = conf.getBoolean(
486         HConstants.ENABLE_DATA_FILE_UMASK, false);
487 
488     if (enablePermissions) {
489       try {
490         FsPermission perm = new FsPermission(FULL_RWX_PERMISSIONS);
491         // make sure that we have a mask, if not, go default.
492         String mask = conf.get(permssionConfKey);
493         if (mask == null)
494           return FsPermission.getFileDefault();
495         // appy the umask
496         FsPermission umask = new FsPermission(mask);
497         return perm.applyUMask(umask);
498       } catch (IllegalArgumentException e) {
499         LOG.warn(
500             "Incorrect umask attempted to be created: "
501                 + conf.get(permssionConfKey)
502                 + ", using default file permissions.", e);
503         return FsPermission.getFileDefault();
504       }
505     }
506     return FsPermission.getFileDefault();
507   }
508 
509   /**
510    * Checks to see if the specified file system is available
511    *
512    * @param fs filesystem
513    * @throws IOException e
514    */
515   public static void checkFileSystemAvailable(final FileSystem fs)
516   throws IOException {
517     if (!(fs instanceof DistributedFileSystem)) {
518       return;
519     }
520     IOException exception = null;
521     DistributedFileSystem dfs = (DistributedFileSystem) fs;
522     try {
523       if (dfs.exists(new Path("/"))) {
524         return;
525       }
526     } catch (IOException e) {
527       exception = RemoteExceptionHandler.checkIOException(e);
528     }
529     try {
530       fs.close();
531     } catch (Exception e) {
532       LOG.error("file system close failed: ", e);
533     }
534     IOException io = new IOException("File system is not available");
535     io.initCause(exception);
536     throw io;
537   }
538 
539   /**
540    * We use reflection because {@link DistributedFileSystem#setSafeMode(
541    * HdfsConstants.SafeModeAction action, boolean isChecked)} is not in hadoop 1.1
542    *
543    * @param dfs
544    * @return whether we're in safe mode
545    * @throws IOException
546    */
547   private static boolean isInSafeMode(DistributedFileSystem dfs) throws IOException {
548     boolean inSafeMode = false;
549     try {
550       Method m = DistributedFileSystem.class.getMethod("setSafeMode", new Class<?> []{
551           org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.class, boolean.class});
552       inSafeMode = (Boolean) m.invoke(dfs,
553         org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.SAFEMODE_GET, true);
554     } catch (Exception e) {
555       if (e instanceof IOException) throw (IOException) e;
556 
557       // Check whether dfs is on safemode.
558       inSafeMode = dfs.setSafeMode(
559         org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction.SAFEMODE_GET);
560     }
561     return inSafeMode;
562   }
563 
564   /**
565    * Check whether dfs is in safemode.
566    * @param conf
567    * @throws IOException
568    */
569   public static void checkDfsSafeMode(final Configuration conf)
570   throws IOException {
571     boolean isInSafeMode = false;
572     FileSystem fs = FileSystem.get(conf);
573     if (fs instanceof DistributedFileSystem) {
574       DistributedFileSystem dfs = (DistributedFileSystem)fs;
575       isInSafeMode = isInSafeMode(dfs);
576     }
577     if (isInSafeMode) {
578       throw new IOException("File system is in safemode, it can't be written now");
579     }
580   }
581 
582   /**
583    * Verifies current version of file system
584    *
585    * @param fs filesystem object
586    * @param rootdir root hbase directory
587    * @return null if no version file exists, version string otherwise.
588    * @throws IOException e
589    * @throws org.apache.hadoop.hbase.exceptions.DeserializationException
590    */
591   public static String getVersion(FileSystem fs, Path rootdir)
592   throws IOException, DeserializationException {
593     Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME);
594     FileStatus[] status = null;
595     try {
596       // hadoop 2.0 throws FNFE if directory does not exist.
597       // hadoop 1.0 returns null if directory does not exist.
598       status = fs.listStatus(versionFile);
599     } catch (FileNotFoundException fnfe) {
600       return null;
601     }
602     if (status == null || status.length == 0) return null;
603     String version = null;
604     byte [] content = new byte [(int)status[0].getLen()];
605     FSDataInputStream s = fs.open(versionFile);
606     try {
607       IOUtils.readFully(s, content, 0, content.length);
608       if (ProtobufUtil.isPBMagicPrefix(content)) {
609         version = parseVersionFrom(content);
610       } else {
611         // Presume it pre-pb format.
612         InputStream is = new ByteArrayInputStream(content);
613         DataInputStream dis = new DataInputStream(is);
614         try {
615           version = dis.readUTF();
616         } finally {
617           dis.close();
618         }
619       }
620     } catch (EOFException eof) {
621       LOG.warn("Version file was empty, odd, will try to set it.");
622     } finally {
623       s.close();
624     }
625     return version;
626   }
627 
628   /**
629    * Parse the content of the ${HBASE_ROOTDIR}/hbase.version file.
630    * @param bytes The byte content of the hbase.version file.
631    * @return The version found in the file as a String.
632    * @throws DeserializationException
633    */
634   static String parseVersionFrom(final byte [] bytes)
635   throws DeserializationException {
636     ProtobufUtil.expectPBMagicPrefix(bytes);
637     int pblen = ProtobufUtil.lengthOfPBMagic();
638     FSProtos.HBaseVersionFileContent.Builder builder =
639       FSProtos.HBaseVersionFileContent.newBuilder();
640     try {
641       ProtobufUtil.mergeFrom(builder, bytes, pblen, bytes.length - pblen);
642       return builder.getVersion();
643     } catch (IOException e) {
644       // Convert
645       throw new DeserializationException(e);
646     }
647   }
648 
649   /**
650    * Create the content to write into the ${HBASE_ROOTDIR}/hbase.version file.
651    * @param version Version to persist
652    * @return Serialized protobuf with <code>version</code> content and a bit of pb magic for a prefix.
653    */
654   static byte [] toVersionByteArray(final String version) {
655     FSProtos.HBaseVersionFileContent.Builder builder =
656       FSProtos.HBaseVersionFileContent.newBuilder();
657     return ProtobufUtil.prependPBMagic(builder.setVersion(version).build().toByteArray());
658   }
659 
660   /**
661    * Verifies current version of file system
662    *
663    * @param fs file system
664    * @param rootdir root directory of HBase installation
665    * @param message if true, issues a message on System.out
666    *
667    * @throws IOException e
668    * @throws DeserializationException
669    */
670   public static void checkVersion(FileSystem fs, Path rootdir, boolean message)
671   throws IOException, DeserializationException {
672     checkVersion(fs, rootdir, message, 0, HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS);
673   }
674 
675   /**
676    * Verifies current version of file system
677    *
678    * @param fs file system
679    * @param rootdir root directory of HBase installation
680    * @param message if true, issues a message on System.out
681    * @param wait wait interval
682    * @param retries number of times to retry
683    *
684    * @throws IOException e
685    * @throws DeserializationException
686    */
687   public static void checkVersion(FileSystem fs, Path rootdir,
688       boolean message, int wait, int retries)
689   throws IOException, DeserializationException {
690     String version = getVersion(fs, rootdir);
691     if (version == null) {
692       if (!metaRegionExists(fs, rootdir)) {
693         // rootDir is empty (no version file and no root region)
694         // just create new version file (HBASE-1195)
695         setVersion(fs, rootdir, wait, retries);
696         return;
697       }
698     } else if (version.compareTo(HConstants.FILE_SYSTEM_VERSION) == 0) return;
699 
700     // version is deprecated require migration
701     // Output on stdout so user sees it in terminal.
702     String msg = "HBase file layout needs to be upgraded."
703       + " You have version " + version
704       + " and I want version " + HConstants.FILE_SYSTEM_VERSION
705       + ". Consult http://hbase.apache.org/book.html for further information about upgrading HBase."
706       + " Is your hbase.rootdir valid? If so, you may need to run "
707       + "'hbase hbck -fixVersionFile'.";
708     if (message) {
709       System.out.println("WARNING! " + msg);
710     }
711     throw new FileSystemVersionException(msg);
712   }
713 
714   /**
715    * Sets version of file system
716    *
717    * @param fs filesystem object
718    * @param rootdir hbase root
719    * @throws IOException e
720    */
721   public static void setVersion(FileSystem fs, Path rootdir)
722   throws IOException {
723     setVersion(fs, rootdir, HConstants.FILE_SYSTEM_VERSION, 0,
724       HConstants.DEFAULT_VERSION_FILE_WRITE_ATTEMPTS);
725   }
726 
727   /**
728    * Sets version of file system
729    *
730    * @param fs filesystem object
731    * @param rootdir hbase root
732    * @param wait time to wait for retry
733    * @param retries number of times to retry before failing
734    * @throws IOException e
735    */
736   public static void setVersion(FileSystem fs, Path rootdir, int wait, int retries)
737   throws IOException {
738     setVersion(fs, rootdir, HConstants.FILE_SYSTEM_VERSION, wait, retries);
739   }
740 
741 
742   /**
743    * Sets version of file system
744    *
745    * @param fs filesystem object
746    * @param rootdir hbase root directory
747    * @param version version to set
748    * @param wait time to wait for retry
749    * @param retries number of times to retry before throwing an IOException
750    * @throws IOException e
751    */
752   public static void setVersion(FileSystem fs, Path rootdir, String version,
753       int wait, int retries) throws IOException {
754     Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME);
755     Path tempVersionFile = new Path(rootdir, HConstants.HBASE_TEMP_DIRECTORY + Path.SEPARATOR +
756       HConstants.VERSION_FILE_NAME);
757     while (true) {
758       try {
759         // Write the version to a temporary file
760         FSDataOutputStream s = fs.create(tempVersionFile);
761         try {
762           s.write(toVersionByteArray(version));
763           s.close();
764           s = null;
765           // Move the temp version file to its normal location. Returns false
766           // if the rename failed. Throw an IOE in that case.
767           if (!fs.rename(tempVersionFile, versionFile)) {
768             throw new IOException("Unable to move temp version file to " + versionFile);
769           }
770         } finally {
771           // Cleaning up the temporary if the rename failed would be trying
772           // too hard. We'll unconditionally create it again the next time
773           // through anyway, files are overwritten by default by create().
774 
775           // Attempt to close the stream on the way out if it is still open.
776           try {
777             if (s != null) s.close();
778           } catch (IOException ignore) { }
779         }
780         LOG.info("Created version file at " + rootdir.toString() + " with version=" + version);
781         return;
782       } catch (IOException e) {
783         if (retries > 0) {
784           LOG.debug("Unable to create version file at " + rootdir.toString() + ", retrying", e);
785           fs.delete(versionFile, false);
786           try {
787             if (wait > 0) {
788               Thread.sleep(wait);
789             }
790           } catch (InterruptedException ie) {
791             throw (InterruptedIOException)new InterruptedIOException().initCause(ie);
792           }
793           retries--;
794         } else {
795           throw e;
796         }
797       }
798     }
799   }
800 
801   /**
802    * Checks that a cluster ID file exists in the HBase root directory
803    * @param fs the root directory FileSystem
804    * @param rootdir the HBase root directory in HDFS
805    * @param wait how long to wait between retries
806    * @return <code>true</code> if the file exists, otherwise <code>false</code>
807    * @throws IOException if checking the FileSystem fails
808    */
809   public static boolean checkClusterIdExists(FileSystem fs, Path rootdir,
810       int wait) throws IOException {
811     while (true) {
812       try {
813         Path filePath = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME);
814         return fs.exists(filePath);
815       } catch (IOException ioe) {
816         if (wait > 0) {
817           LOG.warn("Unable to check cluster ID file in " + rootdir.toString() +
818               ", retrying in "+wait+"msec: "+StringUtils.stringifyException(ioe));
819           try {
820             Thread.sleep(wait);
821           } catch (InterruptedException e) {
822             throw (InterruptedIOException)new InterruptedIOException().initCause(e);
823           }
824         } else {
825           throw ioe;
826         }
827       }
828     }
829   }
830 
831   /**
832    * Returns the value of the unique cluster ID stored for this HBase instance.
833    * @param fs the root directory FileSystem
834    * @param rootdir the path to the HBase root directory
835    * @return the unique cluster identifier
836    * @throws IOException if reading the cluster ID file fails
837    */
838   public static ClusterId getClusterId(FileSystem fs, Path rootdir)
839   throws IOException {
840     Path idPath = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME);
841     ClusterId clusterId = null;
842     FileStatus status = fs.exists(idPath)? fs.getFileStatus(idPath):  null;
843     if (status != null) {
844       int len = Ints.checkedCast(status.getLen());
845       byte [] content = new byte[len];
846       FSDataInputStream in = fs.open(idPath);
847       try {
848         in.readFully(content);
849       } catch (EOFException eof) {
850         LOG.warn("Cluster ID file " + idPath.toString() + " was empty");
851       } finally{
852         in.close();
853       }
854       try {
855         clusterId = ClusterId.parseFrom(content);
856       } catch (DeserializationException e) {
857         throw new IOException("content=" + Bytes.toString(content), e);
858       }
859       // If not pb'd, make it so.
860       if (!ProtobufUtil.isPBMagicPrefix(content)) {
861         String cid = null;
862         in = fs.open(idPath);
863         try {
864           cid = in.readUTF();
865           clusterId = new ClusterId(cid);
866         } catch (EOFException eof) {
867           LOG.warn("Cluster ID file " + idPath.toString() + " was empty");
868         } finally {
869           in.close();
870         }
871         rewriteAsPb(fs, rootdir, idPath, clusterId);
872       }
873       return clusterId;
874     } else {
875       LOG.warn("Cluster ID file does not exist at " + idPath.toString());
876     }
877     return clusterId;
878   }
879 
880   /**
881    * @param cid
882    * @throws IOException
883    */
884   private static void rewriteAsPb(final FileSystem fs, final Path rootdir, final Path p,
885       final ClusterId cid)
886   throws IOException {
887     // Rewrite the file as pb.  Move aside the old one first, write new
888     // then delete the moved-aside file.
889     Path movedAsideName = new Path(p + "." + System.currentTimeMillis());
890     if (!fs.rename(p, movedAsideName)) throw new IOException("Failed rename of " + p);
891     setClusterId(fs, rootdir, cid, 100);
892     if (!fs.delete(movedAsideName, false)) {
893       throw new IOException("Failed delete of " + movedAsideName);
894     }
895     LOG.debug("Rewrote the hbase.id file as pb");
896   }
897 
898   /**
899    * Writes a new unique identifier for this cluster to the "hbase.id" file
900    * in the HBase root directory
901    * @param fs the root directory FileSystem
902    * @param rootdir the path to the HBase root directory
903    * @param clusterId the unique identifier to store
904    * @param wait how long (in milliseconds) to wait between retries
905    * @throws IOException if writing to the FileSystem fails and no wait value
906    */
907   public static void setClusterId(FileSystem fs, Path rootdir, ClusterId clusterId,
908       int wait) throws IOException {
909     while (true) {
910       try {
911         Path idFile = new Path(rootdir, HConstants.CLUSTER_ID_FILE_NAME);
912         Path tempIdFile = new Path(rootdir, HConstants.HBASE_TEMP_DIRECTORY +
913           Path.SEPARATOR + HConstants.CLUSTER_ID_FILE_NAME);
914         // Write the id file to a temporary location
915         FSDataOutputStream s = fs.create(tempIdFile);
916         try {
917           s.write(clusterId.toByteArray());
918           s.close();
919           s = null;
920           // Move the temporary file to its normal location. Throw an IOE if
921           // the rename failed
922           if (!fs.rename(tempIdFile, idFile)) {
923             throw new IOException("Unable to move temp version file to " + idFile);
924           }
925         } finally {
926           // Attempt to close the stream if still open on the way out
927           try {
928             if (s != null) s.close();
929           } catch (IOException ignore) { }
930         }
931         if (LOG.isDebugEnabled()) {
932           LOG.debug("Created cluster ID file at " + idFile.toString() + " with ID: " + clusterId);
933         }
934         return;
935       } catch (IOException ioe) {
936         if (wait > 0) {
937           LOG.warn("Unable to create cluster ID file in " + rootdir.toString() +
938               ", retrying in " + wait + "msec: " + StringUtils.stringifyException(ioe));
939           try {
940             Thread.sleep(wait);
941           } catch (InterruptedException e) {
942             throw (InterruptedIOException)new InterruptedIOException().initCause(e);
943           }
944         } else {
945           throw ioe;
946         }
947       }
948     }
949   }
950 
951   /**
952    * Verifies root directory path is a valid URI with a scheme
953    *
954    * @param root root directory path
955    * @return Passed <code>root</code> argument.
956    * @throws IOException if not a valid URI with a scheme
957    */
958   public static Path validateRootPath(Path root) throws IOException {
959     try {
960       URI rootURI = new URI(root.toString());
961       String scheme = rootURI.getScheme();
962       if (scheme == null) {
963         throw new IOException("Root directory does not have a scheme");
964       }
965       return root;
966     } catch (URISyntaxException e) {
967       IOException io = new IOException("Root directory path is not a valid " +
968         "URI -- check your " + HBASE_DIR + " configuration");
969       io.initCause(e);
970       throw io;
971     }
972   }
973 
974   /**
975    * Checks for the presence of the WAL log root path (using the provided conf object) in the given path. If
976    * it exists, this method removes it and returns the String representation of remaining relative path.
977    * @param path
978    * @param conf
979    * @return String representation of the remaining relative path
980    * @throws IOException
981    */
982   public static String removeWALRootPath(Path path, final Configuration conf) throws IOException {
983     Path root = getWALRootDir(conf);
984     String pathStr = path.toString();
985     // check that the path is absolute... it has the root path in it.
986     if (!pathStr.startsWith(root.toString())) return pathStr;
987     // if not, return as it is.
988     return pathStr.substring(root.toString().length() + 1);// remove the "/" too.
989   }
990 
991   /**
992    * If DFS, check safe mode and if so, wait until we clear it.
993    * @param conf configuration
994    * @param wait Sleep between retries
995    * @throws IOException e
996    */
997   public static void waitOnSafeMode(final Configuration conf,
998     final long wait)
999   throws IOException {
1000     FileSystem fs = FileSystem.get(conf);
1001     if (!(fs instanceof DistributedFileSystem)) return;
1002     DistributedFileSystem dfs = (DistributedFileSystem)fs;
1003     // Make sure dfs is not in safe mode
1004     while (isInSafeMode(dfs)) {
1005       LOG.info("Waiting for dfs to exit safe mode...");
1006       try {
1007         Thread.sleep(wait);
1008       } catch (InterruptedException e) {
1009         throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1010       }
1011     }
1012   }
1013 
1014   /**
1015    * Return the 'path' component of a Path.  In Hadoop, Path is an URI.  This
1016    * method returns the 'path' component of a Path's URI: e.g. If a Path is
1017    * <code>hdfs://example.org:9000/hbase_trunk/TestTable/compaction.dir</code>,
1018    * this method returns <code>/hbase_trunk/TestTable/compaction.dir</code>.
1019    * This method is useful if you want to print out a Path without qualifying
1020    * Filesystem instance.
1021    * @param p Filesystem Path whose 'path' component we are to return.
1022    * @return Path portion of the Filesystem
1023    */
1024   public static String getPath(Path p) {
1025     return p.toUri().getPath();
1026   }
1027 
1028   /**
1029    * @param c configuration
1030    * @return {@link Path} to hbase root directory: i.e. {@value org.apache.hadoop.hbase.HConstants#HBASE_DIR} from
1031    * configuration as a qualified Path.
1032    * @throws IOException e
1033    */
1034   public static Path getRootDir(final Configuration c) throws IOException {
1035     Path p = new Path(c.get(HBASE_DIR));
1036     FileSystem fs = p.getFileSystem(c);
1037     return p.makeQualified(fs);
1038   }
1039 
1040   public static void setRootDir(final Configuration c, final Path root) throws IOException {
1041     c.set(HBASE_DIR, root.toString());
1042   }
1043 
1044   public static void setFsDefault(final Configuration c, final Path root) throws IOException {
1045     c.set("fs.defaultFS", root.toString());    // for hadoop 0.21+
1046   }
1047 
1048   public static FileSystem getRootDirFileSystem(final Configuration c) throws IOException {
1049     Path p = getRootDir(c);
1050     return p.getFileSystem(c);
1051   }
1052 
1053   /**
1054    * @param c configuration
1055    * @return {@link Path} to hbase log root directory: i.e. {@value org.apache.hadoop.hbase.fs.HFileSystem#HBASE_WAL_DIR} from
1056    * configuration as a qualified Path. Defaults to {@value org.apache.hadoop.hbase.HConstants#HBASE_DIR}
1057    * @throws IOException e
1058    */
1059   public static Path getWALRootDir(final Configuration c) throws IOException {
1060     Path p = new Path(c.get(HFileSystem.HBASE_WAL_DIR, c.get(HBASE_DIR)));
1061     if (!isValidWALRootDir(p, c)) {
1062       return FSUtils.getRootDir(c);
1063     }
1064     FileSystem fs = p.getFileSystem(c);
1065     return p.makeQualified(fs);
1066   }
1067 
1068   @VisibleForTesting
1069   public static void setWALRootDir(final Configuration c, final Path root) throws IOException {
1070     c.set(HFileSystem.HBASE_WAL_DIR, root.toString());
1071   }
1072 
1073   public static FileSystem getWALFileSystem(final Configuration c) throws IOException {
1074     Path p = getWALRootDir(c);
1075     return p.getFileSystem(c);
1076   }
1077 
1078   private static boolean isValidWALRootDir(Path walDir, final Configuration c) throws IOException {
1079     Path rootDir = FSUtils.getRootDir(c);
1080     if (!walDir.equals(rootDir)) {
1081       if (walDir.toString().startsWith(rootDir.toString() + "/")) {
1082         throw new IllegalStateException("Illegal WAL directory specified. " +
1083             "WAL directories are not permitted to be under the root directory if set.");
1084       }
1085     }
1086     return true;
1087   }
1088 
1089   /**
1090    * Returns the WAL region directory based on the region info
1091    * @param conf configuration to determine WALRootDir
1092    * @param regionInfo used to get region and table
1093    * @return the region directory used to store WALs under the WALRootDir
1094    * @throws IOException if there is an exception determining the WALRootDir
1095    */
1096   public static Path getWALRegionDir(final Configuration conf, final HRegionInfo regionInfo)
1097       throws IOException {
1098     return new Path(getWALTableDir(conf, regionInfo.getTable()),
1099         regionInfo.getEncodedName());
1100   }
1101 
1102   /**
1103    * Returns the WAL region directory based on the region info
1104    * @param conf configuration to determine WALRootDir
1105    * @param tableName the table name
1106    * @param encodedRegionName the encoded region name
1107    * @return the region directory used to store WALs under the WALRootDir
1108    * @throws IOException if there is an exception determining the WALRootDir
1109    */
1110   public static Path getWALRegionDir(final Configuration conf, final TableName tableName,
1111       final String encodedRegionName) throws IOException {
1112     return new Path(getWALTableDir(conf, tableName), encodedRegionName);
1113   }
1114 
1115   /**
1116    * Checks if meta region exists
1117    *
1118    * @param fs file system
1119    * @param rootDir root directory of HBase installation
1120    * @return true if exists
1121    * @throws IOException e
1122    */
1123   @SuppressWarnings("deprecation")
1124   public static boolean metaRegionExists(FileSystem fs, Path rootDir) throws IOException {
1125     Path metaRegionDir = getRegionDirFromRootDir(rootDir, HRegionInfo.FIRST_META_REGIONINFO);
1126     return fs.exists(metaRegionDir);
1127   }
1128 
1129   /**
1130    * Compute HDFS blocks distribution of a given file, or a portion of the file
1131    * @param fs file system
1132    * @param status file status of the file
1133    * @param start start position of the portion
1134    * @param length length of the portion
1135    * @return The HDFS blocks distribution
1136    */
1137   static public HDFSBlocksDistribution computeHDFSBlocksDistribution(
1138     final FileSystem fs, FileStatus status, long start, long length)
1139     throws IOException {
1140     HDFSBlocksDistribution blocksDistribution = new HDFSBlocksDistribution();
1141     BlockLocation [] blockLocations =
1142       fs.getFileBlockLocations(status, start, length);
1143     for(BlockLocation bl : blockLocations) {
1144       String [] hosts = bl.getHosts();
1145       long len = bl.getLength();
1146       blocksDistribution.addHostsAndBlockWeight(hosts, len);
1147     }
1148 
1149     return blocksDistribution;
1150   }
1151 
1152   /**
1153    * Update blocksDistribution with blockLocations
1154    * @param blocksDistribution the hdfs blocks distribution
1155    * @param blockLocations an array containing block location
1156    */
1157   static public void addToHDFSBlocksDistribution(
1158       HDFSBlocksDistribution blocksDistribution, BlockLocation[] blockLocations)
1159       throws IOException {
1160     for (BlockLocation bl : blockLocations) {
1161       String[] hosts = bl.getHosts();
1162       long len = bl.getLength();
1163       blocksDistribution.addHostsAndBlockWeight(hosts, len);
1164     }
1165   }
1166 
1167   // TODO move this method OUT of FSUtils. No dependencies to HMaster
1168   /**
1169    * Returns the total overall fragmentation percentage. Includes hbase:meta and
1170    * -ROOT- as well.
1171    *
1172    * @param master  The master defining the HBase root and file system.
1173    * @return A map for each table and its percentage.
1174    * @throws IOException When scanning the directory fails.
1175    */
1176   public static int getTotalTableFragmentation(final HMaster master)
1177   throws IOException {
1178     Map<String, Integer> map = getTableFragmentation(master);
1179     return map != null && map.size() > 0 ? map.get("-TOTAL-") : -1;
1180   }
1181 
1182   /**
1183    * Runs through the HBase rootdir and checks how many stores for each table
1184    * have more than one file in them. Checks -ROOT- and hbase:meta too. The total
1185    * percentage across all tables is stored under the special key "-TOTAL-".
1186    *
1187    * @param master  The master defining the HBase root and file system.
1188    * @return A map for each table and its percentage.
1189    *
1190    * @throws IOException When scanning the directory fails.
1191    */
1192   public static Map<String, Integer> getTableFragmentation(
1193     final HMaster master)
1194   throws IOException {
1195     Path path = getRootDir(master.getConfiguration());
1196     // since HMaster.getFileSystem() is package private
1197     FileSystem fs = path.getFileSystem(master.getConfiguration());
1198     return getTableFragmentation(fs, path);
1199   }
1200 
1201   /**
1202    * Runs through the HBase rootdir and checks how many stores for each table
1203    * have more than one file in them. Checks -ROOT- and hbase:meta too. The total
1204    * percentage across all tables is stored under the special key "-TOTAL-".
1205    *
1206    * @param fs  The file system to use.
1207    * @param hbaseRootDir  The root directory to scan.
1208    * @return A map for each table and its percentage.
1209    * @throws IOException When scanning the directory fails.
1210    */
1211   public static Map<String, Integer> getTableFragmentation(
1212     final FileSystem fs, final Path hbaseRootDir)
1213   throws IOException {
1214     Map<String, Integer> frags = new HashMap<String, Integer>();
1215     int cfCountTotal = 0;
1216     int cfFragTotal = 0;
1217     PathFilter regionFilter = new RegionDirFilter(fs);
1218     PathFilter familyFilter = new FamilyDirFilter(fs);
1219     List<Path> tableDirs = getTableDirs(fs, hbaseRootDir);
1220     for (Path d : tableDirs) {
1221       int cfCount = 0;
1222       int cfFrag = 0;
1223       FileStatus[] regionDirs = fs.listStatus(d, regionFilter);
1224       for (FileStatus regionDir : regionDirs) {
1225         Path dd = regionDir.getPath();
1226         // else its a region name, now look in region for families
1227         FileStatus[] familyDirs = fs.listStatus(dd, familyFilter);
1228         for (FileStatus familyDir : familyDirs) {
1229           cfCount++;
1230           cfCountTotal++;
1231           Path family = familyDir.getPath();
1232           // now in family make sure only one file
1233           FileStatus[] familyStatus = fs.listStatus(family);
1234           if (familyStatus.length > 1) {
1235             cfFrag++;
1236             cfFragTotal++;
1237           }
1238         }
1239       }
1240       // compute percentage per table and store in result list
1241       frags.put(FSUtils.getTableName(d).getNameAsString(),
1242         cfCount == 0? 0: Math.round((float) cfFrag / cfCount * 100));
1243     }
1244     // set overall percentage for all tables
1245     frags.put("-TOTAL-",
1246       cfCountTotal == 0? 0: Math.round((float) cfFragTotal / cfCountTotal * 100));
1247     return frags;
1248   }
1249 
1250   /**
1251    * Returns the {@link org.apache.hadoop.fs.Path} object representing the table directory under
1252    * path rootdir
1253    *
1254    * @param rootdir qualified path of HBase root directory
1255    * @param tableName name of table
1256    * @return {@link org.apache.hadoop.fs.Path} for table
1257    */
1258   public static Path getTableDir(Path rootdir, final TableName tableName) {
1259     return new Path(getNamespaceDir(rootdir, tableName.getNamespaceAsString()),
1260         tableName.getQualifierAsString());
1261   }
1262 
1263   /**
1264    * Returns the Table directory under the WALRootDir for the specified table name
1265    * @param conf configuration used to get the WALRootDir
1266    * @param tableName Table to get the directory for
1267    * @return a path to the WAL table directory for the specified table
1268    * @throws IOException if there is an exception determining the WALRootDir
1269    */
1270   public static Path getWALTableDir(final Configuration conf, final TableName tableName)
1271       throws IOException {
1272     Path baseDir = new Path(getWALRootDir(conf), HConstants.BASE_NAMESPACE_DIR);
1273     return new Path(new Path(baseDir, tableName.getNamespaceAsString()),
1274       tableName.getQualifierAsString());
1275   }
1276 
1277   /**
1278    * For backward compatibility with HBASE-20734, where we store recovered edits in a wrong
1279    * directory without BASE_NAMESPACE_DIR. See HBASE-22617 for more details.
1280    * @deprecated For compatibility, will be removed in 4.0.0.
1281    */
1282   @Deprecated
1283   public static Path getWrongWALRegionDir(final Configuration conf, final TableName tableName,
1284       final String encodedRegionName) throws IOException {
1285     Path wrongTableDir = new Path(new Path(getWALRootDir(conf), tableName.getNamespaceAsString()),
1286       tableName.getQualifierAsString());
1287     return new Path(wrongTableDir, encodedRegionName);
1288   }
1289 
1290   /**
1291    * Returns the {@link org.apache.hadoop.hbase.TableName} object representing
1292    * the table directory under
1293    * path rootdir
1294    *
1295    * @param tablePath path of table
1296    * @return {@link org.apache.hadoop.fs.Path} for table
1297    */
1298   public static TableName getTableName(Path tablePath) {
1299     return TableName.valueOf(tablePath.getParent().getName(), tablePath.getName());
1300   }
1301 
1302   /**
1303    * Returns the {@link org.apache.hadoop.fs.Path} object representing
1304    * the namespace directory under path rootdir
1305    *
1306    * @param rootdir qualified path of HBase root directory
1307    * @param namespace namespace name
1308    * @return {@link org.apache.hadoop.fs.Path} for table
1309    */
1310   public static Path getNamespaceDir(Path rootdir, final String namespace) {
1311     return new Path(rootdir, new Path(HConstants.BASE_NAMESPACE_DIR,
1312         new Path(namespace)));
1313   }
1314 
1315   /**
1316    * A {@link PathFilter} that returns only regular files.
1317    */
1318   static class FileFilter extends AbstractFileStatusFilter {
1319     private final FileSystem fs;
1320 
1321     public FileFilter(final FileSystem fs) {
1322       this.fs = fs;
1323     }
1324 
1325     @Override
1326     protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1327       try {
1328         return isFile(fs, isDir, p);
1329       } catch (IOException e) {
1330         LOG.warn("unable to verify if path=" + p + " is a regular file", e);
1331         return false;
1332       }
1333     }
1334   }
1335 
1336   /**
1337    * Directory filter that doesn't include any of the directories in the specified blacklist
1338    */
1339   public static class BlackListDirFilter extends AbstractFileStatusFilter {
1340     private final FileSystem fs;
1341     private List<String> blacklist;
1342 
1343     /**
1344      * Create a filter on the givem filesystem with the specified blacklist
1345      * @param fs filesystem to filter
1346      * @param directoryNameBlackList list of the names of the directories to filter. If
1347      *          <tt>null</tt>, all directories are returned
1348      */
1349     @SuppressWarnings("unchecked")
1350     public BlackListDirFilter(final FileSystem fs, final List<String> directoryNameBlackList) {
1351       this.fs = fs;
1352       blacklist =
1353         (List<String>) (directoryNameBlackList == null ? Collections.emptyList()
1354           : directoryNameBlackList);
1355     }
1356 
1357     @Override
1358     protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1359       if (!isValidName(p.getName())) {
1360         return false;
1361       }
1362 
1363       try {
1364         return isDirectory(fs, isDir, p);
1365       } catch (IOException e) {
1366         LOG.warn("An error occurred while verifying if [" + p.toString()
1367             + "] is a valid directory. Returning 'not valid' and continuing.", e);
1368         return false;
1369       }
1370     }
1371 
1372     protected boolean isValidName(final String name) {
1373       return !blacklist.contains(name);
1374     }
1375   }
1376 
1377   /**
1378    * A {@link PathFilter} that only allows directories.
1379    */
1380   public static class DirFilter extends BlackListDirFilter {
1381 
1382     public DirFilter(FileSystem fs) {
1383       super(fs, null);
1384     }
1385   }
1386 
1387   /**
1388    * A {@link PathFilter} that returns usertable directories. To get all directories use the
1389    * {@link BlackListDirFilter} with a <tt>null</tt> blacklist
1390    */
1391   public static class UserTableDirFilter extends BlackListDirFilter {
1392     public UserTableDirFilter(FileSystem fs) {
1393       super(fs, HConstants.HBASE_NON_TABLE_DIRS);
1394     }
1395 
1396     @Override
1397     protected boolean isValidName(final String name) {
1398       if (!super.isValidName(name))
1399         return false;
1400 
1401       try {
1402         TableName.isLegalTableQualifierName(Bytes.toBytes(name));
1403       } catch (IllegalArgumentException e) {
1404         LOG.info("INVALID NAME " + name);
1405         return false;
1406       }
1407       return true;
1408     }
1409   }
1410 
1411   /**
1412    * Heuristic to determine whether is safe or not to open a file for append
1413    * Looks both for dfs.support.append and use reflection to search
1414    * for SequenceFile.Writer.syncFs() or FSDataOutputStream.hflush()
1415    * @param conf
1416    * @return True if append support
1417    */
1418   public static boolean isAppendSupported(final Configuration conf) {
1419     boolean append = conf.getBoolean("dfs.support.append", false);
1420     if (append) {
1421       try {
1422         // TODO: The implementation that comes back when we do a createWriter
1423         // may not be using SequenceFile so the below is not a definitive test.
1424         // Will do for now (hdfs-200).
1425         SequenceFile.Writer.class.getMethod("syncFs", new Class<?> []{});
1426         append = true;
1427       } catch (SecurityException e) {
1428       } catch (NoSuchMethodException e) {
1429         append = false;
1430       }
1431     }
1432     if (!append) {
1433       // Look for the 0.21, 0.22, new-style append evidence.
1434       try {
1435         FSDataOutputStream.class.getMethod("hflush", new Class<?> []{});
1436         append = true;
1437       } catch (NoSuchMethodException e) {
1438         append = false;
1439       }
1440     }
1441     return append;
1442   }
1443 
1444   /**
1445    * @param conf
1446    * @return True if this filesystem whose scheme is 'hdfs'.
1447    * @throws IOException
1448    */
1449   public static boolean isHDFS(final Configuration conf) throws IOException {
1450     FileSystem fs = FileSystem.get(conf);
1451     String scheme = fs.getUri().getScheme();
1452     return scheme.equalsIgnoreCase("hdfs");
1453   }
1454 
1455   /**
1456    * Recover file lease. Used when a file might be suspect
1457    * to be had been left open by another process.
1458    * @param fs FileSystem handle
1459    * @param p Path of file to recover lease
1460    * @param conf Configuration handle
1461    * @throws IOException
1462    */
1463   public abstract void recoverFileLease(final FileSystem fs, final Path p,
1464       Configuration conf, CancelableProgressable reporter) throws IOException;
1465 
1466   public static List<Path> getTableDirs(final FileSystem fs, final Path rootdir)
1467       throws IOException {
1468     List<Path> tableDirs = new LinkedList<Path>();
1469 
1470     for(FileStatus status :
1471         fs.globStatus(new Path(rootdir,
1472             new Path(HConstants.BASE_NAMESPACE_DIR, "*")))) {
1473       tableDirs.addAll(FSUtils.getLocalTableDirs(fs, status.getPath()));
1474     }
1475     return tableDirs;
1476   }
1477 
1478   /**
1479    * @param fs
1480    * @param rootdir
1481    * @return All the table directories under <code>rootdir</code>. Ignore non table hbase folders such as
1482    * .logs, .oldlogs, .corrupt folders.
1483    * @throws IOException
1484    */
1485   public static List<Path> getLocalTableDirs(final FileSystem fs, final Path rootdir)
1486       throws IOException {
1487     // presumes any directory under hbase.rootdir is a table
1488     FileStatus[] dirs = fs.listStatus(rootdir, new UserTableDirFilter(fs));
1489     List<Path> tabledirs = new ArrayList<Path>(dirs.length);
1490     for (FileStatus dir: dirs) {
1491       tabledirs.add(dir.getPath());
1492     }
1493     return tabledirs;
1494   }
1495 
1496   /**
1497    * Checks if the given path is the one with 'recovered.edits' dir.
1498    * @param path
1499    * @return True if we recovered edits
1500    */
1501   public static boolean isRecoveredEdits(Path path) {
1502     return path.toString().contains(HConstants.RECOVERED_EDITS_DIR);
1503   }
1504 
1505   /**
1506    * Filter for all dirs that don't start with '.'
1507    */
1508   public static class RegionDirFilter extends AbstractFileStatusFilter {
1509     // This pattern will accept 0.90+ style hex region dirs and older numeric region dir names.
1510     final public static Pattern regionDirPattern = Pattern.compile("^[0-9a-f]*$");
1511     final FileSystem fs;
1512 
1513     public RegionDirFilter(FileSystem fs) {
1514       this.fs = fs;
1515     }
1516 
1517     @Override
1518     protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1519       if (!regionDirPattern.matcher(p.getName()).matches()) {
1520         return false;
1521       }
1522 
1523       try {
1524         return isDirectory(fs, isDir, p);
1525       } catch (IOException ioe) {
1526         // Maybe the file was moved or the fs was disconnected.
1527         LOG.warn("Skipping file " + p +" due to IOException", ioe);
1528         return false;
1529       }
1530     }
1531   }
1532 
1533   public static Path getRegionDirFromRootDir(Path rootDir, HRegionInfo region) {
1534     return getRegionDirFromTableDir(getTableDir(rootDir, region.getTable()), region);
1535   }
1536 
1537   public static Path getRegionDirFromTableDir(Path tableDir, HRegionInfo region) {
1538     return new Path(tableDir, ServerRegionReplicaUtil.getRegionInfoForFs(region).getEncodedName());
1539   }
1540 
1541   /**
1542    * Given a particular table dir, return all the regiondirs inside it, excluding files such as
1543    * .tableinfo
1544    * @param fs A file system for the Path
1545    * @param tableDir Path to a specific table directory &lt;hbase.rootdir&gt;/&lt;tabledir&gt;
1546    * @return List of paths to valid region directories in table dir.
1547    * @throws IOException
1548    */
1549   public static List<Path> getRegionDirs(final FileSystem fs, final Path tableDir) throws IOException {
1550     // assumes we are in a table dir.
1551     List<FileStatus> rds = listStatusWithStatusFilter(fs, tableDir, new RegionDirFilter(fs));
1552     if (rds == null) {
1553       return new ArrayList<Path>();
1554     }
1555     List<Path> regionDirs = new ArrayList<Path>(rds.size());
1556     for (FileStatus rdfs: rds) {
1557       Path rdPath = rdfs.getPath();
1558       regionDirs.add(rdPath);
1559     }
1560     return regionDirs;
1561   }
1562 
1563   /**
1564    * Filter for all dirs that are legal column family names.  This is generally used for colfam
1565    * dirs &lt;hbase.rootdir&gt;/&lt;tabledir&gt;/&lt;regiondir&gt;/&lt;colfamdir&gt;.
1566    */
1567   public static class FamilyDirFilter extends AbstractFileStatusFilter {
1568     final FileSystem fs;
1569 
1570     public FamilyDirFilter(FileSystem fs) {
1571       this.fs = fs;
1572     }
1573 
1574     @Override
1575     protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1576       try {
1577         // throws IAE if invalid
1578         HColumnDescriptor.isLegalFamilyName(Bytes.toBytes(p.getName()));
1579       } catch (IllegalArgumentException iae) {
1580         // path name is an invalid family name and thus is excluded.
1581         return false;
1582       }
1583 
1584       try {
1585         return isDirectory(fs, isDir, p);
1586       } catch (IOException ioe) {
1587         // Maybe the file was moved or the fs was disconnected.
1588         LOG.warn("Skipping file " + p +" due to IOException", ioe);
1589         return false;
1590       }
1591     }
1592   }
1593 
1594   /**
1595    * Given a particular region dir, return all the familydirs inside it
1596    *
1597    * @param fs A file system for the Path
1598    * @param regionDir Path to a specific region directory
1599    * @return List of paths to valid family directories in region dir.
1600    * @throws IOException
1601    */
1602   public static List<Path> getFamilyDirs(final FileSystem fs, final Path regionDir) throws IOException {
1603     // assumes we are in a region dir.
1604     FileStatus[] fds = fs.listStatus(regionDir, new FamilyDirFilter(fs));
1605     List<Path> familyDirs = new ArrayList<Path>(fds.length);
1606     for (FileStatus fdfs: fds) {
1607       Path fdPath = fdfs.getPath();
1608       familyDirs.add(fdPath);
1609     }
1610     return familyDirs;
1611   }
1612 
1613   public static List<Path> getReferenceFilePaths(final FileSystem fs, final Path familyDir) throws IOException {
1614     List<FileStatus> fds = listStatusWithStatusFilter(fs, familyDir, new ReferenceFileFilter(fs));
1615     if (fds == null) {
1616       return new ArrayList<Path>();
1617     }
1618     List<Path> referenceFiles = new ArrayList<Path>(fds.size());
1619     for (FileStatus fdfs: fds) {
1620       Path fdPath = fdfs.getPath();
1621       referenceFiles.add(fdPath);
1622     }
1623     return referenceFiles;
1624   }
1625 
1626   /**
1627    * Filter for HFiles that excludes reference files.
1628    */
1629   public static class HFileFilter extends AbstractFileStatusFilter {
1630     final FileSystem fs;
1631 
1632     public HFileFilter(FileSystem fs) {
1633       this.fs = fs;
1634     }
1635 
1636     @Override
1637     protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1638       if (!StoreFileInfo.isHFile(p)) {
1639         return false;
1640       }
1641 
1642       try {
1643         return isFile(fs, isDir, p);
1644       } catch (IOException ioe) {
1645         // Maybe the file was moved or the fs was disconnected.
1646         LOG.warn("Skipping file " + p +" due to IOException", ioe);
1647         return false;
1648       }
1649     }
1650   }
1651 
1652   /**
1653    * Filter for HFileLinks (StoreFiles and HFiles not included).
1654    * the filter itself does not consider if a link is file or not.
1655    */
1656   public static class HFileLinkFilter implements PathFilter {
1657 
1658     @Override
1659     public boolean accept(Path p) {
1660       return HFileLink.isHFileLink(p);
1661     }
1662   }
1663 
1664   public static class ReferenceFileFilter extends AbstractFileStatusFilter {
1665 
1666     private final FileSystem fs;
1667 
1668     public ReferenceFileFilter(FileSystem fs) {
1669       this.fs = fs;
1670     }
1671 
1672     @Override
1673     protected boolean accept(Path p, @CheckForNull Boolean isDir) {
1674       if (!StoreFileInfo.isReference(p)) {
1675         return false;
1676       }
1677 
1678       try {
1679         // only files can be references.
1680         return isFile(fs, isDir, p);
1681       } catch (IOException ioe) {
1682         // Maybe the file was moved or the fs was disconnected.
1683         LOG.warn("Skipping file " + p +" due to IOException", ioe);
1684         return false;
1685       }
1686     }
1687   }
1688 
1689 
1690   /**
1691    * @param conf
1692    * @return Returns the filesystem of the hbase rootdir.
1693    * @throws IOException
1694    */
1695   public static FileSystem getCurrentFileSystem(Configuration conf)
1696   throws IOException {
1697     return getRootDir(conf).getFileSystem(conf);
1698   }
1699 
1700 
1701   /**
1702    * Runs through the HBase rootdir/tablename and creates a reverse lookup map for
1703    * table StoreFile names to the full Path.
1704    * <br>
1705    * Example...<br>
1706    * Key = 3944417774205889744  <br>
1707    * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744
1708    *
1709    * @param map map to add values.  If null, this method will create and populate one to return
1710    * @param fs  The file system to use.
1711    * @param hbaseRootDir  The root directory to scan.
1712    * @param tableName name of the table to scan.
1713    * @return Map keyed by StoreFile name with a value of the full Path.
1714    * @throws IOException When scanning the directory fails.
1715    * @throws InterruptedException
1716    */
1717   public static Map<String, Path> getTableStoreFilePathMap(Map<String, Path> map,
1718   final FileSystem fs, final Path hbaseRootDir, TableName tableName)
1719   throws IOException, InterruptedException {
1720     return getTableStoreFilePathMap(map, fs, hbaseRootDir, tableName, null, null, null);
1721   }
1722 
1723   /**
1724    * Runs through the HBase rootdir/tablename and creates a reverse lookup map for
1725    * table StoreFile names to the full Path.  Note that because this method can be called
1726    * on a 'live' HBase system that we will skip files that no longer exist by the time
1727    * we traverse them and similarly the user of the result needs to consider that some
1728    * entries in this map may not exist by the time this call completes.
1729    * <br>
1730    * Example...<br>
1731    * Key = 3944417774205889744  <br>
1732    * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744
1733    *
1734    * @param resultMap map to add values.  If null, this method will create and populate one to return
1735    * @param fs  The file system to use.
1736    * @param hbaseRootDir  The root directory to scan.
1737    * @param tableName name of the table to scan.
1738    * @param sfFilter optional path filter to apply to store files
1739    * @param executor optional executor service to parallelize this operation
1740    * @param errors ErrorReporter instance or null
1741    * @return Map keyed by StoreFile name with a value of the full Path.
1742    * @throws IOException When scanning the directory fails.
1743    * @throws InterruptedException
1744    */
1745   public static Map<String, Path> getTableStoreFilePathMap(
1746       Map<String, Path> resultMap,
1747       final FileSystem fs, final Path hbaseRootDir, TableName tableName, final PathFilter sfFilter,
1748       ExecutorService executor, final ErrorReporter errors) throws IOException, InterruptedException {
1749 
1750     final Map<String, Path> finalResultMap =
1751         resultMap == null ? new ConcurrentHashMap<String, Path>(128, 0.75f, 32) : resultMap;
1752 
1753     // only include the directory paths to tables
1754     Path tableDir = FSUtils.getTableDir(hbaseRootDir, tableName);
1755     // Inside a table, there are compaction.dir directories to skip.  Otherwise, all else
1756     // should be regions.
1757     final FamilyDirFilter familyFilter = new FamilyDirFilter(fs);
1758     final Vector<Exception> exceptions = new Vector<Exception>();
1759 
1760     try {
1761       List<FileStatus> regionDirs = FSUtils.listStatusWithStatusFilter(fs, tableDir, new RegionDirFilter(fs));
1762       if (regionDirs == null) {
1763         return finalResultMap;
1764       }
1765 
1766       final List<Future<?>> futures = new ArrayList<Future<?>>(regionDirs.size());
1767 
1768       for (FileStatus regionDir : regionDirs) {
1769         if (null != errors) {
1770           errors.progress();
1771         }
1772         final Path dd = regionDir.getPath();
1773 
1774         if (!exceptions.isEmpty()) {
1775           break;
1776         }
1777 
1778         Runnable getRegionStoreFileMapCall = new Runnable() {
1779           @Override
1780           public void run() {
1781             try {
1782               HashMap<String,Path> regionStoreFileMap = new HashMap<String, Path>();
1783               List<FileStatus> familyDirs = FSUtils.listStatusWithStatusFilter(fs, dd, familyFilter);
1784               if (familyDirs == null) {
1785                 if (!fs.exists(dd)) {
1786                   LOG.warn("Skipping region because it no longer exists: " + dd);
1787                 } else {
1788                   LOG.warn("Skipping region because it has no family dirs: " + dd);
1789                 }
1790                 return;
1791               }
1792               for (FileStatus familyDir : familyDirs) {
1793                 if (null != errors) {
1794                   errors.progress();
1795                 }
1796                 Path family = familyDir.getPath();
1797                 if (family.getName().equals(HConstants.RECOVERED_EDITS_DIR)) {
1798                   continue;
1799                 }
1800                 // now in family, iterate over the StoreFiles and
1801                 // put in map
1802                 FileStatus[] familyStatus = fs.listStatus(family);
1803                 for (FileStatus sfStatus : familyStatus) {
1804                   if (null != errors) {
1805                     errors.progress();
1806                   }
1807                   Path sf = sfStatus.getPath();
1808                   if (sfFilter == null || sfFilter.accept(sf)) {
1809                     regionStoreFileMap.put( sf.getName(), sf);
1810                   }
1811                 }
1812               }
1813               finalResultMap.putAll(regionStoreFileMap);
1814             } catch (Exception e) {
1815               LOG.error("Could not get region store file map for region: " + dd, e);
1816               exceptions.add(e);
1817             }
1818           }
1819         };
1820 
1821         // If executor is available, submit async tasks to exec concurrently, otherwise
1822         // just do serial sync execution
1823         if (executor != null) {
1824           Future<?> future = executor.submit(getRegionStoreFileMapCall);
1825           futures.add(future);
1826         } else {
1827           FutureTask<?> future = new FutureTask<Object>(getRegionStoreFileMapCall, null);
1828           future.run();
1829           futures.add(future);
1830         }
1831       }
1832 
1833       // Ensure all pending tasks are complete (or that we run into an exception)
1834       for (Future<?> f : futures) {
1835         if (!exceptions.isEmpty()) {
1836           break;
1837         }
1838         try {
1839           f.get();
1840         } catch (ExecutionException e) {
1841           LOG.error("Unexpected exec exception!  Should've been caught already.  (Bug?)", e);
1842           // Shouldn't happen, we already logged/caught any exceptions in the Runnable
1843         }
1844       }
1845     } catch (IOException e) {
1846       LOG.error("Cannot execute getTableStoreFilePathMap for " + tableName, e);
1847       exceptions.add(e);
1848     } finally {
1849       if (!exceptions.isEmpty()) {
1850         // Just throw the first exception as an indication something bad happened
1851         // Don't need to propagate all the exceptions, we already logged them all anyway
1852         Throwables.propagateIfInstanceOf(exceptions.firstElement(), IOException.class);
1853         throw Throwables.propagate(exceptions.firstElement());
1854       }
1855     }
1856 
1857     return finalResultMap;
1858   }
1859 
1860   public static int getRegionReferenceFileCount(final FileSystem fs, final Path p) {
1861     int result = 0;
1862     try {
1863       for (Path familyDir:getFamilyDirs(fs, p)){
1864         result += getReferenceFilePaths(fs, familyDir).size();
1865       }
1866     } catch (IOException e) {
1867       LOG.warn("Error Counting reference files.", e);
1868     }
1869     return result;
1870   }
1871 
1872   /**
1873    * Runs through the HBase rootdir and creates a reverse lookup map for
1874    * table StoreFile names to the full Path.
1875    * <br>
1876    * Example...<br>
1877    * Key = 3944417774205889744  <br>
1878    * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744
1879    *
1880    * @param fs  The file system to use.
1881    * @param hbaseRootDir  The root directory to scan.
1882    * @return Map keyed by StoreFile name with a value of the full Path.
1883    * @throws IOException When scanning the directory fails.
1884    * @throws InterruptedException
1885    */
1886   public static Map<String, Path> getTableStoreFilePathMap(
1887     final FileSystem fs, final Path hbaseRootDir)
1888   throws IOException, InterruptedException {
1889     return getTableStoreFilePathMap(fs, hbaseRootDir, null, null, null);
1890   }
1891 
1892   /**
1893    * Runs through the HBase rootdir and creates a reverse lookup map for
1894    * table StoreFile names to the full Path.
1895    * <br>
1896    * Example...<br>
1897    * Key = 3944417774205889744  <br>
1898    * Value = hdfs://localhost:51169/user/userid/-ROOT-/70236052/info/3944417774205889744
1899    *
1900    * @param fs  The file system to use.
1901    * @param hbaseRootDir  The root directory to scan.
1902    * @param sfFilter optional path filter to apply to store files
1903    * @param executor optional executor service to parallelize this operation
1904    * @param errors ErrorReporter instance or null
1905    * @return Map keyed by StoreFile name with a value of the full Path.
1906    * @throws IOException When scanning the directory fails.
1907    * @throws InterruptedException
1908    */
1909   public static Map<String, Path> getTableStoreFilePathMap(
1910     final FileSystem fs, final Path hbaseRootDir, PathFilter sfFilter,
1911     ExecutorService executor, ErrorReporter errors)
1912   throws IOException, InterruptedException {
1913     ConcurrentHashMap<String, Path> map = new ConcurrentHashMap<String, Path>(1024, 0.75f, 32);
1914 
1915     // if this method looks similar to 'getTableFragmentation' that is because
1916     // it was borrowed from it.
1917 
1918     // only include the directory paths to tables
1919     for (Path tableDir : FSUtils.getTableDirs(fs, hbaseRootDir)) {
1920       getTableStoreFilePathMap(map, fs, hbaseRootDir,
1921           FSUtils.getTableName(tableDir), sfFilter, executor, errors);
1922     }
1923     return map;
1924   }
1925 
1926   /**
1927    * Filters FileStatuses in an array and returns a list
1928    *
1929    * @param input   An array of FileStatuses
1930    * @param filter  A required filter to filter the array
1931    * @return        A list of FileStatuses
1932    */
1933   public static List<FileStatus> filterFileStatuses(FileStatus[] input,
1934       FileStatusFilter filter) {
1935     if (input == null) return null;
1936     return filterFileStatuses(Iterators.forArray(input), filter);
1937   }
1938 
1939   /**
1940    * Filters FileStatuses in an iterator and returns a list
1941    *
1942    * @param input   An iterator of FileStatuses
1943    * @param filter  A required filter to filter the array
1944    * @return        A list of FileStatuses
1945    */
1946   public static List<FileStatus> filterFileStatuses(Iterator<FileStatus> input,
1947       FileStatusFilter filter) {
1948     if (input == null) return null;
1949     ArrayList<FileStatus> results = new ArrayList<FileStatus>();
1950     while (input.hasNext()) {
1951       FileStatus f = input.next();
1952       if (filter.accept(f)) {
1953         results.add(f);
1954       }
1955     }
1956     return results;
1957   }
1958 
1959   /**
1960    * Calls fs.listStatus() and treats FileNotFoundException as non-fatal
1961    * This accommodates differences between hadoop versions, where hadoop 1
1962    * does not throw a FileNotFoundException, and return an empty FileStatus[]
1963    * while Hadoop 2 will throw FileNotFoundException.
1964    *
1965    * @param fs file system
1966    * @param dir directory
1967    * @param filter file status filter
1968    * @return null if dir is empty or doesn't exist, otherwise FileStatus list
1969    */
1970   public static List<FileStatus> listStatusWithStatusFilter(final FileSystem fs,
1971       final Path dir, final FileStatusFilter filter) throws IOException {
1972     FileStatus [] status = null;
1973     try {
1974       status = fs.listStatus(dir);
1975     } catch (FileNotFoundException fnfe) {
1976       // if directory doesn't exist, return null
1977       if (LOG.isTraceEnabled()) {
1978         LOG.trace(dir + " doesn't exist");
1979       }
1980     }
1981 
1982     if (status == null || status.length < 1)  {
1983       return null;
1984     }
1985 
1986     if (filter == null) {
1987       return Arrays.asList(status);
1988     } else {
1989       List<FileStatus> status2 = filterFileStatuses(status, filter);
1990       if (status2 == null || status2.isEmpty()) {
1991         return null;
1992       } else {
1993         return status2;
1994       }
1995     }
1996   }
1997 
1998   /**
1999    * Calls fs.listStatus() and treats FileNotFoundException as non-fatal
2000    * This accommodates differences between hadoop versions, where hadoop 1
2001    * does not throw a FileNotFoundException, and return an empty FileStatus[]
2002    * while Hadoop 2 will throw FileNotFoundException.
2003    *
2004    * Where possible, prefer {@link #listStatusWithStatusFilter(FileSystem,
2005    * Path, FileStatusFilter)} instead.
2006    *
2007    * @param fs file system
2008    * @param dir directory
2009    * @param filter path filter
2010    * @return null if dir is empty or doesn't exist, otherwise FileStatus array
2011    */
2012   public static FileStatus [] listStatus(final FileSystem fs,
2013       final Path dir, final PathFilter filter) throws IOException {
2014     FileStatus [] status = null;
2015     try {
2016       status = filter == null ? fs.listStatus(dir) : fs.listStatus(dir, filter);
2017     } catch (FileNotFoundException fnfe) {
2018       // if directory doesn't exist, return null
2019       if (LOG.isTraceEnabled()) {
2020         LOG.trace(dir + " doesn't exist");
2021       }
2022     }
2023     if (status == null || status.length < 1) return null;
2024     return status;
2025   }
2026 
2027   /**
2028    * Calls fs.listStatus() and treats FileNotFoundException as non-fatal
2029    * This would accommodates differences between hadoop versions
2030    *
2031    * @param fs file system
2032    * @param dir directory
2033    * @return null if dir is empty or doesn't exist, otherwise FileStatus array
2034    */
2035   public static FileStatus[] listStatus(final FileSystem fs, final Path dir) throws IOException {
2036     return listStatus(fs, dir, null);
2037   }
2038 
2039   /**
2040    * Calls fs.listFiles() to get FileStatus and BlockLocations together for reducing rpc call
2041    *
2042    * @param fs file system
2043    * @param dir directory
2044    * @return LocatedFileStatus list
2045    */
2046   public static List<LocatedFileStatus> listLocatedStatus(final FileSystem fs,
2047       final Path dir) throws IOException {
2048     List<LocatedFileStatus> status = null;
2049     try {
2050       RemoteIterator<LocatedFileStatus> locatedFileStatusRemoteIterator = fs
2051           .listFiles(dir, false);
2052       while (locatedFileStatusRemoteIterator.hasNext()) {
2053         if (status == null) {
2054           status = Lists.newArrayList();
2055         }
2056         status.add(locatedFileStatusRemoteIterator.next());
2057       }
2058     } catch (FileNotFoundException fnfe) {
2059       // if directory doesn't exist, return null
2060       if (LOG.isTraceEnabled()) {
2061         LOG.trace(dir + " doesn't exist");
2062       }
2063     }
2064     return status;
2065   }
2066 
2067   /**
2068    * Calls fs.delete() and returns the value returned by the fs.delete()
2069    *
2070    * @param fs
2071    * @param path
2072    * @param recursive
2073    * @return the value returned by the fs.delete()
2074    * @throws IOException
2075    */
2076   public static boolean delete(final FileSystem fs, final Path path, final boolean recursive)
2077       throws IOException {
2078     return fs.delete(path, recursive);
2079   }
2080 
2081   /**
2082    * Calls fs.exists(). Checks if the specified path exists
2083    *
2084    * @param fs
2085    * @param path
2086    * @return the value returned by fs.exists()
2087    * @throws IOException
2088    */
2089   public static boolean isExists(final FileSystem fs, final Path path) throws IOException {
2090     return fs.exists(path);
2091   }
2092 
2093   /**
2094    * Throw an exception if an action is not permitted by a user on a file.
2095    *
2096    * @param ugi
2097    *          the user
2098    * @param file
2099    *          the file
2100    * @param action
2101    *          the action
2102    */
2103   public static void checkAccess(UserGroupInformation ugi, FileStatus file,
2104       FsAction action) throws AccessDeniedException {
2105     if (ugi.getShortUserName().equals(file.getOwner())) {
2106       if (file.getPermission().getUserAction().implies(action)) {
2107         return;
2108       }
2109     } else if (contains(ugi.getGroupNames(), file.getGroup())) {
2110       if (file.getPermission().getGroupAction().implies(action)) {
2111         return;
2112       }
2113     } else if (file.getPermission().getOtherAction().implies(action)) {
2114       return;
2115     }
2116     throw new AccessDeniedException("Permission denied:" + " action=" + action
2117         + " path=" + file.getPath() + " user=" + ugi.getShortUserName());
2118   }
2119 
2120   private static boolean contains(String[] groups, String user) {
2121     for (String group : groups) {
2122       if (group.equals(user)) {
2123         return true;
2124       }
2125     }
2126     return false;
2127   }
2128 
2129   /**
2130    * Log the current state of the filesystem from a certain root directory
2131    * @param fs filesystem to investigate
2132    * @param root root file/directory to start logging from
2133    * @param LOG log to output information
2134    * @throws IOException if an unexpected exception occurs
2135    */
2136   public static void logFileSystemState(final FileSystem fs, final Path root, Log LOG)
2137       throws IOException {
2138     LOG.debug("Current file system:");
2139     logFSTree(LOG, fs, root, "|-");
2140   }
2141 
2142   /**
2143    * Recursive helper to log the state of the FS
2144    *
2145    * @see #logFileSystemState(FileSystem, Path, Log)
2146    */
2147   private static void logFSTree(Log LOG, final FileSystem fs, final Path root, String prefix)
2148       throws IOException {
2149     FileStatus[] files = FSUtils.listStatus(fs, root, null);
2150     if (files == null) return;
2151 
2152     for (FileStatus file : files) {
2153       if (file.isDirectory()) {
2154         LOG.debug(prefix + file.getPath().getName() + "/");
2155         logFSTree(LOG, fs, file.getPath(), prefix + "---");
2156       } else {
2157         LOG.debug(prefix + file.getPath().getName());
2158       }
2159     }
2160   }
2161 
2162   public static boolean renameAndSetModifyTime(final FileSystem fs, final Path src, final Path dest)
2163       throws IOException {
2164     // set the modify time for TimeToLive Cleaner
2165     fs.setTimes(src, EnvironmentEdgeManager.currentTime(), -1);
2166     return fs.rename(src, dest);
2167   }
2168 
2169   /**
2170    * This function is to scan the root path of the file system to get the
2171    * degree of locality for each region on each of the servers having at least
2172    * one block of that region.
2173    * This is used by the tool {@link org.apache.hadoop.hbase.master.RegionPlacementMaintainer}
2174    *
2175    * @param conf
2176    *          the configuration to use
2177    * @return the mapping from region encoded name to a map of server names to
2178    *           locality fraction
2179    * @throws IOException
2180    *           in case of file system errors or interrupts
2181    */
2182   public static Map<String, Map<String, Float>> getRegionDegreeLocalityMappingFromFS(
2183       final Configuration conf) throws IOException {
2184     return getRegionDegreeLocalityMappingFromFS(
2185         conf, null,
2186         conf.getInt(THREAD_POOLSIZE, DEFAULT_THREAD_POOLSIZE));
2187 
2188   }
2189 
2190   /**
2191    * This function is to scan the root path of the file system to get the
2192    * degree of locality for each region on each of the servers having at least
2193    * one block of that region.
2194    *
2195    * @param conf
2196    *          the configuration to use
2197    * @param desiredTable
2198    *          the table you wish to scan locality for
2199    * @param threadPoolSize
2200    *          the thread pool size to use
2201    * @return the mapping from region encoded name to a map of server names to
2202    *           locality fraction
2203    * @throws IOException
2204    *           in case of file system errors or interrupts
2205    */
2206   public static Map<String, Map<String, Float>> getRegionDegreeLocalityMappingFromFS(
2207       final Configuration conf, final String desiredTable, int threadPoolSize)
2208       throws IOException {
2209     Map<String, Map<String, Float>> regionDegreeLocalityMapping =
2210         new ConcurrentHashMap<String, Map<String, Float>>();
2211     getRegionLocalityMappingFromFS(conf, desiredTable, threadPoolSize, null,
2212         regionDegreeLocalityMapping);
2213     return regionDegreeLocalityMapping;
2214   }
2215 
2216   /**
2217    * This function is to scan the root path of the file system to get either the
2218    * mapping between the region name and its best locality region server or the
2219    * degree of locality of each region on each of the servers having at least
2220    * one block of that region. The output map parameters are both optional.
2221    *
2222    * @param conf
2223    *          the configuration to use
2224    * @param desiredTable
2225    *          the table you wish to scan locality for
2226    * @param threadPoolSize
2227    *          the thread pool size to use
2228    * @param regionToBestLocalityRSMapping
2229    *          the map into which to put the best locality mapping or null
2230    * @param regionDegreeLocalityMapping
2231    *          the map into which to put the locality degree mapping or null,
2232    *          must be a thread-safe implementation
2233    * @throws IOException
2234    *           in case of file system errors or interrupts
2235    */
2236   private static void getRegionLocalityMappingFromFS(
2237       final Configuration conf, final String desiredTable,
2238       int threadPoolSize,
2239       Map<String, String> regionToBestLocalityRSMapping,
2240       Map<String, Map<String, Float>> regionDegreeLocalityMapping)
2241       throws IOException {
2242     FileSystem fs =  FileSystem.get(conf);
2243     Path rootPath = FSUtils.getRootDir(conf);
2244     long startTime = EnvironmentEdgeManager.currentTime();
2245     Path queryPath;
2246     // The table files are in ${hbase.rootdir}/data/<namespace>/<table>/*
2247     if (null == desiredTable) {
2248       queryPath = new Path(new Path(rootPath, HConstants.BASE_NAMESPACE_DIR).toString() + "/*/*/*/");
2249     } else {
2250       queryPath = new Path(FSUtils.getTableDir(rootPath, TableName.valueOf(desiredTable)).toString() + "/*/");
2251     }
2252 
2253     // reject all paths that are not appropriate
2254     PathFilter pathFilter = new PathFilter() {
2255       @Override
2256       public boolean accept(Path path) {
2257         // this is the region name; it may get some noise data
2258         if (null == path) {
2259           return false;
2260         }
2261 
2262         // no parent?
2263         Path parent = path.getParent();
2264         if (null == parent) {
2265           return false;
2266         }
2267 
2268         String regionName = path.getName();
2269         if (null == regionName) {
2270           return false;
2271         }
2272 
2273         if (!regionName.toLowerCase(Locale.ROOT).matches("[0-9a-f]+")) {
2274           return false;
2275         }
2276         return true;
2277       }
2278     };
2279 
2280     FileStatus[] statusList = fs.globStatus(queryPath, pathFilter);
2281 
2282     if (null == statusList) {
2283       return;
2284     } else {
2285       LOG.debug("Query Path: " + queryPath + " ; # list of files: " +
2286           statusList.length);
2287     }
2288 
2289     // lower the number of threads in case we have very few expected regions
2290     threadPoolSize = Math.min(threadPoolSize, statusList.length);
2291 
2292     // run in multiple threads
2293     ThreadPoolExecutor tpe = new ThreadPoolExecutor(threadPoolSize,
2294         threadPoolSize, 60, TimeUnit.SECONDS,
2295         new ArrayBlockingQueue<Runnable>(statusList.length));
2296     try {
2297       // ignore all file status items that are not of interest
2298       for (FileStatus regionStatus : statusList) {
2299         if (null == regionStatus) {
2300           continue;
2301         }
2302 
2303         if (!regionStatus.isDirectory()) {
2304           continue;
2305         }
2306 
2307         Path regionPath = regionStatus.getPath();
2308         if (null == regionPath) {
2309           continue;
2310         }
2311 
2312         tpe.execute(new FSRegionScanner(fs, regionPath,
2313             regionToBestLocalityRSMapping, regionDegreeLocalityMapping));
2314       }
2315     } finally {
2316       tpe.shutdown();
2317       int threadWakeFrequency = conf.getInt(HConstants.THREAD_WAKE_FREQUENCY,
2318           60 * 1000);
2319       try {
2320         // here we wait until TPE terminates, which is either naturally or by
2321         // exceptions in the execution of the threads
2322         while (!tpe.awaitTermination(threadWakeFrequency,
2323             TimeUnit.MILLISECONDS)) {
2324           // printing out rough estimate, so as to not introduce
2325           // AtomicInteger
2326           LOG.info("Locality checking is underway: { Scanned Regions : "
2327               + tpe.getCompletedTaskCount() + "/"
2328               + tpe.getTaskCount() + " }");
2329         }
2330       } catch (InterruptedException e) {
2331         throw (InterruptedIOException)new InterruptedIOException().initCause(e);
2332       }
2333     }
2334 
2335     long overhead = EnvironmentEdgeManager.currentTime() - startTime;
2336     String overheadMsg = "Scan DFS for locality info takes " + overhead + " ms";
2337 
2338     LOG.info(overheadMsg);
2339   }
2340 
2341   /**
2342    * Do our short circuit read setup.
2343    * Checks buffer size to use and whether to do checksumming in hbase or hdfs.
2344    * @param conf
2345    */
2346   public static void setupShortCircuitRead(final Configuration conf) {
2347     // Check that the user has not set the "dfs.client.read.shortcircuit.skip.checksum" property.
2348     boolean shortCircuitSkipChecksum =
2349       conf.getBoolean("dfs.client.read.shortcircuit.skip.checksum", false);
2350     boolean useHBaseChecksum = conf.getBoolean(HConstants.HBASE_CHECKSUM_VERIFICATION, true);
2351     if (shortCircuitSkipChecksum) {
2352       LOG.warn("Configuration \"dfs.client.read.shortcircuit.skip.checksum\" should not " +
2353         "be set to true." + (useHBaseChecksum ? " HBase checksum doesn't require " +
2354         "it, see https://issues.apache.org/jira/browse/HBASE-6868." : ""));
2355       assert !shortCircuitSkipChecksum; //this will fail if assertions are on
2356     }
2357     checkShortCircuitReadBufferSize(conf);
2358   }
2359 
2360   /**
2361    * Check if short circuit read buffer size is set and if not, set it to hbase value.
2362    * @param conf
2363    */
2364   public static void checkShortCircuitReadBufferSize(final Configuration conf) {
2365     final int defaultSize = HConstants.DEFAULT_BLOCKSIZE * 2;
2366     final int notSet = -1;
2367     // DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_KEY is only defined in h2
2368     final String dfsKey = "dfs.client.read.shortcircuit.buffer.size";
2369     int size = conf.getInt(dfsKey, notSet);
2370     // If a size is set, return -- we will use it.
2371     if (size != notSet) return;
2372     // But short circuit buffer size is normally not set.  Put in place the hbase wanted size.
2373     int hbaseSize = conf.getInt("hbase." + dfsKey, defaultSize);
2374     conf.setIfUnset(dfsKey, Integer.toString(hbaseSize));
2375   }
2376 }