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