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