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  
20  package org.apache.hadoop.hbase.regionserver;
21  
22  import java.io.FileNotFoundException;
23  import java.io.IOException;
24  import java.io.InterruptedIOException;
25  import java.util.ArrayList;
26  import java.util.Collection;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.UUID;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.hadoop.classification.InterfaceAudience;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.fs.FSDataInputStream;
36  import org.apache.hadoop.fs.FSDataOutputStream;
37  import org.apache.hadoop.fs.FileStatus;
38  import org.apache.hadoop.fs.FileSystem;
39  import org.apache.hadoop.fs.FileUtil;
40  import org.apache.hadoop.fs.Path;
41  import org.apache.hadoop.fs.PathFilter;
42  import org.apache.hadoop.fs.permission.FsPermission;
43  import org.apache.hadoop.hbase.HColumnDescriptor;
44  import org.apache.hadoop.hbase.HConstants;
45  import org.apache.hadoop.hbase.HRegionInfo;
46  import org.apache.hadoop.hbase.HTableDescriptor;
47  import org.apache.hadoop.hbase.KeyValue;
48  import org.apache.hadoop.hbase.KeyValueUtil;
49  import org.apache.hadoop.hbase.backup.HFileArchiver;
50  import org.apache.hadoop.hbase.fs.HFileSystem;
51  import org.apache.hadoop.hbase.io.Reference;
52  import org.apache.hadoop.hbase.util.Bytes;
53  import org.apache.hadoop.hbase.util.FSHDFSUtils;
54  import org.apache.hadoop.hbase.util.FSUtils;
55  
56  /**
57   * View to an on-disk Region.
58   * Provides the set of methods necessary to interact with the on-disk region data.
59   */
60  @InterfaceAudience.Private
61  public class HRegionFileSystem {
62    public static final Log LOG = LogFactory.getLog(HRegionFileSystem.class);
63  
64    /** Name of the region info file that resides just under the region directory. */
65    public final static String REGION_INFO_FILE = ".regioninfo";
66  
67    /** Temporary subdirectory of the region directory used for merges. */
68    public static final String REGION_MERGES_DIR = ".merges";
69  
70    /** Temporary subdirectory of the region directory used for splits. */
71    public static final String REGION_SPLITS_DIR = ".splits";
72  
73    /** Temporary subdirectory of the region directory used for compaction output. */
74    private static final String REGION_TEMP_DIR = ".tmp";
75  
76    private final HRegionInfo regionInfo;
77    private final Configuration conf;
78    private final Path tableDir;
79    private final FileSystem fs;
80  
81    /**
82     * In order to handle NN connectivity hiccups, one need to retry non-idempotent operation at the
83     * client level.
84     */
85    private final int hdfsClientRetriesNumber;
86    private final int baseSleepBeforeRetries;
87    private static final int DEFAULT_HDFS_CLIENT_RETRIES_NUMBER = 10;
88    private static final int DEFAULT_BASE_SLEEP_BEFORE_RETRIES = 1000;
89  
90    /**
91     * Create a view to the on-disk region
92     * @param conf the {@link Configuration} to use
93     * @param fs {@link FileSystem} that contains the region
94     * @param tableDir {@link Path} to where the table is being stored
95     * @param regionInfo {@link HRegionInfo} for region
96     */
97    HRegionFileSystem(final Configuration conf, final FileSystem fs, final Path tableDir,
98        final HRegionInfo regionInfo) {
99      this.fs = fs;
100     this.conf = conf;
101     this.tableDir = tableDir;
102     this.regionInfo = regionInfo;
103     this.hdfsClientRetriesNumber = conf.getInt("hdfs.client.retries.number",
104       DEFAULT_HDFS_CLIENT_RETRIES_NUMBER);
105     this.baseSleepBeforeRetries = conf.getInt("hdfs.client.sleep.before.retries",
106       DEFAULT_BASE_SLEEP_BEFORE_RETRIES);
107  }
108 
109   /** @return the underlying {@link FileSystem} */
110   public FileSystem getFileSystem() {
111     return this.fs;
112   }
113 
114   /** @return the {@link HRegionInfo} that describe this on-disk region view */
115   public HRegionInfo getRegionInfo() {
116     return this.regionInfo;
117   }
118 
119   /** @return {@link Path} to the region's root directory. */
120   public Path getTableDir() {
121     return this.tableDir;
122   }
123 
124   /** @return {@link Path} to the region directory. */
125   public Path getRegionDir() {
126     return new Path(this.tableDir, this.regionInfo.getEncodedName());
127   }
128 
129   // ===========================================================================
130   //  Temp Helpers
131   // ===========================================================================
132   /** @return {@link Path} to the region's temp directory, used for file creations */
133   Path getTempDir() {
134     return new Path(getRegionDir(), REGION_TEMP_DIR);
135   }
136 
137   /**
138    * Clean up any temp detritus that may have been left around from previous operation attempts.
139    */
140   void cleanupTempDir() throws IOException {
141     deleteDir(getTempDir());
142   }
143 
144   // ===========================================================================
145   //  Store/StoreFile Helpers
146   // ===========================================================================
147   /**
148    * Returns the directory path of the specified family
149    * @param familyName Column Family Name
150    * @return {@link Path} to the directory of the specified family
151    */
152   public Path getStoreDir(final String familyName) {
153     return new Path(this.getRegionDir(), familyName);
154   }
155 
156   /**
157    * Create the store directory for the specified family name
158    * @param familyName Column Family Name
159    * @return {@link Path} to the directory of the specified family
160    * @throws IOException if the directory creation fails.
161    */
162   Path createStoreDir(final String familyName) throws IOException {
163     Path storeDir = getStoreDir(familyName);
164     if(!fs.exists(storeDir) && !createDir(storeDir))
165       throw new IOException("Failed creating "+storeDir);
166     return storeDir;
167   }
168 
169   /**
170    * Returns the store files available for the family.
171    * This methods performs the filtering based on the valid store files.
172    * @param familyName Column Family Name
173    * @return a set of {@link StoreFileInfo} for the specified family.
174    */
175   public Collection<StoreFileInfo> getStoreFiles(final byte[] familyName) throws IOException {
176     return getStoreFiles(Bytes.toString(familyName));
177   }
178 
179   public Collection<StoreFileInfo> getStoreFiles(final String familyName) throws IOException {
180     return getStoreFiles(familyName, true);
181   }
182 
183   /**
184    * Returns the store files available for the family.
185    * This methods performs the filtering based on the valid store files.
186    * @param familyName Column Family Name
187    * @return a set of {@link StoreFileInfo} for the specified family.
188    */
189   public Collection<StoreFileInfo> getStoreFiles(final String familyName, final boolean validate)
190       throws IOException {
191     Path familyDir = getStoreDir(familyName);
192     FileStatus[] files = FSUtils.listStatus(this.fs, familyDir);
193     if (files == null) {
194       LOG.debug("No StoreFiles for: " + familyDir);
195       return null;
196     }
197 
198     ArrayList<StoreFileInfo> storeFiles = new ArrayList<StoreFileInfo>(files.length);
199     for (FileStatus status: files) {
200       if (validate && !StoreFileInfo.isValid(status)) {
201         LOG.warn("Invalid StoreFile: " + status.getPath());
202         continue;
203       }
204 
205       storeFiles.add(new StoreFileInfo(this.conf, this.fs, status));
206     }
207     return storeFiles;
208   }
209 
210   /**
211    * Return Qualified Path of the specified family/file
212    *
213    * @param familyName Column Family Name
214    * @param fileName File Name
215    * @return The qualified Path for the specified family/file
216    */
217   Path getStoreFilePath(final String familyName, final String fileName) {
218     Path familyDir = getStoreDir(familyName);
219     return new Path(familyDir, fileName).makeQualified(this.fs);
220   }
221 
222   /**
223    * Return the store file information of the specified family/file.
224    *
225    * @param familyName Column Family Name
226    * @param fileName File Name
227    * @return The {@link StoreFileInfo} for the specified family/file
228    */
229   StoreFileInfo getStoreFileInfo(final String familyName, final String fileName)
230       throws IOException {
231     Path familyDir = getStoreDir(familyName);
232     FileStatus status = fs.getFileStatus(new Path(familyDir, fileName));
233     return new StoreFileInfo(this.conf, this.fs, status);
234   }
235 
236   /**
237    * Returns true if the specified family has reference files
238    * @param familyName Column Family Name
239    * @return true if family contains reference files
240    * @throws IOException
241    */
242   public boolean hasReferences(final String familyName) throws IOException {
243     FileStatus[] files = FSUtils.listStatus(fs, getStoreDir(familyName),
244       new PathFilter () {
245         public boolean accept(Path path) {
246           return StoreFileInfo.isReference(path);
247         }
248       }
249     );
250     return files != null && files.length > 0;
251   }
252 
253   /**
254    * Check whether region has Reference file
255    * @param htd table desciptor of the region
256    * @return true if region has reference file
257    * @throws IOException
258    */
259   public boolean hasReferences(final HTableDescriptor htd) throws IOException {
260     for (HColumnDescriptor family : htd.getFamilies()) {
261       if (hasReferences(family.getNameAsString())) {
262         return true;
263       }
264     }
265     return false;
266   }
267 
268   /**
269    * @return the set of families present on disk
270    * @throws IOException
271    */
272   public Collection<String> getFamilies() throws IOException {
273     FileStatus[] fds = FSUtils.listStatus(fs, getRegionDir(), new FSUtils.FamilyDirFilter(fs));
274     if (fds == null) return null;
275 
276     ArrayList<String> families = new ArrayList<String>(fds.length);
277     for (FileStatus status: fds) {
278       families.add(status.getPath().getName());
279     }
280 
281     return families;
282   }
283 
284   /**
285    * Remove the region family from disk, archiving the store files.
286    * @param familyName Column Family Name
287    * @throws IOException if an error occours during the archiving
288    */
289   public void deleteFamily(final String familyName) throws IOException {
290     // archive family store files
291     HFileArchiver.archiveFamily(fs, conf, regionInfo, tableDir, Bytes.toBytes(familyName));
292 
293     // delete the family folder
294     Path familyDir = getStoreDir(familyName);
295     if(fs.exists(familyDir) && !deleteDir(familyDir))
296       throw new IOException("Could not delete family " + familyName
297           + " from FileSystem for region " + regionInfo.getRegionNameAsString() + "("
298           + regionInfo.getEncodedName() + ")");
299   }
300 
301   /**
302    * Generate a unique file name, used by createTempName() and commitStoreFile()
303    * @param suffix extra information to append to the generated name
304    * @return Unique file name
305    */
306   private static String generateUniqueName(final String suffix) {
307     String name = UUID.randomUUID().toString().replaceAll("-", "");
308     if (suffix != null) name += suffix;
309     return name;
310   }
311 
312   /**
313    * Generate a unique temporary Path. Used in conjuction with commitStoreFile()
314    * to get a safer file creation.
315    * <code>
316    * Path file = fs.createTempName();
317    * ...StoreFile.Writer(file)...
318    * fs.commitStoreFile("family", file);
319    * </code>
320    *
321    * @return Unique {@link Path} of the temporary file
322    */
323   public Path createTempName() {
324     return createTempName(null);
325   }
326 
327   /**
328    * Generate a unique temporary Path. Used in conjuction with commitStoreFile()
329    * to get a safer file creation.
330    * <code>
331    * Path file = fs.createTempName();
332    * ...StoreFile.Writer(file)...
333    * fs.commitStoreFile("family", file);
334    * </code>
335    *
336    * @param suffix extra information to append to the generated name
337    * @return Unique {@link Path} of the temporary file
338    */
339   public Path createTempName(final String suffix) {
340     return new Path(getTempDir(), generateUniqueName(suffix));
341   }
342 
343   /**
344    * Move the file from a build/temp location to the main family store directory.
345    * @param familyName Family that will gain the file
346    * @param buildPath {@link Path} to the file to commit.
347    * @return The new {@link Path} of the committed file
348    * @throws IOException
349    */
350   public Path commitStoreFile(final String familyName, final Path buildPath) throws IOException {
351     return commitStoreFile(familyName, buildPath, -1, false);
352   }
353 
354   /**
355    * Move the file from a build/temp location to the main family store directory.
356    * @param familyName Family that will gain the file
357    * @param buildPath {@link Path} to the file to commit.
358    * @param seqNum Sequence Number to append to the file name (less then 0 if no sequence number)
359    * @param generateNewName False if you want to keep the buildPath name
360    * @return The new {@link Path} of the committed file
361    * @throws IOException
362    */
363   private Path commitStoreFile(final String familyName, final Path buildPath,
364       final long seqNum, final boolean generateNewName) throws IOException {
365     Path storeDir = getStoreDir(familyName);
366     if(!fs.exists(storeDir) && !createDir(storeDir))
367       throw new IOException("Failed creating " + storeDir);
368 
369     String name = buildPath.getName();
370     if (generateNewName) {
371       name = generateUniqueName((seqNum < 0) ? null : "_SeqId_" + seqNum + "_");
372     }
373     Path dstPath = new Path(storeDir, name);
374     if (!fs.exists(buildPath)) {
375       throw new FileNotFoundException(buildPath.toString());
376     }
377     LOG.debug("Committing store file " + buildPath + " as " + dstPath);
378     // buildPath exists, therefore not doing an exists() check.
379     if (!rename(buildPath, dstPath)) {
380       throw new IOException("Failed rename of " + buildPath + " to " + dstPath);
381     }
382     return dstPath;
383   }
384 
385 
386   /**
387    * Moves multiple store files to the relative region's family store directory.
388    * @param storeFiles list of store files divided by family
389    * @throws IOException
390    */
391   void commitStoreFiles(final Map<byte[], List<StoreFile>> storeFiles) throws IOException {
392     for (Map.Entry<byte[], List<StoreFile>> es: storeFiles.entrySet()) {
393       String familyName = Bytes.toString(es.getKey());
394       for (StoreFile sf: es.getValue()) {
395         commitStoreFile(familyName, sf.getPath());
396       }
397     }
398   }
399 
400   /**
401    * Archives the specified store file from the specified family.
402    * @param familyName Family that contains the store files
403    * @param filePath {@link Path} to the store file to remove
404    * @throws IOException if the archiving fails
405    */
406   public void removeStoreFile(final String familyName, final Path filePath)
407       throws IOException {
408     HFileArchiver.archiveStoreFile(this.conf, this.fs, this.regionInfo,
409         this.tableDir, Bytes.toBytes(familyName), filePath);
410   }
411 
412   /**
413    * Closes and archives the specified store files from the specified family.
414    * @param familyName Family that contains the store files
415    * @param storeFiles set of store files to remove
416    * @throws IOException if the archiving fails
417    */
418   public void removeStoreFiles(final String familyName, final Collection<StoreFile> storeFiles)
419       throws IOException {
420     HFileArchiver.archiveStoreFiles(this.conf, this.fs, this.regionInfo,
421         this.tableDir, Bytes.toBytes(familyName), storeFiles);
422   }
423 
424   /**
425    * Bulk load: Add a specified store file to the specified family.
426    * If the source file is on the same different file-system is moved from the
427    * source location to the destination location, otherwise is copied over.
428    *
429    * @param familyName Family that will gain the file
430    * @param srcPath {@link Path} to the file to import
431    * @param seqNum Bulk Load sequence number
432    * @return The destination {@link Path} of the bulk loaded file
433    * @throws IOException
434    */
435   Path bulkLoadStoreFile(final String familyName, Path srcPath, long seqNum)
436       throws IOException {
437     // Copy the file if it's on another filesystem
438     FileSystem srcFs = srcPath.getFileSystem(conf);
439     FileSystem desFs = fs instanceof HFileSystem ? ((HFileSystem)fs).getBackingFs() : fs;
440 
441     // We can't compare FileSystem instances as equals() includes UGI instance
442     // as part of the comparison and won't work when doing SecureBulkLoad
443     // TODO deal with viewFS
444     if (!FSHDFSUtils.isSameHdfs(conf, srcFs, desFs)) {
445       LOG.info("Bulk-load file " + srcPath + " is on different filesystem than " +
446           "the destination store. Copying file over to destination filesystem.");
447       Path tmpPath = createTempName();
448       FileUtil.copy(srcFs, srcPath, fs, tmpPath, false, conf);
449       LOG.info("Copied " + srcPath + " to temporary path on destination filesystem: " + tmpPath);
450       srcPath = tmpPath;
451     }
452 
453     return commitStoreFile(familyName, srcPath, seqNum, true);
454   }
455 
456   // ===========================================================================
457   //  Splits Helpers
458   // ===========================================================================
459   /** @return {@link Path} to the temp directory used during split operations */
460   Path getSplitsDir() {
461     return new Path(getRegionDir(), REGION_SPLITS_DIR);
462   }
463 
464   Path getSplitsDir(final HRegionInfo hri) {
465     return new Path(getSplitsDir(), hri.getEncodedName());
466   }
467 
468   /**
469    * Clean up any split detritus that may have been left around from previous split attempts.
470    */
471   void cleanupSplitsDir() throws IOException {
472     deleteDir(getSplitsDir());
473   }
474 
475   /**
476    * Clean up any split detritus that may have been left around from previous
477    * split attempts.
478    * Call this method on initial region deploy.
479    * @throws IOException
480    */
481   void cleanupAnySplitDetritus() throws IOException {
482     Path splitdir = this.getSplitsDir();
483     if (!fs.exists(splitdir)) return;
484     // Look at the splitdir.  It could have the encoded names of the daughter
485     // regions we tried to make.  See if the daughter regions actually got made
486     // out under the tabledir.  If here under splitdir still, then the split did
487     // not complete.  Try and do cleanup.  This code WILL NOT catch the case
488     // where we successfully created daughter a but regionserver crashed during
489     // the creation of region b.  In this case, there'll be an orphan daughter
490     // dir in the filesystem.  TOOD: Fix.
491     FileStatus[] daughters = FSUtils.listStatus(fs, splitdir, new FSUtils.DirFilter(fs));
492     if (daughters != null) {
493       for (FileStatus daughter: daughters) {
494         Path daughterDir = new Path(getTableDir(), daughter.getPath().getName());
495         if (fs.exists(daughterDir) && !deleteDir(daughterDir)) {
496           throw new IOException("Failed delete of " + daughterDir);
497         }
498       }
499     }
500     cleanupSplitsDir();
501     LOG.info("Cleaned up old failed split transaction detritus: " + splitdir);
502   }
503 
504   /**
505    * Remove daughter region
506    * @param regionInfo daughter {@link HRegionInfo}
507    * @throws IOException
508    */
509   void cleanupDaughterRegion(final HRegionInfo regionInfo) throws IOException {
510     Path regionDir = new Path(this.tableDir, regionInfo.getEncodedName());
511     if (this.fs.exists(regionDir) && !deleteDir(regionDir)) {
512       throw new IOException("Failed delete of " + regionDir);
513     }
514   }
515 
516   /**
517    * Commit a daughter region, moving it from the split temporary directory
518    * to the proper location in the filesystem.
519    * @param regionInfo daughter {@link HRegionInfo}
520    * @throws IOException
521    */
522   Path commitDaughterRegion(final HRegionInfo regionInfo) throws IOException {
523     Path regionDir = new Path(this.tableDir, regionInfo.getEncodedName());
524     Path daughterTmpDir = this.getSplitsDir(regionInfo);
525     if (fs.exists(daughterTmpDir)) {
526       // Write HRI to a file in case we need to recover hbase:meta
527       Path regionInfoFile = new Path(daughterTmpDir, REGION_INFO_FILE);
528       byte[] regionInfoContent = getRegionInfoFileContent(regionInfo);
529       writeRegionInfoFileContent(conf, fs, regionInfoFile, regionInfoContent);
530 
531       // Move the daughter temp dir to the table dir
532       if (!rename(daughterTmpDir, regionDir)) {
533         throw new IOException("Unable to rename " + daughterTmpDir + " to " + regionDir);
534       }
535     }
536     return regionDir;
537   }
538 
539   /**
540    * Create the region splits directory.
541    */
542   void createSplitsDir() throws IOException {
543     Path splitdir = getSplitsDir();
544     if (fs.exists(splitdir)) {
545       LOG.info("The " + splitdir + " directory exists.  Hence deleting it to recreate it");
546       if (!deleteDir(splitdir)) {
547         throw new IOException("Failed deletion of " + splitdir
548             + " before creating them again.");
549       }
550     }
551     // splitDir doesn't exists now. No need to do an exists() call for it.
552     if (!createDir(splitdir)) {
553       throw new IOException("Failed create of " + splitdir);
554     }
555   }
556 
557   /**
558    * Write out a split reference. Package local so it doesnt leak out of
559    * regionserver.
560    * @param hri {@link HRegionInfo} of the destination
561    * @param familyName Column Family Name
562    * @param f File to split.
563    * @param splitRow Split Row
564    * @param top True if we are referring to the top half of the hfile.
565    * @return Path to created reference.
566    * @throws IOException
567    */
568   Path splitStoreFile(final HRegionInfo hri, final String familyName,
569       final StoreFile f, final byte[] splitRow, final boolean top) throws IOException {
570 
571     // Check whether the split row lies in the range of the store file
572     // If it is outside the range, return directly.
573     if (top) {
574       //check if larger than last key.
575       KeyValue splitKey = KeyValueUtil.createFirstOnRow(splitRow);
576       byte[] lastKey = f.createReader().getLastKey();
577       // If lastKey is null means storefile is empty.
578       if (lastKey == null) return null;
579       if (f.getReader().getComparator().compareFlatKey(splitKey.getBuffer(),
580           splitKey.getKeyOffset(), splitKey.getKeyLength(), lastKey, 0, lastKey.length) > 0) {
581         return null;
582       }
583     } else {
584       //check if smaller than first key
585       KeyValue splitKey = KeyValueUtil.createLastOnRow(splitRow);
586       byte[] firstKey = f.createReader().getFirstKey();
587       // If firstKey is null means storefile is empty.
588       if (firstKey == null) return null;
589       if (f.getReader().getComparator().compareFlatKey(splitKey.getBuffer(),
590           splitKey.getKeyOffset(), splitKey.getKeyLength(), firstKey, 0, firstKey.length) < 0) {
591         return null;
592       }
593     }
594 
595     f.getReader().close(true);
596 
597     Path splitDir = new Path(getSplitsDir(hri), familyName);
598     // A reference to the bottom half of the hsf store file.
599     Reference r =
600       top ? Reference.createTopReference(splitRow): Reference.createBottomReference(splitRow);
601     // Add the referred-to regions name as a dot separated suffix.
602     // See REF_NAME_REGEX regex above.  The referred-to regions name is
603     // up in the path of the passed in <code>f</code> -- parentdir is family,
604     // then the directory above is the region name.
605     String parentRegionName = regionInfo.getEncodedName();
606     // Write reference with same file id only with the other region name as
607     // suffix and into the new region location (under same family).
608     Path p = new Path(splitDir, f.getPath().getName() + "." + parentRegionName);
609     return r.write(fs, p);
610   }
611 
612   // ===========================================================================
613   //  Merge Helpers
614   // ===========================================================================
615   /** @return {@link Path} to the temp directory used during merge operations */
616   Path getMergesDir() {
617     return new Path(getRegionDir(), REGION_MERGES_DIR);
618   }
619 
620   Path getMergesDir(final HRegionInfo hri) {
621     return new Path(getMergesDir(), hri.getEncodedName());
622   }
623 
624   /**
625    * Clean up any merge detritus that may have been left around from previous merge attempts.
626    */
627   void cleanupMergesDir() throws IOException {
628     deleteDir(getMergesDir());
629   }
630 
631   /**
632    * Remove merged region
633    * @param mergedRegion {@link HRegionInfo}
634    * @throws IOException
635    */
636   void cleanupMergedRegion(final HRegionInfo mergedRegion) throws IOException {
637     Path regionDir = new Path(this.tableDir, mergedRegion.getEncodedName());
638     if (this.fs.exists(regionDir) && !this.fs.delete(regionDir, true)) {
639       throw new IOException("Failed delete of " + regionDir);
640     }
641   }
642 
643   /**
644    * Create the region merges directory.
645    * @throws IOException If merges dir already exists or we fail to create it.
646    * @see HRegionFileSystem#cleanupMergesDir()
647    */
648   void createMergesDir() throws IOException {
649     Path mergesdir = getMergesDir();
650     if (fs.exists(mergesdir)) {
651       LOG.info("The " + mergesdir
652           + " directory exists.  Hence deleting it to recreate it");
653       if (!fs.delete(mergesdir, true)) {
654         throw new IOException("Failed deletion of " + mergesdir
655             + " before creating them again.");
656       }
657     }
658     if (!fs.mkdirs(mergesdir))
659       throw new IOException("Failed create of " + mergesdir);
660   }
661 
662   /**
663    * Write out a merge reference under the given merges directory. Package local
664    * so it doesnt leak out of regionserver.
665    * @param mergedRegion {@link HRegionInfo} of the merged region
666    * @param familyName Column Family Name
667    * @param f File to create reference.
668    * @param mergedDir
669    * @return Path to created reference.
670    * @throws IOException
671    */
672   Path mergeStoreFile(final HRegionInfo mergedRegion, final String familyName,
673       final StoreFile f, final Path mergedDir)
674       throws IOException {
675     Path referenceDir = new Path(new Path(mergedDir,
676         mergedRegion.getEncodedName()), familyName);
677     // A whole reference to the store file.
678     Reference r = Reference.createTopReference(regionInfo.getStartKey());
679     // Add the referred-to regions name as a dot separated suffix.
680     // See REF_NAME_REGEX regex above. The referred-to regions name is
681     // up in the path of the passed in <code>f</code> -- parentdir is family,
682     // then the directory above is the region name.
683     String mergingRegionName = regionInfo.getEncodedName();
684     // Write reference with same file id only with the other region name as
685     // suffix and into the new region location (under same family).
686     Path p = new Path(referenceDir, f.getPath().getName() + "."
687         + mergingRegionName);
688     return r.write(fs, p);
689   }
690 
691   /**
692    * Commit a merged region, moving it from the merges temporary directory to
693    * the proper location in the filesystem.
694    * @param mergedRegionInfo merged region {@link HRegionInfo}
695    * @throws IOException
696    */
697   void commitMergedRegion(final HRegionInfo mergedRegionInfo) throws IOException {
698     Path regionDir = new Path(this.tableDir, mergedRegionInfo.getEncodedName());
699     Path mergedRegionTmpDir = this.getMergesDir(mergedRegionInfo);
700     // Move the tmp dir in the expected location
701     if (mergedRegionTmpDir != null && fs.exists(mergedRegionTmpDir)) {
702       if (!fs.rename(mergedRegionTmpDir, regionDir)) {
703         throw new IOException("Unable to rename " + mergedRegionTmpDir + " to "
704             + regionDir);
705       }
706     }
707   }
708 
709   // ===========================================================================
710   //  Create/Open/Delete Helpers
711   // ===========================================================================
712   /**
713    * Log the current state of the region
714    * @param LOG log to output information
715    * @throws IOException if an unexpected exception occurs
716    */
717   void logFileSystemState(final Log LOG) throws IOException {
718     FSUtils.logFileSystemState(fs, this.getRegionDir(), LOG);
719   }
720 
721   /**
722    * @param hri
723    * @return Content of the file we write out to the filesystem under a region
724    * @throws IOException
725    */
726   private static byte[] getRegionInfoFileContent(final HRegionInfo hri) throws IOException {
727     return hri.toDelimitedByteArray();
728   }
729 
730   /**
731    * Create a {@link HRegionInfo} from the serialized version on-disk.
732    * @param fs {@link FileSystem} that contains the Region Info file
733    * @param regionDir {@link Path} to the Region Directory that contains the Info file
734    * @return An {@link HRegionInfo} instance gotten from the Region Info file.
735    * @throws IOException if an error occurred during file open/read operation.
736    */
737   public static HRegionInfo loadRegionInfoFileContent(final FileSystem fs, final Path regionDir)
738       throws IOException {
739     FSDataInputStream in = fs.open(new Path(regionDir, REGION_INFO_FILE));
740     try {
741       return HRegionInfo.parseFrom(in);
742     } finally {
743       in.close();
744     }
745   }
746 
747   /**
748    * Write the .regioninfo file on-disk.
749    */
750   private static void writeRegionInfoFileContent(final Configuration conf, final FileSystem fs,
751       final Path regionInfoFile, final byte[] content) throws IOException {
752     // First check to get the permissions
753     FsPermission perms = FSUtils.getFilePermissions(fs, conf, HConstants.DATA_FILE_UMASK_KEY);
754     // Write the RegionInfo file content
755     FSDataOutputStream out = FSUtils.create(fs, regionInfoFile, perms, null);
756     try {
757       out.write(content);
758     } finally {
759       out.close();
760     }
761   }
762 
763   /**
764    * Write out an info file under the stored region directory. Useful recovering mangled regions.
765    * If the regionInfo already exists on-disk, then we fast exit.
766    */
767   void checkRegionInfoOnFilesystem() throws IOException {
768     // Compose the content of the file so we can compare to length in filesystem. If not same,
769     // rewrite it (it may have been written in the old format using Writables instead of pb). The
770     // pb version is much shorter -- we write now w/o the toString version -- so checking length
771     // only should be sufficient. I don't want to read the file every time to check if it pb
772     // serialized.
773     byte[] content = getRegionInfoFileContent(regionInfo);
774     try {
775       Path regionInfoFile = new Path(getRegionDir(), REGION_INFO_FILE);
776 
777       FileStatus status = fs.getFileStatus(regionInfoFile);
778       if (status != null && status.getLen() == content.length) {
779         // Then assume the content good and move on.
780         // NOTE: that the length is not sufficient to define the the content matches.
781         return;
782       }
783 
784       LOG.info("Rewriting .regioninfo file at: " + regionInfoFile);
785       if (!fs.delete(regionInfoFile, false)) {
786         throw new IOException("Unable to remove existing " + regionInfoFile);
787       }
788     } catch (FileNotFoundException e) {
789       LOG.warn(REGION_INFO_FILE + " file not found for region: " + regionInfo.getEncodedName() +
790           " on table " + regionInfo.getTable());
791     }
792 
793     // Write HRI to a file in case we need to recover hbase:meta
794     writeRegionInfoOnFilesystem(content, true);
795   }
796 
797   /**
798    * Write out an info file under the region directory. Useful recovering mangled regions.
799    * @param useTempDir indicate whether or not using the region .tmp dir for a safer file creation.
800    */
801   private void writeRegionInfoOnFilesystem(boolean useTempDir) throws IOException {
802     byte[] content = getRegionInfoFileContent(regionInfo);
803     writeRegionInfoOnFilesystem(content, useTempDir);
804   }
805 
806   /**
807    * Write out an info file under the region directory. Useful recovering mangled regions.
808    * @param regionInfoContent serialized version of the {@link HRegionInfo}
809    * @param useTempDir indicate whether or not using the region .tmp dir for a safer file creation.
810    */
811   private void writeRegionInfoOnFilesystem(final byte[] regionInfoContent,
812       final boolean useTempDir) throws IOException {
813     Path regionInfoFile = new Path(getRegionDir(), REGION_INFO_FILE);
814     if (useTempDir) {
815       // Create in tmpDir and then move into place in case we crash after
816       // create but before close. If we don't successfully close the file,
817       // subsequent region reopens will fail the below because create is
818       // registered in NN.
819 
820       // And then create the file
821       Path tmpPath = new Path(getTempDir(), REGION_INFO_FILE);
822 
823       // If datanode crashes or if the RS goes down just before the close is called while trying to
824       // close the created regioninfo file in the .tmp directory then on next
825       // creation we will be getting AlreadyCreatedException.
826       // Hence delete and create the file if exists.
827       if (FSUtils.isExists(fs, tmpPath)) {
828         FSUtils.delete(fs, tmpPath, true);
829       }
830 
831       // Write HRI to a file in case we need to recover hbase:meta
832       writeRegionInfoFileContent(conf, fs, tmpPath, regionInfoContent);
833 
834       // Move the created file to the original path
835       if (fs.exists(tmpPath) &&  !rename(tmpPath, regionInfoFile)) {
836         throw new IOException("Unable to rename " + tmpPath + " to " + regionInfoFile);
837       }
838     } else {
839       // Write HRI to a file in case we need to recover hbase:meta
840       writeRegionInfoFileContent(conf, fs, regionInfoFile, regionInfoContent);
841     }
842   }
843 
844   /**
845    * Create a new Region on file-system.
846    * @param conf the {@link Configuration} to use
847    * @param fs {@link FileSystem} from which to add the region
848    * @param tableDir {@link Path} to where the table is being stored
849    * @param regionInfo {@link HRegionInfo} for region to be added
850    * @throws IOException if the region creation fails due to a FileSystem exception.
851    */
852   public static HRegionFileSystem createRegionOnFileSystem(final Configuration conf,
853       final FileSystem fs, final Path tableDir, final HRegionInfo regionInfo) throws IOException {
854     HRegionFileSystem regionFs = new HRegionFileSystem(conf, fs, tableDir, regionInfo);
855     Path regionDir = regionFs.getRegionDir();
856 
857     if (fs.exists(regionDir)) {
858       LOG.warn("Trying to create a region that already exists on disk: " + regionDir);
859       throw new IOException("The specified region already exists on disk: " + regionDir);
860     }
861 
862     // Create the region directory
863     if (!createDirOnFileSystem(fs, conf, regionDir)) {
864       LOG.warn("Unable to create the region directory: " + regionDir);
865       throw new IOException("Unable to create region directory: " + regionDir);
866     }
867 
868     // Write HRI to a file in case we need to recover hbase:meta
869     regionFs.writeRegionInfoOnFilesystem(false);
870     return regionFs;
871   }
872 
873   /**
874    * Open Region from file-system.
875    * @param conf the {@link Configuration} to use
876    * @param fs {@link FileSystem} from which to add the region
877    * @param tableDir {@link Path} to where the table is being stored
878    * @param regionInfo {@link HRegionInfo} for region to be added
879    * @param readOnly True if you don't want to edit the region data
880    * @throws IOException if the region creation fails due to a FileSystem exception.
881    */
882   public static HRegionFileSystem openRegionFromFileSystem(final Configuration conf,
883       final FileSystem fs, final Path tableDir, final HRegionInfo regionInfo, boolean readOnly)
884       throws IOException {
885     HRegionFileSystem regionFs = new HRegionFileSystem(conf, fs, tableDir, regionInfo);
886     Path regionDir = regionFs.getRegionDir();
887 
888     if (!fs.exists(regionDir)) {
889       LOG.warn("Trying to open a region that do not exists on disk: " + regionDir);
890       throw new IOException("The specified region do not exists on disk: " + regionDir);
891     }
892 
893     if (!readOnly) {
894       // Cleanup temporary directories
895       regionFs.cleanupTempDir();
896       regionFs.cleanupSplitsDir();
897       regionFs.cleanupMergesDir();
898 
899       // if it doesn't exists, Write HRI to a file, in case we need to recover hbase:meta
900       regionFs.checkRegionInfoOnFilesystem();
901     }
902 
903     return regionFs;
904   }
905 
906   /**
907    * Remove the region from the table directory, archiving the region's hfiles.
908    * @param conf the {@link Configuration} to use
909    * @param fs {@link FileSystem} from which to remove the region
910    * @param tableDir {@link Path} to where the table is being stored
911    * @param regionInfo {@link HRegionInfo} for region to be deleted
912    * @throws IOException if the request cannot be completed
913    */
914   public static void deleteRegionFromFileSystem(final Configuration conf,
915       final FileSystem fs, final Path tableDir, final HRegionInfo regionInfo) throws IOException {
916     HRegionFileSystem regionFs = new HRegionFileSystem(conf, fs, tableDir, regionInfo);
917     Path regionDir = regionFs.getRegionDir();
918 
919     if (!fs.exists(regionDir)) {
920       LOG.warn("Trying to delete a region that do not exists on disk: " + regionDir);
921       return;
922     }
923 
924     if (LOG.isDebugEnabled()) {
925       LOG.debug("DELETING region " + regionDir);
926     }
927 
928     // Archive region
929     Path rootDir = FSUtils.getRootDir(conf);
930     HFileArchiver.archiveRegion(fs, rootDir, tableDir, regionDir);
931 
932     // Delete empty region dir
933     if (!fs.delete(regionDir, true)) {
934       LOG.warn("Failed delete of " + regionDir);
935     }
936   }
937 
938   /**
939    * Creates a directory. Assumes the user has already checked for this directory existence.
940    * @param dir
941    * @return the result of fs.mkdirs(). In case underlying fs throws an IOException, it checks
942    *         whether the directory exists or not, and returns true if it exists.
943    * @throws IOException
944    */
945   boolean createDir(Path dir) throws IOException {
946     int i = 0;
947     IOException lastIOE = null;
948     do {
949       try {
950         return fs.mkdirs(dir);
951       } catch (IOException ioe) {
952         lastIOE = ioe;
953         if (fs.exists(dir)) return true; // directory is present
954         try {
955           sleepBeforeRetry("Create Directory", i+1);
956         } catch (InterruptedException e) {
957           throw (InterruptedIOException)new InterruptedIOException().initCause(e);
958         }
959       }
960     } while (++i <= hdfsClientRetriesNumber);
961     throw new IOException("Exception in createDir", lastIOE);
962   }
963 
964   /**
965    * Renames a directory. Assumes the user has already checked for this directory existence.
966    * @param srcpath
967    * @param dstPath
968    * @return true if rename is successful.
969    * @throws IOException
970    */
971   boolean rename(Path srcpath, Path dstPath) throws IOException {
972     IOException lastIOE = null;
973     int i = 0;
974     do {
975       try {
976         return fs.rename(srcpath, dstPath);
977       } catch (IOException ioe) {
978         lastIOE = ioe;
979         if (!fs.exists(srcpath) && fs.exists(dstPath)) return true; // successful move
980         // dir is not there, retry after some time.
981         try {
982           sleepBeforeRetry("Rename Directory", i+1);
983         } catch (InterruptedException e) {
984           throw (InterruptedIOException)new InterruptedIOException().initCause(e);
985         }
986       }
987     } while (++i <= hdfsClientRetriesNumber);
988 
989     throw new IOException("Exception in rename", lastIOE);
990   }
991 
992   /**
993    * Deletes a directory. Assumes the user has already checked for this directory existence.
994    * @param dir
995    * @return true if the directory is deleted.
996    * @throws IOException
997    */
998   boolean deleteDir(Path dir) throws IOException {
999     IOException lastIOE = null;
1000     int i = 0;
1001     do {
1002       try {
1003         return fs.delete(dir, true);
1004       } catch (IOException ioe) {
1005         lastIOE = ioe;
1006         if (!fs.exists(dir)) return true;
1007         // dir is there, retry deleting after some time.
1008         try {
1009           sleepBeforeRetry("Delete Directory", i+1);
1010         } catch (InterruptedException e) {
1011           throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1012         }
1013       }
1014     } while (++i <= hdfsClientRetriesNumber);
1015 
1016     throw new IOException("Exception in DeleteDir", lastIOE);
1017   }
1018 
1019   /**
1020    * sleeping logic; handles the interrupt exception.
1021    */
1022   private void sleepBeforeRetry(String msg, int sleepMultiplier) throws InterruptedException {
1023     sleepBeforeRetry(msg, sleepMultiplier, baseSleepBeforeRetries, hdfsClientRetriesNumber);
1024   }
1025 
1026   /**
1027    * Creates a directory for a filesystem and configuration object. Assumes the user has already
1028    * checked for this directory existence.
1029    * @param fs
1030    * @param conf
1031    * @param dir
1032    * @return the result of fs.mkdirs(). In case underlying fs throws an IOException, it checks
1033    *         whether the directory exists or not, and returns true if it exists.
1034    * @throws IOException
1035    */
1036   private static boolean createDirOnFileSystem(FileSystem fs, Configuration conf, Path dir)
1037       throws IOException {
1038     int i = 0;
1039     IOException lastIOE = null;
1040     int hdfsClientRetriesNumber = conf.getInt("hdfs.client.retries.number",
1041       DEFAULT_HDFS_CLIENT_RETRIES_NUMBER);
1042     int baseSleepBeforeRetries = conf.getInt("hdfs.client.sleep.before.retries",
1043       DEFAULT_BASE_SLEEP_BEFORE_RETRIES);
1044     do {
1045       try {
1046         return fs.mkdirs(dir);
1047       } catch (IOException ioe) {
1048         lastIOE = ioe;
1049         if (fs.exists(dir)) return true; // directory is present
1050         try {
1051           sleepBeforeRetry("Create Directory", i+1, baseSleepBeforeRetries, hdfsClientRetriesNumber);
1052         } catch (InterruptedException e) {
1053           throw (InterruptedIOException)new InterruptedIOException().initCause(e);
1054         }
1055       }
1056     } while (++i <= hdfsClientRetriesNumber);
1057 
1058     throw new IOException("Exception in createDir", lastIOE);
1059   }
1060 
1061   /**
1062    * sleeping logic for static methods; handles the interrupt exception. Keeping a static version
1063    * for this to avoid re-looking for the integer values.
1064    */
1065   private static void sleepBeforeRetry(String msg, int sleepMultiplier, int baseSleepBeforeRetries,
1066       int hdfsClientRetriesNumber) throws InterruptedException {
1067     if (sleepMultiplier > hdfsClientRetriesNumber) {
1068       LOG.debug(msg + ", retries exhausted");
1069       return;
1070     }
1071     LOG.debug(msg + ", sleeping " + baseSleepBeforeRetries + " times " + sleepMultiplier);
1072     Thread.sleep((long)baseSleepBeforeRetries * sleepMultiplier);
1073   }
1074 }