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