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