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