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