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