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