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