001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.io.hfile;
020
021import java.io.ByteArrayInputStream;
022import java.io.Closeable;
023import java.io.DataInput;
024import java.io.DataInputStream;
025import java.io.DataOutputStream;
026import java.io.IOException;
027import java.io.SequenceInputStream;
028import java.net.InetSocketAddress;
029import java.util.ArrayList;
030import java.util.Collection;
031import java.util.Comparator;
032import java.util.List;
033import java.util.Map;
034import java.util.Optional;
035import java.util.Set;
036import java.util.SortedMap;
037import java.util.TreeMap;
038import java.util.concurrent.atomic.LongAdder;
039
040import org.apache.commons.io.IOUtils;
041import org.apache.hadoop.conf.Configuration;
042import org.apache.hadoop.fs.FSDataInputStream;
043import org.apache.hadoop.fs.FSDataOutputStream;
044import org.apache.hadoop.fs.FileStatus;
045import org.apache.hadoop.fs.FileSystem;
046import org.apache.hadoop.fs.Path;
047import org.apache.hadoop.fs.PathFilter;
048import org.apache.hadoop.hbase.Cell;
049import org.apache.hadoop.hbase.CellComparator;
050import org.apache.hadoop.hbase.HConstants;
051import org.apache.yetus.audience.InterfaceAudience;
052import org.slf4j.Logger;
053import org.slf4j.LoggerFactory;
054import org.apache.hadoop.hbase.fs.HFileSystem;
055import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
056import org.apache.hadoop.hbase.io.MetricsIO;
057import org.apache.hadoop.hbase.io.MetricsIOWrapperImpl;
058import org.apache.hadoop.hbase.io.compress.Compression;
059import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
060import org.apache.hadoop.hbase.protobuf.ProtobufMagic;
061import org.apache.hadoop.hbase.regionserver.CellSink;
062import org.apache.hadoop.hbase.regionserver.ShipperListener;
063import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
064import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
065import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;
066import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.BytesBytesPair;
067import org.apache.hadoop.hbase.shaded.protobuf.generated.HFileProtos;
068import org.apache.hadoop.hbase.util.BloomFilterWriter;
069import org.apache.hadoop.hbase.util.Bytes;
070import org.apache.hadoop.hbase.util.FSUtils;
071import org.apache.hadoop.io.Writable;
072
073import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
074import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
075
076/**
077 * File format for hbase.
078 * A file of sorted key/value pairs. Both keys and values are byte arrays.
079 * <p>
080 * The memory footprint of a HFile includes the following (below is taken from the
081 * <a
082 * href=https://issues.apache.org/jira/browse/HADOOP-3315>TFile</a> documentation
083 * but applies also to HFile):
084 * <ul>
085 * <li>Some constant overhead of reading or writing a compressed block.
086 * <ul>
087 * <li>Each compressed block requires one compression/decompression codec for
088 * I/O.
089 * <li>Temporary space to buffer the key.
090 * <li>Temporary space to buffer the value.
091 * </ul>
092 * <li>HFile index, which is proportional to the total number of Data Blocks.
093 * The total amount of memory needed to hold the index can be estimated as
094 * (56+AvgKeySize)*NumBlocks.
095 * </ul>
096 * Suggestions on performance optimization.
097 * <ul>
098 * <li>Minimum block size. We recommend a setting of minimum block size between
099 * 8KB to 1MB for general usage. Larger block size is preferred if files are
100 * primarily for sequential access. However, it would lead to inefficient random
101 * access (because there are more data to decompress). Smaller blocks are good
102 * for random access, but require more memory to hold the block index, and may
103 * be slower to create (because we must flush the compressor stream at the
104 * conclusion of each data block, which leads to an FS I/O flush). Further, due
105 * to the internal caching in Compression codec, the smallest possible block
106 * size would be around 20KB-30KB.
107 * <li>The current implementation does not offer true multi-threading for
108 * reading. The implementation uses FSDataInputStream seek()+read(), which is
109 * shown to be much faster than positioned-read call in single thread mode.
110 * However, it also means that if multiple threads attempt to access the same
111 * HFile (using multiple scanners) simultaneously, the actual I/O is carried out
112 * sequentially even if they access different DFS blocks (Reexamine! pread seems
113 * to be 10% faster than seek+read in my testing -- stack).
114 * <li>Compression codec. Use "none" if the data is not very compressable (by
115 * compressable, I mean a compression ratio at least 2:1). Generally, use "lzo"
116 * as the starting point for experimenting. "gz" overs slightly better
117 * compression ratio over "lzo" but requires 4x CPU to compress and 2x CPU to
118 * decompress, comparing to "lzo".
119 * </ul>
120 *
121 * For more on the background behind HFile, see <a
122 * href=https://issues.apache.org/jira/browse/HBASE-61>HBASE-61</a>.
123 * <p>
124 * File is made of data blocks followed by meta data blocks (if any), a fileinfo
125 * block, data block index, meta data block index, and a fixed size trailer
126 * which records the offsets at which file changes content type.
127 * <pre>&lt;data blocks&gt;&lt;meta blocks&gt;&lt;fileinfo&gt;&lt;
128 * data index&gt;&lt;meta index&gt;&lt;trailer&gt;</pre>
129 * Each block has a bit of magic at its start.  Block are comprised of
130 * key/values.  In data blocks, they are both byte arrays.  Metadata blocks are
131 * a String key and a byte array value.  An empty file looks like this:
132 * <pre>&lt;fileinfo&gt;&lt;trailer&gt;</pre>.  That is, there are not data nor meta
133 * blocks present.
134 * <p>
135 * TODO: Do scanners need to be able to take a start and end row?
136 * TODO: Should BlockIndex know the name of its file?  Should it have a Path
137 * that points at its file say for the case where an index lives apart from
138 * an HFile instance?
139 */
140@InterfaceAudience.Private
141public class HFile {
142  // LOG is being used in HFileBlock and CheckSumUtil
143  static final Logger LOG = LoggerFactory.getLogger(HFile.class);
144
145  /**
146   * Maximum length of key in HFile.
147   */
148  public final static int MAXIMUM_KEY_LENGTH = Integer.MAX_VALUE;
149
150  /**
151   * Default compression: none.
152   */
153  public final static Compression.Algorithm DEFAULT_COMPRESSION_ALGORITHM =
154    Compression.Algorithm.NONE;
155
156  /** Minimum supported HFile format version */
157  public static final int MIN_FORMAT_VERSION = 2;
158
159  /** Maximum supported HFile format version
160   */
161  public static final int MAX_FORMAT_VERSION = 3;
162
163  /**
164   * Minimum HFile format version with support for persisting cell tags
165   */
166  public static final int MIN_FORMAT_VERSION_WITH_TAGS = 3;
167
168  /** Default compression name: none. */
169  public final static String DEFAULT_COMPRESSION =
170    DEFAULT_COMPRESSION_ALGORITHM.getName();
171
172  /** Meta data block name for bloom filter bits. */
173  public static final String BLOOM_FILTER_DATA_KEY = "BLOOM_FILTER_DATA";
174
175  /**
176   * We assume that HFile path ends with
177   * ROOT_DIR/TABLE_NAME/REGION_NAME/CF_NAME/HFILE, so it has at least this
178   * many levels of nesting. This is needed for identifying table and CF name
179   * from an HFile path.
180   */
181  public final static int MIN_NUM_HFILE_PATH_LEVELS = 5;
182
183  /**
184   * The number of bytes per checksum.
185   */
186  public static final int DEFAULT_BYTES_PER_CHECKSUM = 16 * 1024;
187
188  // For measuring number of checksum failures
189  static final LongAdder CHECKSUM_FAILURES = new LongAdder();
190
191  // For tests. Gets incremented when we read a block whether from HDFS or from Cache.
192  public static final LongAdder DATABLOCK_READ_COUNT = new LongAdder();
193
194  /** Static instance for the metrics so that HFileReaders access the same instance */
195  static final MetricsIO metrics = new MetricsIO(new MetricsIOWrapperImpl());
196
197  /**
198   * Number of checksum verification failures. It also
199   * clears the counter.
200   */
201  public static final long getAndResetChecksumFailuresCount() {
202    return CHECKSUM_FAILURES.sumThenReset();
203  }
204
205  /**
206   * Number of checksum verification failures. It also
207   * clears the counter.
208   */
209  public static final long getChecksumFailuresCount() {
210    return CHECKSUM_FAILURES.sum();
211  }
212
213  public static final void updateReadLatency(long latencyMillis, boolean pread) {
214    if (pread) {
215      metrics.updateFsPreadTime(latencyMillis);
216    } else {
217      metrics.updateFsReadTime(latencyMillis);
218    }
219  }
220
221  public static final void updateWriteLatency(long latencyMillis) {
222    metrics.updateFsWriteTime(latencyMillis);
223  }
224
225  /** API required to write an {@link HFile} */
226  public interface Writer extends Closeable, CellSink, ShipperListener {
227    /** Max memstore (mvcc) timestamp in FileInfo */
228    public static final byte [] MAX_MEMSTORE_TS_KEY = Bytes.toBytes("MAX_MEMSTORE_TS_KEY");
229
230    /** Add an element to the file info map. */
231    void appendFileInfo(byte[] key, byte[] value) throws IOException;
232
233    /** @return the path to this {@link HFile} */
234    Path getPath();
235
236    /**
237     * Adds an inline block writer such as a multi-level block index writer or
238     * a compound Bloom filter writer.
239     */
240    void addInlineBlockWriter(InlineBlockWriter bloomWriter);
241
242    // The below three methods take Writables.  We'd like to undo Writables but undoing the below would be pretty
243    // painful.  Could take a byte [] or a Message but we want to be backward compatible around hfiles so would need
244    // to map between Message and Writable or byte [] and current Writable serialization.  This would be a bit of work
245    // to little gain.  Thats my thinking at moment.  St.Ack 20121129
246
247    void appendMetaBlock(String bloomFilterMetaKey, Writable metaWriter);
248
249    /**
250     * Store general Bloom filter in the file. This does not deal with Bloom filter
251     * internals but is necessary, since Bloom filters are stored differently
252     * in HFile version 1 and version 2.
253     */
254    void addGeneralBloomFilter(BloomFilterWriter bfw);
255
256    /**
257     * Store delete family Bloom filter in the file, which is only supported in
258     * HFile V2.
259     */
260    void addDeleteFamilyBloomFilter(BloomFilterWriter bfw) throws IOException;
261
262    /**
263     * Return the file context for the HFile this writer belongs to
264     */
265    HFileContext getFileContext();
266  }
267
268  /**
269   * This variety of ways to construct writers is used throughout the code, and
270   * we want to be able to swap writer implementations.
271   */
272  public static class WriterFactory {
273    protected final Configuration conf;
274    protected final CacheConfig cacheConf;
275    protected FileSystem fs;
276    protected Path path;
277    protected FSDataOutputStream ostream;
278    protected CellComparator comparator = CellComparator.getInstance();
279    protected InetSocketAddress[] favoredNodes;
280    private HFileContext fileContext;
281    protected boolean shouldDropBehind = false;
282
283    WriterFactory(Configuration conf, CacheConfig cacheConf) {
284      this.conf = conf;
285      this.cacheConf = cacheConf;
286    }
287
288    public WriterFactory withPath(FileSystem fs, Path path) {
289      Preconditions.checkNotNull(fs);
290      Preconditions.checkNotNull(path);
291      this.fs = fs;
292      this.path = path;
293      return this;
294    }
295
296    public WriterFactory withOutputStream(FSDataOutputStream ostream) {
297      Preconditions.checkNotNull(ostream);
298      this.ostream = ostream;
299      return this;
300    }
301
302    public WriterFactory withComparator(CellComparator comparator) {
303      Preconditions.checkNotNull(comparator);
304      this.comparator = comparator;
305      return this;
306    }
307
308    public WriterFactory withFavoredNodes(InetSocketAddress[] favoredNodes) {
309      // Deliberately not checking for null here.
310      this.favoredNodes = favoredNodes;
311      return this;
312    }
313
314    public WriterFactory withFileContext(HFileContext fileContext) {
315      this.fileContext = fileContext;
316      return this;
317    }
318
319    public WriterFactory withShouldDropCacheBehind(boolean shouldDropBehind) {
320      this.shouldDropBehind = shouldDropBehind;
321      return this;
322    }
323
324
325    public Writer create() throws IOException {
326      if ((path != null ? 1 : 0) + (ostream != null ? 1 : 0) != 1) {
327        throw new AssertionError("Please specify exactly one of " +
328            "filesystem/path or path");
329      }
330      if (path != null) {
331        ostream = HFileWriterImpl.createOutputStream(conf, fs, path, favoredNodes);
332        try {
333          ostream.setDropBehind(shouldDropBehind && cacheConf.shouldDropBehindCompaction());
334        } catch (UnsupportedOperationException uoe) {
335          LOG.trace("Unable to set drop behind on {}", path, uoe);
336          LOG.debug("Unable to set drop behind on {}", path.getName());
337        }
338      }
339      return new HFileWriterImpl(conf, cacheConf, path, ostream, comparator, fileContext);
340    }
341  }
342
343  /** The configuration key for HFile version to use for new files */
344  public static final String FORMAT_VERSION_KEY = "hfile.format.version";
345
346  public static int getFormatVersion(Configuration conf) {
347    int version = conf.getInt(FORMAT_VERSION_KEY, MAX_FORMAT_VERSION);
348    checkFormatVersion(version);
349    return version;
350  }
351
352  /**
353   * Returns the factory to be used to create {@link HFile} writers.
354   * Disables block cache access for all writers created through the
355   * returned factory.
356   */
357  public static final WriterFactory getWriterFactoryNoCache(Configuration
358       conf) {
359    Configuration tempConf = new Configuration(conf);
360    tempConf.setFloat(HConstants.HFILE_BLOCK_CACHE_SIZE_KEY, 0.0f);
361    return HFile.getWriterFactory(conf, new CacheConfig(tempConf));
362  }
363
364  /**
365   * Returns the factory to be used to create {@link HFile} writers
366   */
367  public static final WriterFactory getWriterFactory(Configuration conf,
368      CacheConfig cacheConf) {
369    int version = getFormatVersion(conf);
370    switch (version) {
371    case 2:
372      throw new IllegalArgumentException("This should never happen. " +
373        "Did you change hfile.format.version to read v2? This version of the software writes v3" +
374        " hfiles only (but it can read v2 files without having to update hfile.format.version " +
375        "in hbase-site.xml)");
376    case 3:
377      return new HFile.WriterFactory(conf, cacheConf);
378    default:
379      throw new IllegalArgumentException("Cannot create writer for HFile " +
380          "format version " + version);
381    }
382  }
383
384  /**
385   * An abstraction used by the block index.
386   * Implementations will check cache for any asked-for block and return cached block if found.
387   * Otherwise, after reading from fs, will try and put block into cache before returning.
388   */
389  public interface CachingBlockReader {
390    /**
391     * Read in a file block.
392     * @param offset offset to read.
393     * @param onDiskBlockSize size of the block
394     * @param cacheBlock
395     * @param pread
396     * @param isCompaction is this block being read as part of a compaction
397     * @param expectedBlockType the block type we are expecting to read with this read operation,
398     *  or null to read whatever block type is available and avoid checking (that might reduce
399     *  caching efficiency of encoded data blocks)
400     * @param expectedDataBlockEncoding the data block encoding the caller is expecting data blocks
401     *  to be in, or null to not perform this check and return the block irrespective of the
402     *  encoding. This check only applies to data blocks and can be set to null when the caller is
403     *  expecting to read a non-data block and has set expectedBlockType accordingly.
404     * @return Block wrapped in a ByteBuffer.
405     * @throws IOException
406     */
407    HFileBlock readBlock(long offset, long onDiskBlockSize,
408        boolean cacheBlock, final boolean pread, final boolean isCompaction,
409        final boolean updateCacheMetrics, BlockType expectedBlockType,
410        DataBlockEncoding expectedDataBlockEncoding)
411        throws IOException;
412
413    /**
414     * Return the given block back to the cache, if it was obtained from cache.
415     * @param block Block to be returned.
416     */
417    void returnBlock(HFileBlock block);
418  }
419
420  /** An interface used by clients to open and iterate an {@link HFile}. */
421  public interface Reader extends Closeable, CachingBlockReader {
422    /**
423     * Returns this reader's "name". Usually the last component of the path.
424     * Needs to be constant as the file is being moved to support caching on
425     * write.
426     */
427    String getName();
428
429    CellComparator getComparator();
430
431    HFileScanner getScanner(boolean cacheBlocks, final boolean pread, final boolean isCompaction);
432
433    HFileBlock getMetaBlock(String metaBlockName, boolean cacheBlock) throws IOException;
434
435    Map<byte[], byte[]> loadFileInfo() throws IOException;
436
437    Optional<Cell> getLastKey();
438
439    Optional<Cell> midKey() throws IOException;
440
441    long length();
442
443    long getEntries();
444
445    Optional<Cell> getFirstKey();
446
447    long indexSize();
448
449    Optional<byte[]> getFirstRowKey();
450
451    Optional<byte[]> getLastRowKey();
452
453    FixedFileTrailer getTrailer();
454
455    HFileBlockIndex.BlockIndexReader getDataBlockIndexReader();
456
457    HFileScanner getScanner(boolean cacheBlocks, boolean pread);
458
459    Compression.Algorithm getCompressionAlgorithm();
460
461    /**
462     * Retrieves general Bloom filter metadata as appropriate for each
463     * {@link HFile} version.
464     * Knows nothing about how that metadata is structured.
465     */
466    DataInput getGeneralBloomFilterMetadata() throws IOException;
467
468    /**
469     * Retrieves delete family Bloom filter metadata as appropriate for each
470     * {@link HFile}  version.
471     * Knows nothing about how that metadata is structured.
472     */
473    DataInput getDeleteBloomFilterMetadata() throws IOException;
474
475    Path getPath();
476
477    /** Close method with optional evictOnClose */
478    void close(boolean evictOnClose) throws IOException;
479
480    DataBlockEncoding getDataBlockEncoding();
481
482    boolean hasMVCCInfo();
483
484    /**
485     * Return the file context of the HFile this reader belongs to
486     */
487    HFileContext getFileContext();
488
489    boolean isPrimaryReplicaReader();
490
491    boolean shouldIncludeMemStoreTS();
492
493    boolean isDecodeMemStoreTS();
494
495    DataBlockEncoding getEffectiveEncodingInCache(boolean isCompaction);
496
497    @VisibleForTesting
498    HFileBlock.FSReader getUncachedBlockReader();
499
500    @VisibleForTesting
501    boolean prefetchComplete();
502
503    /**
504     * To close the stream's socket. Note: This can be concurrently called from multiple threads and
505     * implementation should take care of thread safety.
506     */
507    void unbufferStream();
508  }
509
510  /**
511   * Method returns the reader given the specified arguments.
512   * TODO This is a bad abstraction.  See HBASE-6635.
513   *
514   * @param path hfile's path
515   * @param fsdis stream of path's file
516   * @param size max size of the trailer.
517   * @param cacheConf Cache configuation values, cannot be null.
518   * @param hfs
519   * @param primaryReplicaReader true if this is a reader for primary replica
520   * @return an appropriate instance of HFileReader
521   * @throws IOException If file is invalid, will throw CorruptHFileException flavored IOException
522   */
523  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="SF_SWITCH_FALLTHROUGH",
524      justification="Intentional")
525  private static Reader openReader(Path path, FSDataInputStreamWrapper fsdis, long size,
526      CacheConfig cacheConf, HFileSystem hfs, boolean primaryReplicaReader, Configuration conf)
527      throws IOException {
528    FixedFileTrailer trailer = null;
529    try {
530      boolean isHBaseChecksum = fsdis.shouldUseHBaseChecksum();
531      assert !isHBaseChecksum; // Initially we must read with FS checksum.
532      trailer = FixedFileTrailer.readFromStream(fsdis.getStream(isHBaseChecksum), size);
533      switch (trailer.getMajorVersion()) {
534        case 2:
535          LOG.debug("Opening HFile v2 with v3 reader");
536          // Fall through. FindBugs: SF_SWITCH_FALLTHROUGH
537        case 3:
538          return new HFileReaderImpl(path, trailer, fsdis, size, cacheConf, hfs,
539              primaryReplicaReader, conf);
540        default:
541          throw new IllegalArgumentException("Invalid HFile version " + trailer.getMajorVersion());
542      }
543    } catch (Throwable t) {
544      IOUtils.closeQuietly(fsdis);
545      throw new CorruptHFileException("Problem reading HFile Trailer from file " + path, t);
546    } finally {
547      fsdis.unbuffer();
548    }
549  }
550
551  /**
552   * The sockets and the file descriptors held by the method parameter
553   * {@code FSDataInputStreamWrapper} passed will be freed after its usage so caller needs to ensure
554   * that no other threads have access to the same passed reference.
555   * @param fs A file system
556   * @param path Path to HFile
557   * @param fsdis a stream of path's file
558   * @param size max size of the trailer.
559   * @param cacheConf Cache configuration for hfile's contents
560   * @param primaryReplicaReader true if this is a reader for primary replica
561   * @param conf Configuration
562   * @return A version specific Hfile Reader
563   * @throws IOException If file is invalid, will throw CorruptHFileException flavored IOException
564   */
565  public static Reader createReader(FileSystem fs, Path path, FSDataInputStreamWrapper fsdis,
566      long size, CacheConfig cacheConf, boolean primaryReplicaReader, Configuration conf)
567      throws IOException {
568    HFileSystem hfs = null;
569
570    // If the fs is not an instance of HFileSystem, then create an
571    // instance of HFileSystem that wraps over the specified fs.
572    // In this case, we will not be able to avoid checksumming inside
573    // the filesystem.
574    if (!(fs instanceof HFileSystem)) {
575      hfs = new HFileSystem(fs);
576    } else {
577      hfs = (HFileSystem) fs;
578    }
579    return openReader(path, fsdis, size, cacheConf, hfs, primaryReplicaReader, conf);
580  }
581
582  /**
583  * Creates reader with cache configuration disabled
584  * @param fs filesystem
585  * @param path Path to file to read
586  * @return an active Reader instance
587  * @throws IOException Will throw a CorruptHFileException
588  * (DoNotRetryIOException subtype) if hfile is corrupt/invalid.
589  */
590  public static Reader createReader(FileSystem fs, Path path, Configuration conf)
591      throws IOException {
592    // The primaryReplicaReader is mainly used for constructing block cache key, so if we do not use
593    // block cache then it is OK to set it as any value. We use true here.
594    return createReader(fs, path, CacheConfig.DISABLED, true, conf);
595  }
596
597  /**
598   * @param fs filesystem
599   * @param path Path to file to read
600   * @param cacheConf This must not be null. @see
601   *          {@link org.apache.hadoop.hbase.io.hfile.CacheConfig#CacheConfig(Configuration)}
602   * @param primaryReplicaReader true if this is a reader for primary replica
603   * @return an active Reader instance
604   * @throws IOException Will throw a CorruptHFileException (DoNotRetryIOException subtype) if hfile
605   *           is corrupt/invalid.
606   */
607  public static Reader createReader(FileSystem fs, Path path, CacheConfig cacheConf,
608      boolean primaryReplicaReader, Configuration conf) throws IOException {
609    Preconditions.checkNotNull(cacheConf, "Cannot create Reader with null CacheConf");
610    FSDataInputStreamWrapper stream = new FSDataInputStreamWrapper(fs, path);
611    return openReader(path, stream, fs.getFileStatus(path).getLen(), cacheConf,
612      stream.getHfs(), primaryReplicaReader, conf);
613  }
614
615  /**
616   * This factory method is used only by unit tests. <br/>
617   * The sockets and the file descriptors held by the method parameter
618   * {@code FSDataInputStreamWrapper} passed will be freed after its usage so caller needs to ensure
619   * that no other threads have access to the same passed reference.
620   */
621  @VisibleForTesting
622  static Reader createReaderFromStream(Path path, FSDataInputStream fsdis, long size,
623      CacheConfig cacheConf, Configuration conf) throws IOException {
624    FSDataInputStreamWrapper wrapper = new FSDataInputStreamWrapper(fsdis);
625    return openReader(path, wrapper, size, cacheConf, null, true, conf);
626  }
627
628  /**
629   * Returns true if the specified file has a valid HFile Trailer.
630   * @param fs filesystem
631   * @param path Path to file to verify
632   * @return true if the file has a valid HFile Trailer, otherwise false
633   * @throws IOException if failed to read from the underlying stream
634   */
635  public static boolean isHFileFormat(final FileSystem fs, final Path path) throws IOException {
636    return isHFileFormat(fs, fs.getFileStatus(path));
637  }
638
639  /**
640   * Returns true if the specified file has a valid HFile Trailer.
641   * @param fs filesystem
642   * @param fileStatus the file to verify
643   * @return true if the file has a valid HFile Trailer, otherwise false
644   * @throws IOException if failed to read from the underlying stream
645   */
646  public static boolean isHFileFormat(final FileSystem fs, final FileStatus fileStatus)
647      throws IOException {
648    final Path path = fileStatus.getPath();
649    final long size = fileStatus.getLen();
650    try (FSDataInputStreamWrapper fsdis = new FSDataInputStreamWrapper(fs, path)) {
651      boolean isHBaseChecksum = fsdis.shouldUseHBaseChecksum();
652      assert !isHBaseChecksum; // Initially we must read with FS checksum.
653      FixedFileTrailer.readFromStream(fsdis.getStream(isHBaseChecksum), size);
654      return true;
655    } catch (IllegalArgumentException e) {
656      return false;
657    }
658  }
659
660  /**
661   * Metadata for this file. Conjured by the writer. Read in by the reader.
662   */
663  public static class FileInfo implements SortedMap<byte[], byte[]> {
664    static final String RESERVED_PREFIX = "hfile.";
665    static final byte[] RESERVED_PREFIX_BYTES = Bytes.toBytes(RESERVED_PREFIX);
666    static final byte [] LASTKEY = Bytes.toBytes(RESERVED_PREFIX + "LASTKEY");
667    static final byte [] AVG_KEY_LEN = Bytes.toBytes(RESERVED_PREFIX + "AVG_KEY_LEN");
668    static final byte [] AVG_VALUE_LEN = Bytes.toBytes(RESERVED_PREFIX + "AVG_VALUE_LEN");
669    static final byte [] CREATE_TIME_TS = Bytes.toBytes(RESERVED_PREFIX + "CREATE_TIME_TS");
670    static final byte [] COMPARATOR = Bytes.toBytes(RESERVED_PREFIX + "COMPARATOR");
671    static final byte [] TAGS_COMPRESSED = Bytes.toBytes(RESERVED_PREFIX + "TAGS_COMPRESSED");
672    public static final byte [] MAX_TAGS_LEN = Bytes.toBytes(RESERVED_PREFIX + "MAX_TAGS_LEN");
673    private final SortedMap<byte [], byte []> map = new TreeMap<>(Bytes.BYTES_COMPARATOR);
674
675    public FileInfo() {
676      super();
677    }
678
679    /**
680     * Append the given key/value pair to the file info, optionally checking the
681     * key prefix.
682     *
683     * @param k key to add
684     * @param v value to add
685     * @param checkPrefix whether to check that the provided key does not start
686     *          with the reserved prefix
687     * @return this file info object
688     * @throws IOException if the key or value is invalid
689     */
690    public FileInfo append(final byte[] k, final byte[] v,
691        final boolean checkPrefix) throws IOException {
692      if (k == null || v == null) {
693        throw new NullPointerException("Key nor value may be null");
694      }
695      if (checkPrefix && isReservedFileInfoKey(k)) {
696        throw new IOException("Keys with a " + FileInfo.RESERVED_PREFIX
697            + " are reserved");
698      }
699      put(k, v);
700      return this;
701    }
702
703    @Override
704    public void clear() {
705      this.map.clear();
706    }
707
708    @Override
709    public Comparator<? super byte[]> comparator() {
710      return map.comparator();
711    }
712
713    @Override
714    public boolean containsKey(Object key) {
715      return map.containsKey(key);
716    }
717
718    @Override
719    public boolean containsValue(Object value) {
720      return map.containsValue(value);
721    }
722
723    @Override
724    public Set<java.util.Map.Entry<byte[], byte[]>> entrySet() {
725      return map.entrySet();
726    }
727
728    @Override
729    public boolean equals(Object o) {
730      return map.equals(o);
731    }
732
733    @Override
734    public byte[] firstKey() {
735      return map.firstKey();
736    }
737
738    @Override
739    public byte[] get(Object key) {
740      return map.get(key);
741    }
742
743    @Override
744    public int hashCode() {
745      return map.hashCode();
746    }
747
748    @Override
749    public SortedMap<byte[], byte[]> headMap(byte[] toKey) {
750      return this.map.headMap(toKey);
751    }
752
753    @Override
754    public boolean isEmpty() {
755      return map.isEmpty();
756    }
757
758    @Override
759    public Set<byte[]> keySet() {
760      return map.keySet();
761    }
762
763    @Override
764    public byte[] lastKey() {
765      return map.lastKey();
766    }
767
768    @Override
769    public byte[] put(byte[] key, byte[] value) {
770      return this.map.put(key, value);
771    }
772
773    @Override
774    public void putAll(Map<? extends byte[], ? extends byte[]> m) {
775      this.map.putAll(m);
776    }
777
778    @Override
779    public byte[] remove(Object key) {
780      return this.map.remove(key);
781    }
782
783    @Override
784    public int size() {
785      return map.size();
786    }
787
788    @Override
789    public SortedMap<byte[], byte[]> subMap(byte[] fromKey, byte[] toKey) {
790      return this.map.subMap(fromKey, toKey);
791    }
792
793    @Override
794    public SortedMap<byte[], byte[]> tailMap(byte[] fromKey) {
795      return this.map.tailMap(fromKey);
796    }
797
798    @Override
799    public Collection<byte[]> values() {
800      return map.values();
801    }
802
803    /**
804     * Write out this instance on the passed in <code>out</code> stream.
805     * We write it as a protobuf.
806     * @param out
807     * @throws IOException
808     * @see #read(DataInputStream)
809     */
810    void write(final DataOutputStream out) throws IOException {
811      HFileProtos.FileInfoProto.Builder builder = HFileProtos.FileInfoProto.newBuilder();
812      for (Map.Entry<byte [], byte[]> e: this.map.entrySet()) {
813        HBaseProtos.BytesBytesPair.Builder bbpBuilder = HBaseProtos.BytesBytesPair.newBuilder();
814        bbpBuilder.setFirst(UnsafeByteOperations.unsafeWrap(e.getKey()));
815        bbpBuilder.setSecond(UnsafeByteOperations.unsafeWrap(e.getValue()));
816        builder.addMapEntry(bbpBuilder.build());
817      }
818      out.write(ProtobufMagic.PB_MAGIC);
819      builder.build().writeDelimitedTo(out);
820    }
821
822    /**
823     * Populate this instance with what we find on the passed in <code>in</code> stream.
824     * Can deserialize protobuf of old Writables format.
825     * @param in
826     * @throws IOException
827     * @see #write(DataOutputStream)
828     */
829    void read(final DataInputStream in) throws IOException {
830      // This code is tested over in TestHFileReaderV1 where we read an old hfile w/ this new code.
831      int pblen = ProtobufUtil.lengthOfPBMagic();
832      byte [] pbuf = new byte[pblen];
833      if (in.markSupported()) in.mark(pblen);
834      int read = in.read(pbuf);
835      if (read != pblen) throw new IOException("read=" + read + ", wanted=" + pblen);
836      if (ProtobufUtil.isPBMagicPrefix(pbuf)) {
837        parsePB(HFileProtos.FileInfoProto.parseDelimitedFrom(in));
838      } else {
839        if (in.markSupported()) {
840          in.reset();
841          parseWritable(in);
842        } else {
843          // We cannot use BufferedInputStream, it consumes more than we read from the underlying IS
844          ByteArrayInputStream bais = new ByteArrayInputStream(pbuf);
845          SequenceInputStream sis = new SequenceInputStream(bais, in); // Concatenate input streams
846          // TODO: Am I leaking anything here wrapping the passed in stream?  We are not calling close on the wrapped
847          // streams but they should be let go after we leave this context?  I see that we keep a reference to the
848          // passed in inputstream but since we no longer have a reference to this after we leave, we should be ok.
849          parseWritable(new DataInputStream(sis));
850        }
851      }
852    }
853
854    /** Now parse the old Writable format.  It was a list of Map entries.  Each map entry was a key and a value of
855     * a byte [].  The old map format had a byte before each entry that held a code which was short for the key or
856     * value type.  We know it was a byte [] so in below we just read and dump it.
857     * @throws IOException
858     */
859    void parseWritable(final DataInputStream in) throws IOException {
860      // First clear the map.  Otherwise we will just accumulate entries every time this method is called.
861      this.map.clear();
862      // Read the number of entries in the map
863      int entries = in.readInt();
864      // Then read each key/value pair
865      for (int i = 0; i < entries; i++) {
866        byte [] key = Bytes.readByteArray(in);
867        // We used to read a byte that encoded the class type.  Read and ignore it because it is always byte [] in hfile
868        in.readByte();
869        byte [] value = Bytes.readByteArray(in);
870        this.map.put(key, value);
871      }
872    }
873
874    /**
875     * Fill our map with content of the pb we read off disk
876     * @param fip protobuf message to read
877     */
878    void parsePB(final HFileProtos.FileInfoProto fip) {
879      this.map.clear();
880      for (BytesBytesPair pair: fip.getMapEntryList()) {
881        this.map.put(pair.getFirst().toByteArray(), pair.getSecond().toByteArray());
882      }
883    }
884  }
885
886  /** Return true if the given file info key is reserved for internal use. */
887  public static boolean isReservedFileInfoKey(byte[] key) {
888    return Bytes.startsWith(key, FileInfo.RESERVED_PREFIX_BYTES);
889  }
890
891  /**
892   * Get names of supported compression algorithms. The names are acceptable by
893   * HFile.Writer.
894   *
895   * @return Array of strings, each represents a supported compression
896   *         algorithm. Currently, the following compression algorithms are
897   *         supported.
898   *         <ul>
899   *         <li>"none" - No compression.
900   *         <li>"gz" - GZIP compression.
901   *         </ul>
902   */
903  public static String[] getSupportedCompressionAlgorithms() {
904    return Compression.getSupportedAlgorithms();
905  }
906
907  // Utility methods.
908  /*
909   * @param l Long to convert to an int.
910   * @return <code>l</code> cast as an int.
911   */
912  static int longToInt(final long l) {
913    // Expecting the size() of a block not exceeding 4GB. Assuming the
914    // size() will wrap to negative integer if it exceeds 2GB (From tfile).
915    return (int)(l & 0x00000000ffffffffL);
916  }
917
918  /**
919   * Returns all HFiles belonging to the given region directory. Could return an
920   * empty list.
921   *
922   * @param fs  The file system reference.
923   * @param regionDir  The region directory to scan.
924   * @return The list of files found.
925   * @throws IOException When scanning the files fails.
926   */
927  static List<Path> getStoreFiles(FileSystem fs, Path regionDir)
928      throws IOException {
929    List<Path> regionHFiles = new ArrayList<>();
930    PathFilter dirFilter = new FSUtils.DirFilter(fs);
931    FileStatus[] familyDirs = fs.listStatus(regionDir, dirFilter);
932    for(FileStatus dir : familyDirs) {
933      FileStatus[] files = fs.listStatus(dir.getPath());
934      for (FileStatus file : files) {
935        if (!file.isDirectory() &&
936            (!file.getPath().toString().contains(HConstants.HREGION_OLDLOGDIR_NAME)) &&
937            (!file.getPath().toString().contains(HConstants.RECOVERED_EDITS_DIR))) {
938          regionHFiles.add(file.getPath());
939        }
940      }
941    }
942    return regionHFiles;
943  }
944
945  /**
946   * Checks the given {@link HFile} format version, and throws an exception if
947   * invalid. Note that if the version number comes from an input file and has
948   * not been verified, the caller needs to re-throw an {@link IOException} to
949   * indicate that this is not a software error, but corrupted input.
950   *
951   * @param version an HFile version
952   * @throws IllegalArgumentException if the version is invalid
953   */
954  public static void checkFormatVersion(int version)
955      throws IllegalArgumentException {
956    if (version < MIN_FORMAT_VERSION || version > MAX_FORMAT_VERSION) {
957      throw new IllegalArgumentException("Invalid HFile version: " + version
958          + " (expected to be " + "between " + MIN_FORMAT_VERSION + " and "
959          + MAX_FORMAT_VERSION + ")");
960    }
961  }
962
963
964  public static void checkHFileVersion(final Configuration c) {
965    int version = c.getInt(FORMAT_VERSION_KEY, MAX_FORMAT_VERSION);
966    if (version < MAX_FORMAT_VERSION || version > MAX_FORMAT_VERSION) {
967      throw new IllegalArgumentException("The setting for " + FORMAT_VERSION_KEY +
968        " (in your hbase-*.xml files) is " + version + " which does not match " +
969        MAX_FORMAT_VERSION +
970        "; are you running with a configuration from an older or newer hbase install (an " +
971        "incompatible hbase-default.xml or hbase-site.xml on your CLASSPATH)?");
972    }
973  }
974
975  public static void main(String[] args) throws Exception {
976    // delegate to preserve old behavior
977    HFilePrettyPrinter.main(args);
978  }
979}