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