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