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