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