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    public 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   // timestamp on when the file was created, is 0 and ignored for reference or link files
101   private long createdTimestamp;
102 
103   /**
104    * Create a Store File Info
105    * @param conf the {@link Configuration} to use
106    * @param fs The current file system to use.
107    * @param initialPath The {@link Path} of the file
108    */
109   public StoreFileInfo(final Configuration conf, final FileSystem fs, final Path initialPath)
110       throws IOException {
111     assert fs != null;
112     assert initialPath != null;
113     assert conf != null;
114 
115     this.fs = fs;
116     this.conf = conf;
117     this.initialPath = initialPath;
118     Path p = initialPath;
119     if (HFileLink.isHFileLink(p)) {
120       // HFileLink
121       this.reference = null;
122       this.link = HFileLink.buildFromHFileLinkPattern(conf, p);
123       if (LOG.isTraceEnabled()) LOG.trace(p + " is a link");
124     } else if (isReference(p)) {
125       this.reference = Reference.read(fs, p);
126       Path referencePath = getReferredToFile(p);
127       if (HFileLink.isHFileLink(referencePath)) {
128         // HFileLink Reference
129         this.link = HFileLink.buildFromHFileLinkPattern(conf, referencePath);
130       } else {
131         // Reference
132         this.link = null;
133       }
134       if (LOG.isTraceEnabled()) LOG.trace(p + " is a " + reference.getFileRegion() +
135               " reference to " + referencePath);
136     } else if (isHFile(p)) {
137       // HFile
138       this.createdTimestamp = fs.getFileStatus(initialPath).getModificationTime();
139       this.reference = null;
140       this.link = null;
141     } else {
142       throw new IOException("path=" + p + " doesn't look like a valid StoreFile");
143     }
144   }
145 
146   /**
147    * Create a Store File Info
148    * @param conf the {@link Configuration} to use
149    * @param fs The current file system to use.
150    * @param fileStatus The {@link FileStatus} of the file
151    */
152   public StoreFileInfo(final Configuration conf, final FileSystem fs, final FileStatus fileStatus)
153       throws IOException {
154     this(conf, fs, fileStatus.getPath());
155   }
156 
157   /**
158    * Create a Store File Info from an HFileLink
159    * @param conf the {@link Configuration} to use
160    * @param fs The current file system to use.
161    * @param fileStatus The {@link FileStatus} of the file
162    */
163   public StoreFileInfo(final Configuration conf, final FileSystem fs, final FileStatus fileStatus,
164       final HFileLink link)
165       throws IOException {
166     this.fs = fs;
167     this.conf = conf;
168     // initialPath can be null only if we get a link.
169     this.initialPath = (fileStatus == null) ? null : fileStatus.getPath();
170       // HFileLink
171     this.reference = null;
172     this.link = link;
173   }
174 
175   /**
176    * Create a Store File Info from an HFileLink
177    * @param conf
178    * @param fs
179    * @param fileStatus
180    * @param reference
181    * @throws IOException
182    */
183   public StoreFileInfo(final Configuration conf, final FileSystem fs, final FileStatus fileStatus,
184       final Reference reference)
185       throws IOException {
186     this.fs = fs;
187     this.conf = conf;
188     this.initialPath = fileStatus.getPath();
189     this.createdTimestamp = fileStatus.getModificationTime();
190     this.reference = reference;
191     this.link = null;
192   }
193 
194   /**
195    * Sets the region coprocessor env.
196    * @param coprocessorHost
197    */
198   public void setRegionCoprocessorHost(RegionCoprocessorHost coprocessorHost) {
199     this.coprocessorHost = coprocessorHost;
200   }
201 
202   /*
203    * @return the Reference object associated to this StoreFileInfo.
204    *         null if the StoreFile is not a reference.
205    */
206   public Reference getReference() {
207     return this.reference;
208   }
209 
210   /** @return True if the store file is a Reference */
211   public boolean isReference() {
212     return this.reference != null;
213   }
214 
215   /** @return True if the store file is a top Reference */
216   public boolean isTopReference() {
217     return this.reference != null && Reference.isTopFileRegion(this.reference.getFileRegion());
218   }
219 
220   /** @return True if the store file is a link */
221   public boolean isLink() {
222     return this.link != null && this.reference == null;
223   }
224 
225   /** @return the HDFS block distribution */
226   public HDFSBlocksDistribution getHDFSBlockDistribution() {
227     return this.hdfsBlocksDistribution;
228   }
229 
230   /**
231    * Open a Reader for the StoreFile
232    * @param fs The current file system to use.
233    * @param cacheConf The cache configuration and block cache reference.
234    * @return The StoreFile.Reader for the file
235    */
236   public StoreFile.Reader open(final FileSystem fs,
237       final CacheConfig cacheConf) throws IOException {
238     FSDataInputStreamWrapper in;
239     FileStatus status;
240 
241     if (this.link != null) {
242       // HFileLink
243       in = new FSDataInputStreamWrapper(fs, this.link);
244       status = this.link.getFileStatus(fs);
245     } else if (this.reference != null) {
246       // HFile Reference
247       Path referencePath = getReferredToFile(this.getPath());
248       in = new FSDataInputStreamWrapper(fs, referencePath);
249       status = fs.getFileStatus(referencePath);
250     } else {
251       in = new FSDataInputStreamWrapper(fs, this.getPath());
252       status = fs.getFileStatus(initialPath);
253     }
254     long length = status.getLen();
255     hdfsBlocksDistribution = computeHDFSBlocksDistribution(fs);
256 
257     StoreFile.Reader reader = null;
258     if (this.coprocessorHost != null) {
259       reader = this.coprocessorHost.preStoreFileReaderOpen(fs, this.getPath(), in, length,
260         cacheConf, reference);
261     }
262     if (reader == null) {
263       if (this.reference != null) {
264         reader = new HalfStoreFileReader(fs, this.getPath(), in, length, cacheConf, reference,
265           conf);
266       } else {
267         reader = new StoreFile.Reader(fs, status.getPath(), in, length, cacheConf, conf);
268       }
269     }
270     if (this.coprocessorHost != null) {
271       reader = this.coprocessorHost.postStoreFileReaderOpen(fs, this.getPath(), in, length,
272         cacheConf, reference, reader);
273     }
274     return reader;
275   }
276 
277   /**
278    * Compute the HDFS Block Distribution for this StoreFile
279    */
280   public HDFSBlocksDistribution computeHDFSBlocksDistribution(final FileSystem fs)
281       throws IOException {
282 
283     // guard against the case where we get the FileStatus from link, but by the time we
284     // call compute the file is moved again
285     if (this.link != null) {
286       FileNotFoundException exToThrow = null;
287       for (int i = 0; i < this.link.getLocations().length; i++) {
288         try {
289           return computeHDFSBlocksDistributionInternal(fs);
290         } catch (FileNotFoundException ex) {
291           // try the other location
292           exToThrow = ex;
293         }
294       }
295       throw exToThrow;
296     } else {
297       return computeHDFSBlocksDistributionInternal(fs);
298     }
299   }
300 
301   private HDFSBlocksDistribution computeHDFSBlocksDistributionInternal(final FileSystem fs)
302       throws IOException {
303     FileStatus status = getReferencedFileStatus(fs);
304     if (this.reference != null) {
305       return computeRefFileHDFSBlockDistribution(fs, reference, status);
306     } else {
307       return FSUtils.computeHDFSBlocksDistribution(fs, status, 0, status.getLen());
308     }
309   }
310 
311   /**
312    * Get the {@link FileStatus} of the file referenced by this StoreFileInfo
313    * @param fs The current file system to use.
314    * @return The {@link FileStatus} of the file referenced by this StoreFileInfo
315    */
316   public FileStatus getReferencedFileStatus(final FileSystem fs) throws IOException {
317     FileStatus status;
318     if (this.reference != null) {
319       if (this.link != null) {
320         FileNotFoundException exToThrow = null;
321         for (int i = 0; i < this.link.getLocations().length; i++) {
322           // HFileLink Reference
323           try {
324             return link.getFileStatus(fs);
325           } catch (FileNotFoundException ex) {
326             // try the other location
327             exToThrow = ex;
328           }
329         }
330         throw exToThrow;
331       } else {
332         // HFile Reference
333         Path referencePath = getReferredToFile(this.getPath());
334         status = fs.getFileStatus(referencePath);
335       }
336     } else {
337       if (this.link != null) {
338         FileNotFoundException exToThrow = null;
339         for (int i = 0; i < this.link.getLocations().length; i++) {
340           // HFileLink
341           try {
342             return link.getFileStatus(fs);
343           } catch (FileNotFoundException ex) {
344             // try the other location
345             exToThrow = ex;
346           }
347         }
348         throw exToThrow;
349       } else {
350         status = fs.getFileStatus(initialPath);
351       }
352     }
353     return status;
354   }
355 
356   /** @return The {@link Path} of the file */
357   public Path getPath() {
358     return initialPath;
359   }
360 
361   /** @return The {@link FileStatus} of the file */
362   public FileStatus getFileStatus() throws IOException {
363     return getReferencedFileStatus(fs);
364   }
365 
366   /** @return Get the modification time of the file. */
367   public long getModificationTime() throws IOException {
368     return getFileStatus().getModificationTime();
369   }
370 
371   @Override
372   public String toString() {
373     return this.getPath() +
374       (isReference() ? "-" + getReferredToFile(this.getPath()) + "-" + reference : "");
375   }
376 
377   /**
378    * @param path Path to check.
379    * @return True if the path has format of a HFile.
380    */
381   public static boolean isHFile(final Path path) {
382     return isHFile(path.getName());
383   }
384 
385   public static boolean isHFile(final String fileName) {
386     Matcher m = HFILE_NAME_PATTERN.matcher(fileName);
387     return m.matches() && m.groupCount() > 0;
388   }
389 
390   /**
391    * @param path Path to check.
392    * @return True if the path has format of a del file.
393    */
394   public static boolean isDelFile(final Path path) {
395     return isDelFile(path.getName());
396   }
397 
398   /**
399    * @param fileName Sting version of path to validate.
400    * @return True if the file name has format of a del file.
401    */
402   public static boolean isDelFile(final String fileName) {
403     Matcher m = DELFILE_NAME_PATTERN.matcher(fileName);
404     return m.matches() && m.groupCount() > 0;
405   }
406 
407   /**
408    * @param path Path to check.
409    * @return True if the path has format of a HStoreFile reference.
410    */
411   public static boolean isReference(final Path path) {
412     return isReference(path.getName());
413   }
414 
415   /**
416    * @param name file name to check.
417    * @return True if the path has format of a HStoreFile reference.
418    */
419   public static boolean isReference(final String name) {
420     Matcher m = REF_NAME_PATTERN.matcher(name);
421     return m.matches() && m.groupCount() > 1;
422   }
423 
424   /**
425    * @return timestamp when this file was created (as returned by filesystem)
426    */
427   public long getCreatedTimestamp() {
428     return createdTimestamp;
429   }
430 
431   /*
432    * Return path to the file referred to by a Reference.  Presumes a directory
433    * hierarchy of <code>${hbase.rootdir}/data/${namespace}/tablename/regionname/familyname</code>.
434    * @param p Path to a Reference file.
435    * @return Calculated path to parent region file.
436    * @throws IllegalArgumentException when path regex fails to match.
437    */
438   public static Path getReferredToFile(final Path p) {
439     Matcher m = REF_NAME_PATTERN.matcher(p.getName());
440     if (m == null || !m.matches()) {
441       LOG.warn("Failed match of store file name " + p.toString());
442       throw new IllegalArgumentException("Failed match of store file name " +
443           p.toString());
444     }
445 
446     // Other region name is suffix on the passed Reference file name
447     String otherRegion = m.group(2);
448     // Tabledir is up two directories from where Reference was written.
449     Path tableDir = p.getParent().getParent().getParent();
450     String nameStrippedOfSuffix = m.group(1);
451     if (LOG.isDebugEnabled()) {
452       LOG.debug("reference '" + p + "' to region=" + otherRegion
453         + " hfile=" + nameStrippedOfSuffix);
454     }
455 
456     // Build up new path with the referenced region in place of our current
457     // region in the reference path.  Also strip regionname suffix from name.
458     return new Path(new Path(new Path(tableDir, otherRegion),
459       p.getParent().getName()), nameStrippedOfSuffix);
460   }
461 
462   /**
463    * Validate the store file name.
464    * @param fileName name of the file to validate
465    * @return <tt>true</tt> if the file could be a valid store file, <tt>false</tt> otherwise
466    */
467   public static boolean validateStoreFileName(final String fileName) {
468     if (HFileLink.isHFileLink(fileName) || isReference(fileName))
469       return(true);
470     return !fileName.contains("-");
471   }
472 
473   /**
474    * Return if the specified file is a valid store file or not.
475    * @param fileStatus The {@link FileStatus} of the file
476    * @return <tt>true</tt> if the file is valid
477    */
478   public static boolean isValid(final FileStatus fileStatus)
479       throws IOException {
480     final Path p = fileStatus.getPath();
481 
482     if (fileStatus.isDirectory())
483       return false;
484 
485     // Check for empty hfile. Should never be the case but can happen
486     // after data loss in hdfs for whatever reason (upgrade, etc.): HBASE-646
487     // NOTE: that the HFileLink is just a name, so it's an empty file.
488     if (!HFileLink.isHFileLink(p) && fileStatus.getLen() <= 0) {
489       LOG.warn("Skipping " + p + " because it is empty. HBASE-646 DATA LOSS?");
490       return false;
491     }
492 
493     return validateStoreFileName(p.getName());
494   }
495 
496   /**
497    * helper function to compute HDFS blocks distribution of a given reference
498    * file.For reference file, we don't compute the exact value. We use some
499    * estimate instead given it might be good enough. we assume bottom part
500    * takes the first half of reference file, top part takes the second half
501    * of the reference file. This is just estimate, given
502    * midkey ofregion != midkey of HFile, also the number and size of keys vary.
503    * If this estimate isn't good enough, we can improve it later.
504    * @param fs  The FileSystem
505    * @param reference  The reference
506    * @param status  The reference FileStatus
507    * @return HDFS blocks distribution
508    */
509   private static HDFSBlocksDistribution computeRefFileHDFSBlockDistribution(
510       final FileSystem fs, final Reference reference, final FileStatus status)
511       throws IOException {
512     if (status == null) {
513       return null;
514     }
515 
516     long start = 0;
517     long length = 0;
518 
519     if (Reference.isTopFileRegion(reference.getFileRegion())) {
520       start = status.getLen()/2;
521       length = status.getLen() - status.getLen()/2;
522     } else {
523       start = 0;
524       length = status.getLen()/2;
525     }
526     return FSUtils.computeHDFSBlocksDistribution(fs, status, start, length);
527   }
528 
529   @Override
530   public boolean equals(Object that) {
531     if (this == that) return true;
532     if (that == null) return false;
533 
534     if (!(that instanceof StoreFileInfo)) return false;
535 
536     StoreFileInfo o = (StoreFileInfo)that;
537     if (initialPath != null && o.initialPath == null) return false;
538     if (initialPath == null && o.initialPath != null) return false;
539     if (initialPath != o.initialPath && initialPath != null
540             && !initialPath.equals(o.initialPath)) return false;
541 
542     if (reference != null && o.reference == null) return false;
543     if (reference == null && o.reference != null) return false;
544     if (reference != o.reference && reference != null
545             && !reference.equals(o.reference)) return false;
546 
547     if (link != null && o.link == null) return false;
548     if (link == null && o.link != null) return false;
549     if (link != o.link && link != null && !link.equals(o.link)) return false;
550 
551     return true;
552   };
553 
554 
555   @Override
556   public int hashCode() {
557     int hash = 17;
558     hash = hash * 31 + ((reference == null) ? 0 : reference.hashCode());
559     hash = hash * 31 + ((initialPath ==  null) ? 0 : initialPath.hashCode());
560     hash = hash * 31 + ((link == null) ? 0 : link.hashCode());
561     return  hash;
562   }
563 }