View Javadoc

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