View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.regionserver;
21  
22  import java.io.FileNotFoundException;
23  import java.io.IOException;
24  import java.util.regex.Matcher;
25  import java.util.regex.Pattern;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.conf.Configuration;
31  import org.apache.hadoop.fs.FileStatus;
32  import org.apache.hadoop.fs.FileSystem;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.hbase.HDFSBlocksDistribution;
35  import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
36  import org.apache.hadoop.hbase.io.HFileLink;
37  import org.apache.hadoop.hbase.io.HalfStoreFileReader;
38  import org.apache.hadoop.hbase.io.Reference;
39  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
40  import org.apache.hadoop.hbase.util.FSUtils;
41  
42  /**
43   * Describe a StoreFile (hfile, reference, link)
44   */
45  @InterfaceAudience.Private
46  public class StoreFileInfo {
47    private static final Log LOG = LogFactory.getLog(StoreFileInfo.class);
48  
49    /**
50     * A non-capture group, for hfiles, so that this can be embedded.
51     * HFiles are uuid ([0-9a-z]+). Bulk loaded hfiles has (_SeqId_[0-9]+_) has suffix.
52     * The mob del file has (_del) as suffix.
53     */
54    public static final String HFILE_NAME_REGEX = "[0-9a-f]+(?:(?:_SeqId_[0-9]+_)|(?:_del))?";
55  
56    /** Regex that will work for hfiles */
57    private static final Pattern HFILE_NAME_PATTERN =
58      Pattern.compile("^(" + HFILE_NAME_REGEX + ")");
59  
60    /**
61     * A non-capture group, for del files, so that this can be embedded.
62     * A del file has (_del) as suffix.
63     */
64    public static final String DELFILE_NAME_REGEX = "[0-9a-f]+(?:_del)";
65  
66    /** Regex that will work for del files */
67    private static final Pattern DELFILE_NAME_PATTERN =
68      Pattern.compile("^(" + DELFILE_NAME_REGEX + ")");
69  
70    /**
71     * Regex that will work for straight reference names (<hfile>.<parentEncRegion>)
72     * and hfilelink reference names (<table>=<region>-<hfile>.<parentEncRegion>)
73     * If reference, then the regex has more than just one group.
74     * Group 1, hfile/hfilelink pattern, is this file's id.
75     * Group 2 '(.+)' is the reference's parent region name.
76     */
77    private static final Pattern REF_NAME_PATTERN =
78      Pattern.compile(String.format("^(%s|%s)\\.(.+)$",
79        HFILE_NAME_REGEX, HFileLink.LINK_NAME_REGEX));
80  
81    // Configuration
82    private Configuration conf;
83  
84    // FileSystem handle
85    private final FileSystem fs;
86  
87    // HDFS blocks distribution information
88    private HDFSBlocksDistribution hdfsBlocksDistribution = null;
89  
90    // If this storefile references another, this is the reference instance.
91    private final Reference reference;
92  
93    // If this storefile is a link to another, this is the link instance.
94    private final HFileLink link;
95  
96    private final Path initialPath;
97  
98    private RegionCoprocessorHost coprocessorHost;
99  
100   /**
101    * Create a Store File Info
102    * @param conf the {@link Configuration} to use
103    * @param fs The current file system to use.
104    * @param initialPath The {@link Path} of the file
105    */
106   public StoreFileInfo(final Configuration conf, final FileSystem fs, final Path initialPath)
107       throws IOException {
108     assert fs != null;
109     assert initialPath != null;
110     assert conf != null;
111 
112     this.fs = fs;
113     this.conf = conf;
114     this.initialPath = initialPath;
115     Path p = initialPath;
116     if (HFileLink.isHFileLink(p)) {
117       // HFileLink
118       this.reference = null;
119       this.link = HFileLink.buildFromHFileLinkPattern(conf, p);
120       if (LOG.isTraceEnabled()) LOG.trace(p + " is a link");
121     } else if (isReference(p)) {
122       this.reference = Reference.read(fs, p);
123       Path referencePath = getReferredToFile(p);
124       if (HFileLink.isHFileLink(referencePath)) {
125         // HFileLink Reference
126         this.link = HFileLink.buildFromHFileLinkPattern(conf, referencePath);
127       } else {
128         // Reference
129         this.link = null;
130       }
131       if (LOG.isTraceEnabled()) LOG.trace(p + " is a " + reference.getFileRegion() +
132               " reference to " + referencePath);
133     } else if (isHFile(p)) {
134       // HFile
135       this.reference = null;
136       this.link = null;
137     } else {
138       throw new IOException("path=" + p + " doesn't look like a valid StoreFile");
139     }
140   }
141 
142   /**
143    * Create a Store File Info
144    * @param conf the {@link Configuration} to use
145    * @param fs The current file system to use.
146    * @param fileStatus The {@link FileStatus} of the file
147    */
148   public StoreFileInfo(final Configuration conf, final FileSystem fs, final FileStatus fileStatus)
149       throws IOException {
150     this(conf, fs, fileStatus.getPath());
151   }
152 
153   /**
154    * Create a Store File Info from an HFileLink
155    * @param conf the {@link Configuration} to use
156    * @param fs The current file system to use.
157    * @param fileStatus The {@link FileStatus} of the file
158    */
159   public StoreFileInfo(final Configuration conf, final FileSystem fs, final FileStatus fileStatus,
160       final HFileLink link)
161       throws IOException {
162     this.fs = fs;
163     this.conf = conf;
164     // initialPath can be null only if we get a link.
165     this.initialPath = (fileStatus == null) ? null : fileStatus.getPath();
166       // HFileLink
167     this.reference = null;
168     this.link = link;
169   }
170 
171   /**
172    * Create a Store File Info from an HFileLink
173    * @param conf
174    * @param fs
175    * @param fileStatus
176    * @param reference
177    * @throws IOException
178    */
179   public StoreFileInfo(final Configuration conf, final FileSystem fs, final FileStatus fileStatus,
180       final Reference reference)
181       throws IOException {
182     this.fs = fs;
183     this.conf = conf;
184     this.initialPath = fileStatus.getPath();
185     this.reference = reference;
186     this.link = null;
187   }
188 
189   /**
190    * Sets the region coprocessor env.
191    * @param coprocessorHost
192    */
193   public void setRegionCoprocessorHost(RegionCoprocessorHost coprocessorHost) {
194     this.coprocessorHost = coprocessorHost;
195   }
196 
197   /*
198    * @return the Reference object associated to this StoreFileInfo.
199    *         null if the StoreFile is not a reference.
200    */
201   public Reference getReference() {
202     return this.reference;
203   }
204 
205   /** @return True if the store file is a Reference */
206   public boolean isReference() {
207     return this.reference != null;
208   }
209 
210   /** @return True if the store file is a top Reference */
211   public boolean isTopReference() {
212     return this.reference != null && Reference.isTopFileRegion(this.reference.getFileRegion());
213   }
214 
215   /** @return True if the store file is a link */
216   public boolean isLink() {
217     return this.link != null && this.reference == null;
218   }
219 
220   /** @return the HDFS block distribution */
221   public HDFSBlocksDistribution getHDFSBlockDistribution() {
222     return this.hdfsBlocksDistribution;
223   }
224 
225   /**
226    * Open a Reader for the StoreFile
227    * @param fs The current file system to use.
228    * @param cacheConf The cache configuration and block cache reference.
229    * @return The StoreFile.Reader for the file
230    */
231   public StoreFile.Reader open(final FileSystem fs,
232       final CacheConfig cacheConf) throws IOException {
233     FSDataInputStreamWrapper in;
234     FileStatus status;
235 
236     if (this.link != null) {
237       // HFileLink
238       in = new FSDataInputStreamWrapper(fs, this.link);
239       status = this.link.getFileStatus(fs);
240     } else if (this.reference != null) {
241       // HFile Reference
242       Path referencePath = getReferredToFile(this.getPath());
243       in = new FSDataInputStreamWrapper(fs, referencePath);
244       status = fs.getFileStatus(referencePath);
245     } else {
246       in = new FSDataInputStreamWrapper(fs, this.getPath());
247       status = fs.getFileStatus(initialPath);
248     }
249     long length = status.getLen();
250     hdfsBlocksDistribution = computeHDFSBlocksDistribution(fs);
251 
252     StoreFile.Reader reader = null;
253     if (this.coprocessorHost != null) {
254       reader = this.coprocessorHost.preStoreFileReaderOpen(fs, this.getPath(), in, length,
255         cacheConf, reference);
256     }
257     if (reader == null) {
258       if (this.reference != null) {
259         reader = new HalfStoreFileReader(fs, this.getPath(), in, length, cacheConf, reference,
260           conf);
261       } else {
262         reader = new StoreFile.Reader(fs, status.getPath(), in, length, cacheConf, conf);
263       }
264     }
265     if (this.coprocessorHost != null) {
266       reader = this.coprocessorHost.postStoreFileReaderOpen(fs, this.getPath(), in, length,
267         cacheConf, reference, reader);
268     }
269     return reader;
270   }
271 
272   /**
273    * Compute the HDFS Block Distribution for this StoreFile
274    */
275   public HDFSBlocksDistribution computeHDFSBlocksDistribution(final FileSystem fs)
276       throws IOException {
277 
278     // guard against the case where we get the FileStatus from link, but by the time we
279     // call compute the file is moved again
280     if (this.link != null) {
281       FileNotFoundException exToThrow = null;
282       for (int i = 0; i < this.link.getLocations().length; i++) {
283         try {
284           return computeHDFSBlocksDistributionInternal(fs);
285         } catch (FileNotFoundException ex) {
286           // try the other location
287           exToThrow = ex;
288         }
289       }
290       throw exToThrow;
291     } else {
292       return computeHDFSBlocksDistributionInternal(fs);
293     }
294   }
295 
296   private HDFSBlocksDistribution computeHDFSBlocksDistributionInternal(final FileSystem fs)
297       throws IOException {
298     FileStatus status = getReferencedFileStatus(fs);
299     if (this.reference != null) {
300       return computeRefFileHDFSBlockDistribution(fs, reference, status);
301     } else {
302       return FSUtils.computeHDFSBlocksDistribution(fs, status, 0, status.getLen());
303     }
304   }
305 
306   /**
307    * Get the {@link FileStatus} of the file referenced by this StoreFileInfo
308    * @param fs The current file system to use.
309    * @return The {@link FileStatus} of the file referenced by this StoreFileInfo
310    */
311   public FileStatus getReferencedFileStatus(final FileSystem fs) throws IOException {
312     FileStatus status;
313     if (this.reference != null) {
314       if (this.link != null) {
315         FileNotFoundException exToThrow = null;
316         for (int i = 0; i < this.link.getLocations().length; i++) {
317           // HFileLink Reference
318           try {
319             return link.getFileStatus(fs);
320           } catch (FileNotFoundException ex) {
321             // try the other location
322             exToThrow = ex;
323           }
324         }
325         throw exToThrow;
326       } else {
327         // HFile Reference
328         Path referencePath = getReferredToFile(this.getPath());
329         status = fs.getFileStatus(referencePath);
330       }
331     } else {
332       if (this.link != null) {
333         FileNotFoundException exToThrow = null;
334         for (int i = 0; i < this.link.getLocations().length; i++) {
335           // HFileLink
336           try {
337             return link.getFileStatus(fs);
338           } catch (FileNotFoundException ex) {
339             // try the other location
340             exToThrow = ex;
341           }
342         }
343         throw exToThrow;
344       } else {
345         status = fs.getFileStatus(initialPath);
346       }
347     }
348     return status;
349   }
350 
351   /** @return The {@link Path} of the file */
352   public Path getPath() {
353     return initialPath;
354   }
355 
356   /** @return The {@link FileStatus} of the file */
357   public FileStatus getFileStatus() throws IOException {
358     return getReferencedFileStatus(fs);
359   }
360 
361   /** @return Get the modification time of the file. */
362   public long getModificationTime() throws IOException {
363     return getFileStatus().getModificationTime();
364   }
365 
366   @Override
367   public String toString() {
368     return this.getPath() +
369       (isReference() ? "-" + getReferredToFile(this.getPath()) + "-" + reference : "");
370   }
371 
372   /**
373    * @param path Path to check.
374    * @return True if the path has format of a HFile.
375    */
376   public static boolean isHFile(final Path path) {
377     return isHFile(path.getName());
378   }
379 
380   public static boolean isHFile(final String fileName) {
381     Matcher m = HFILE_NAME_PATTERN.matcher(fileName);
382     return m.matches() && m.groupCount() > 0;
383   }
384 
385   /**
386    * @param path Path to check.
387    * @return True if the path has format of a del file.
388    */
389   public static boolean isDelFile(final Path path) {
390     return isDelFile(path.getName());
391   }
392 
393   /**
394    * @param fileName Sting version of path to validate.
395    * @return True if the file name has format of a del file.
396    */
397   public static boolean isDelFile(final String fileName) {
398     Matcher m = DELFILE_NAME_PATTERN.matcher(fileName);
399     return m.matches() && m.groupCount() > 0;
400   }
401 
402   /**
403    * @param path Path to check.
404    * @return True if the path has format of a HStoreFile reference.
405    */
406   public static boolean isReference(final Path path) {
407     return isReference(path.getName());
408   }
409 
410   /**
411    * @param name file name to check.
412    * @return True if the path has format of a HStoreFile reference.
413    */
414   public static boolean isReference(final String name) {
415     Matcher m = REF_NAME_PATTERN.matcher(name);
416     return m.matches() && m.groupCount() > 1;
417   }
418 
419   /*
420    * Return path to the file referred to by a Reference.  Presumes a directory
421    * hierarchy of <code>${hbase.rootdir}/data/${namespace}/tablename/regionname/familyname</code>.
422    * @param p Path to a Reference file.
423    * @return Calculated path to parent region file.
424    * @throws IllegalArgumentException when path regex fails to match.
425    */
426   public static Path getReferredToFile(final Path p) {
427     Matcher m = REF_NAME_PATTERN.matcher(p.getName());
428     if (m == null || !m.matches()) {
429       LOG.warn("Failed match of store file name " + p.toString());
430       throw new IllegalArgumentException("Failed match of store file name " +
431           p.toString());
432     }
433 
434     // Other region name is suffix on the passed Reference file name
435     String otherRegion = m.group(2);
436     // Tabledir is up two directories from where Reference was written.
437     Path tableDir = p.getParent().getParent().getParent();
438     String nameStrippedOfSuffix = m.group(1);
439     if (LOG.isDebugEnabled()) {
440       LOG.debug("reference '" + p + "' to region=" + otherRegion
441         + " hfile=" + nameStrippedOfSuffix);
442     }
443 
444     // Build up new path with the referenced region in place of our current
445     // region in the reference path.  Also strip regionname suffix from name.
446     return new Path(new Path(new Path(tableDir, otherRegion),
447       p.getParent().getName()), nameStrippedOfSuffix);
448   }
449 
450   /**
451    * Validate the store file name.
452    * @param fileName name of the file to validate
453    * @return <tt>true</tt> if the file could be a valid store file, <tt>false</tt> otherwise
454    */
455   public static boolean validateStoreFileName(final String fileName) {
456     if (HFileLink.isHFileLink(fileName) || isReference(fileName))
457       return(true);
458     return !fileName.contains("-");
459   }
460 
461   /**
462    * Return if the specified file is a valid store file or not.
463    * @param fileStatus The {@link FileStatus} of the file
464    * @return <tt>true</tt> if the file is valid
465    */
466   public static boolean isValid(final FileStatus fileStatus)
467       throws IOException {
468     final Path p = fileStatus.getPath();
469 
470     if (fileStatus.isDirectory())
471       return false;
472 
473     // Check for empty hfile. Should never be the case but can happen
474     // after data loss in hdfs for whatever reason (upgrade, etc.): HBASE-646
475     // NOTE: that the HFileLink is just a name, so it's an empty file.
476     if (!HFileLink.isHFileLink(p) && fileStatus.getLen() <= 0) {
477       LOG.warn("Skipping " + p + " because it is empty. HBASE-646 DATA LOSS?");
478       return false;
479     }
480 
481     return validateStoreFileName(p.getName());
482   }
483 
484   /**
485    * helper function to compute HDFS blocks distribution of a given reference
486    * file.For reference file, we don't compute the exact value. We use some
487    * estimate instead given it might be good enough. we assume bottom part
488    * takes the first half of reference file, top part takes the second half
489    * of the reference file. This is just estimate, given
490    * midkey ofregion != midkey of HFile, also the number and size of keys vary.
491    * If this estimate isn't good enough, we can improve it later.
492    * @param fs  The FileSystem
493    * @param reference  The reference
494    * @param status  The reference FileStatus
495    * @return HDFS blocks distribution
496    */
497   private static HDFSBlocksDistribution computeRefFileHDFSBlockDistribution(
498       final FileSystem fs, final Reference reference, final FileStatus status)
499       throws IOException {
500     if (status == null) {
501       return null;
502     }
503 
504     long start = 0;
505     long length = 0;
506 
507     if (Reference.isTopFileRegion(reference.getFileRegion())) {
508       start = status.getLen()/2;
509       length = status.getLen() - status.getLen()/2;
510     } else {
511       start = 0;
512       length = status.getLen()/2;
513     }
514     return FSUtils.computeHDFSBlocksDistribution(fs, status, start, length);
515   }
516 
517   @Override
518   public boolean equals(Object that) {
519     if (this == that) return true;
520     if (that == null) return false;
521 
522     if (!(that instanceof StoreFileInfo)) return false;
523 
524     StoreFileInfo o = (StoreFileInfo)that;
525     if (initialPath != null && o.initialPath == null) return false;
526     if (initialPath == null && o.initialPath != null) return false;
527     if (initialPath != o.initialPath && initialPath != null
528             && !initialPath.equals(o.initialPath)) return false;
529 
530     if (reference != null && o.reference == null) return false;
531     if (reference == null && o.reference != null) return false;
532     if (reference != o.reference && reference != null
533             && !reference.equals(o.reference)) return false;
534 
535     if (link != null && o.link == null) return false;
536     if (link == null && o.link != null) return false;
537     if (link != o.link && link != null && !link.equals(o.link)) return false;
538 
539     return true;
540   };
541 
542 
543   @Override
544   public int hashCode() {
545     int hash = 17;
546     hash = hash * 31 + ((reference == null) ? 0 : reference.hashCode());
547     hash = hash * 31 + ((initialPath ==  null) ? 0 : initialPath.hashCode());
548     hash = hash * 31 + ((link == null) ? 0 : link.hashCode());
549     return  hash;
550   }
551 }