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   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     /**
353      * Read in a file block.
354      * @param offset offset to read.
355      * @param onDiskBlockSize size of the block
356      * @param cacheBlock
357      * @param pread
358      * @param isCompaction is this block being read as part of a compaction
359      * @param expectedBlockType the block type we are expecting to read with this read operation, or
360      *          null to read whatever block type is available and avoid checking (that might reduce
361      *          caching efficiency of encoded data blocks)
362      * @param expectedDataBlockEncoding the data block encoding the caller is
363      *          expecting data blocks to be in, or null to not perform this
364      *          check and return the block irrespective of the encoding. This
365      *          check only applies to data blocks and can be set to null when
366      *          the caller is expecting to read a non-data block and has set
367      *          expectedBlockType accordingly.
368      * @return Block wrapped in a ByteBuffer.
369      * @throws IOException
370      */
371     HFileBlock readBlock(long offset, long onDiskBlockSize,
372         boolean cacheBlock, final boolean pread, final boolean isCompaction,
373         final boolean updateCacheMetrics, BlockType expectedBlockType,
374         DataBlockEncoding expectedDataBlockEncoding)
375         throws IOException;
376   }
377 
378   /** An interface used by clients to open and iterate an {@link HFile}. */
379   public interface Reader extends Closeable, CachingBlockReader {
380     /**
381      * Returns this reader's "name". Usually the last component of the path.
382      * Needs to be constant as the file is being moved to support caching on
383      * write.
384      */
385     String getName();
386 
387     KVComparator getComparator();
388 
389     HFileScanner getScanner(boolean cacheBlocks,
390        final boolean pread, final boolean isCompaction);
391 
392     ByteBuffer getMetaBlock(String metaBlockName,
393        boolean cacheBlock) throws IOException;
394 
395     Map<byte[], byte[]> loadFileInfo() throws IOException;
396 
397     byte[] getLastKey();
398 
399     byte[] midkey() throws IOException;
400 
401     long length();
402 
403     long getEntries();
404 
405     byte[] getFirstKey();
406 
407     long indexSize();
408 
409     byte[] getFirstRowKey();
410 
411     byte[] getLastRowKey();
412 
413     FixedFileTrailer getTrailer();
414 
415     HFileBlockIndex.BlockIndexReader getDataBlockIndexReader();
416 
417     HFileScanner getScanner(boolean cacheBlocks, boolean pread);
418 
419     Compression.Algorithm getCompressionAlgorithm();
420 
421     /**
422      * Retrieves general Bloom filter metadata as appropriate for each
423      * {@link HFile} version.
424      * Knows nothing about how that metadata is structured.
425      */
426     DataInput getGeneralBloomFilterMetadata() throws IOException;
427 
428     /**
429      * Retrieves delete family Bloom filter metadata as appropriate for each
430      * {@link HFile}  version.
431      * Knows nothing about how that metadata is structured.
432      */
433     DataInput getDeleteBloomFilterMetadata() throws IOException;
434 
435     Path getPath();
436 
437     /** Close method with optional evictOnClose */
438     void close(boolean evictOnClose) throws IOException;
439 
440     DataBlockEncoding getDataBlockEncoding();
441 
442     boolean hasMVCCInfo();
443 
444     /**
445      * Return the file context of the HFile this reader belongs to
446      */
447     HFileContext getFileContext();
448   }
449 
450   /**
451    * Method returns the reader given the specified arguments.
452    * TODO This is a bad abstraction.  See HBASE-6635.
453    *
454    * @param path hfile's path
455    * @param fsdis stream of path's file
456    * @param size max size of the trailer.
457    * @param cacheConf Cache configuation values, cannot be null.
458    * @param hfs
459    * @return an appropriate instance of HFileReader
460    * @throws IOException If file is invalid, will throw CorruptHFileException flavored IOException
461    */
462   private static Reader pickReaderVersion(Path path, FSDataInputStreamWrapper fsdis,
463       long size, CacheConfig cacheConf, HFileSystem hfs, Configuration conf) throws IOException {
464     FixedFileTrailer trailer = null;
465     try {
466       boolean isHBaseChecksum = fsdis.shouldUseHBaseChecksum();
467       assert !isHBaseChecksum; // Initially we must read with FS checksum.
468       trailer = FixedFileTrailer.readFromStream(fsdis.getStream(isHBaseChecksum), size);
469       switch (trailer.getMajorVersion()) {
470       case 2:
471         return new HFileReaderV2(path, trailer, fsdis, size, cacheConf, hfs, conf);
472       case 3 :
473         return new HFileReaderV3(path, trailer, fsdis, size, cacheConf, hfs, conf);
474       default:
475         throw new IllegalArgumentException("Invalid HFile version " + trailer.getMajorVersion());
476       }
477     } catch (Throwable t) {
478       try {
479         fsdis.close();
480       } catch (Throwable t2) {
481         LOG.warn("Error closing fsdis FSDataInputStreamWrapper", t2);
482       }
483       throw new CorruptHFileException("Problem reading HFile Trailer from file " + path, t);
484     }
485   }
486 
487   /**
488    * @param fs A file system
489    * @param path Path to HFile
490    * @param fsdis a stream of path's file
491    * @param size max size of the trailer.
492    * @param cacheConf Cache configuration for hfile's contents
493    * @param conf Configuration
494    * @return A version specific Hfile Reader
495    * @throws IOException If file is invalid, will throw CorruptHFileException flavored IOException
496    */
497   public static Reader createReader(FileSystem fs, Path path,
498       FSDataInputStreamWrapper fsdis, long size, CacheConfig cacheConf, Configuration conf)
499       throws IOException {
500     HFileSystem hfs = null;
501 
502     // If the fs is not an instance of HFileSystem, then create an
503     // instance of HFileSystem that wraps over the specified fs.
504     // In this case, we will not be able to avoid checksumming inside
505     // the filesystem.
506     if (!(fs instanceof HFileSystem)) {
507       hfs = new HFileSystem(fs);
508     } else {
509       hfs = (HFileSystem)fs;
510     }
511     return pickReaderVersion(path, fsdis, size, cacheConf, hfs, conf);
512   }
513 
514   /**
515    *
516    * @param fs filesystem
517    * @param path Path to file to read
518    * @param cacheConf This must not be null.  @see {@link org.apache.hadoop.hbase.io.hfile.CacheConfig#CacheConfig(Configuration)}
519    * @return an active Reader instance
520    * @throws IOException Will throw a CorruptHFileException (DoNotRetryIOException subtype) if hfile is corrupt/invalid.
521    */
522   public static Reader createReader(
523       FileSystem fs, Path path, CacheConfig cacheConf, Configuration conf) throws IOException {
524     Preconditions.checkNotNull(cacheConf, "Cannot create Reader with null CacheConf");
525     FSDataInputStreamWrapper stream = new FSDataInputStreamWrapper(fs, path);
526     return pickReaderVersion(path, stream, fs.getFileStatus(path).getLen(),
527       cacheConf, stream.getHfs(), conf);
528   }
529 
530   /**
531    * This factory method is used only by unit tests
532    */
533   static Reader createReaderFromStream(Path path,
534       FSDataInputStream fsdis, long size, CacheConfig cacheConf, Configuration conf)
535       throws IOException {
536     FSDataInputStreamWrapper wrapper = new FSDataInputStreamWrapper(fsdis);
537     return pickReaderVersion(path, wrapper, size, cacheConf, null, conf);
538   }
539 
540   /**
541    * Metadata for this file. Conjured by the writer. Read in by the reader.
542    */
543   public static class FileInfo implements SortedMap<byte[], byte[]> {
544     static final String RESERVED_PREFIX = "hfile.";
545     static final byte[] RESERVED_PREFIX_BYTES = Bytes.toBytes(RESERVED_PREFIX);
546     static final byte [] LASTKEY = Bytes.toBytes(RESERVED_PREFIX + "LASTKEY");
547     static final byte [] AVG_KEY_LEN = Bytes.toBytes(RESERVED_PREFIX + "AVG_KEY_LEN");
548     static final byte [] AVG_VALUE_LEN = Bytes.toBytes(RESERVED_PREFIX + "AVG_VALUE_LEN");
549     static final byte [] COMPARATOR = Bytes.toBytes(RESERVED_PREFIX + "COMPARATOR");
550     static final byte [] TAGS_COMPRESSED = Bytes.toBytes(RESERVED_PREFIX + "TAGS_COMPRESSED");
551     public static final byte [] MAX_TAGS_LEN = Bytes.toBytes(RESERVED_PREFIX + "MAX_TAGS_LEN");
552     private final SortedMap<byte [], byte []> map = new TreeMap<byte [], byte []>(Bytes.BYTES_COMPARATOR);
553 
554     public FileInfo() {
555       super();
556     }
557 
558     /**
559      * Append the given key/value pair to the file info, optionally checking the
560      * key prefix.
561      *
562      * @param k key to add
563      * @param v value to add
564      * @param checkPrefix whether to check that the provided key does not start
565      *          with the reserved prefix
566      * @return this file info object
567      * @throws IOException if the key or value is invalid
568      */
569     public FileInfo append(final byte[] k, final byte[] v,
570         final boolean checkPrefix) throws IOException {
571       if (k == null || v == null) {
572         throw new NullPointerException("Key nor value may be null");
573       }
574       if (checkPrefix && isReservedFileInfoKey(k)) {
575         throw new IOException("Keys with a " + FileInfo.RESERVED_PREFIX
576             + " are reserved");
577       }
578       put(k, v);
579       return this;
580     }
581 
582     public void clear() {
583       this.map.clear();
584     }
585 
586     public Comparator<? super byte[]> comparator() {
587       return map.comparator();
588     }
589 
590     public boolean containsKey(Object key) {
591       return map.containsKey(key);
592     }
593 
594     public boolean containsValue(Object value) {
595       return map.containsValue(value);
596     }
597 
598     public Set<java.util.Map.Entry<byte[], byte[]>> entrySet() {
599       return map.entrySet();
600     }
601 
602     public boolean equals(Object o) {
603       return map.equals(o);
604     }
605 
606     public byte[] firstKey() {
607       return map.firstKey();
608     }
609 
610     public byte[] get(Object key) {
611       return map.get(key);
612     }
613 
614     public int hashCode() {
615       return map.hashCode();
616     }
617 
618     public SortedMap<byte[], byte[]> headMap(byte[] toKey) {
619       return this.map.headMap(toKey);
620     }
621 
622     public boolean isEmpty() {
623       return map.isEmpty();
624     }
625 
626     public Set<byte[]> keySet() {
627       return map.keySet();
628     }
629 
630     public byte[] lastKey() {
631       return map.lastKey();
632     }
633 
634     public byte[] put(byte[] key, byte[] value) {
635       return this.map.put(key, value);
636     }
637 
638     public void putAll(Map<? extends byte[], ? extends byte[]> m) {
639       this.map.putAll(m);
640     }
641 
642     public byte[] remove(Object key) {
643       return this.map.remove(key);
644     }
645 
646     public int size() {
647       return map.size();
648     }
649 
650     public SortedMap<byte[], byte[]> subMap(byte[] fromKey, byte[] toKey) {
651       return this.map.subMap(fromKey, toKey);
652     }
653 
654     public SortedMap<byte[], byte[]> tailMap(byte[] fromKey) {
655       return this.map.tailMap(fromKey);
656     }
657 
658     public Collection<byte[]> values() {
659       return map.values();
660     }
661 
662     /**
663      * Write out this instance on the passed in <code>out</code> stream.
664      * We write it as a protobuf.
665      * @param out
666      * @throws IOException
667      * @see #read(DataInputStream)
668      */
669     void write(final DataOutputStream out) throws IOException {
670       HFileProtos.FileInfoProto.Builder builder = HFileProtos.FileInfoProto.newBuilder();
671       for (Map.Entry<byte [], byte[]> e: this.map.entrySet()) {
672         HBaseProtos.BytesBytesPair.Builder bbpBuilder = HBaseProtos.BytesBytesPair.newBuilder();
673         bbpBuilder.setFirst(ByteStringer.wrap(e.getKey()));
674         bbpBuilder.setSecond(ByteStringer.wrap(e.getValue()));
675         builder.addMapEntry(bbpBuilder.build());
676       }
677       out.write(ProtobufUtil.PB_MAGIC);
678       builder.build().writeDelimitedTo(out);
679     }
680 
681     /**
682      * Populate this instance with what we find on the passed in <code>in</code> stream.
683      * Can deserialize protobuf of old Writables format.
684      * @param in
685      * @throws IOException
686      * @see #write(DataOutputStream)
687      */
688     void read(final DataInputStream in) throws IOException {
689       // This code is tested over in TestHFileReaderV1 where we read an old hfile w/ this new code.
690       int pblen = ProtobufUtil.lengthOfPBMagic();
691       byte [] pbuf = new byte[pblen];
692       if (in.markSupported()) in.mark(pblen);
693       int read = in.read(pbuf);
694       if (read != pblen) throw new IOException("read=" + read + ", wanted=" + pblen);
695       if (ProtobufUtil.isPBMagicPrefix(pbuf)) {
696         parsePB(HFileProtos.FileInfoProto.parseDelimitedFrom(in));
697       } else {
698         if (in.markSupported()) {
699           in.reset();
700           parseWritable(in);
701         } else {
702           // We cannot use BufferedInputStream, it consumes more than we read from the underlying IS
703           ByteArrayInputStream bais = new ByteArrayInputStream(pbuf);
704           SequenceInputStream sis = new SequenceInputStream(bais, in); // Concatenate input streams
705           // TODO: Am I leaking anything here wrapping the passed in stream?  We are not calling close on the wrapped
706           // streams but they should be let go after we leave this context?  I see that we keep a reference to the
707           // passed in inputstream but since we no longer have a reference to this after we leave, we should be ok.
708           parseWritable(new DataInputStream(sis));
709         }
710       }
711     }
712 
713     /** Now parse the old Writable format.  It was a list of Map entries.  Each map entry was a key and a value of
714      * a byte [].  The old map format had a byte before each entry that held a code which was short for the key or
715      * value type.  We know it was a byte [] so in below we just read and dump it.
716      * @throws IOException
717      */
718     void parseWritable(final DataInputStream in) throws IOException {
719       // First clear the map.  Otherwise we will just accumulate entries every time this method is called.
720       this.map.clear();
721       // Read the number of entries in the map
722       int entries = in.readInt();
723       // Then read each key/value pair
724       for (int i = 0; i < entries; i++) {
725         byte [] key = Bytes.readByteArray(in);
726         // We used to read a byte that encoded the class type.  Read and ignore it because it is always byte [] in hfile
727         in.readByte();
728         byte [] value = Bytes.readByteArray(in);
729         this.map.put(key, value);
730       }
731     }
732 
733     /**
734      * Fill our map with content of the pb we read off disk
735      * @param fip protobuf message to read
736      */
737     void parsePB(final HFileProtos.FileInfoProto fip) {
738       this.map.clear();
739       for (BytesBytesPair pair: fip.getMapEntryList()) {
740         this.map.put(pair.getFirst().toByteArray(), pair.getSecond().toByteArray());
741       }
742     }
743   }
744 
745   /** Return true if the given file info key is reserved for internal use. */
746   public static boolean isReservedFileInfoKey(byte[] key) {
747     return Bytes.startsWith(key, FileInfo.RESERVED_PREFIX_BYTES);
748   }
749 
750   /**
751    * Get names of supported compression algorithms. The names are acceptable by
752    * HFile.Writer.
753    *
754    * @return Array of strings, each represents a supported compression
755    *         algorithm. Currently, the following compression algorithms are
756    *         supported.
757    *         <ul>
758    *         <li>"none" - No compression.
759    *         <li>"gz" - GZIP compression.
760    *         </ul>
761    */
762   public static String[] getSupportedCompressionAlgorithms() {
763     return Compression.getSupportedAlgorithms();
764   }
765 
766   // Utility methods.
767   /*
768    * @param l Long to convert to an int.
769    * @return <code>l</code> cast as an int.
770    */
771   static int longToInt(final long l) {
772     // Expecting the size() of a block not exceeding 4GB. Assuming the
773     // size() will wrap to negative integer if it exceeds 2GB (From tfile).
774     return (int)(l & 0x00000000ffffffffL);
775   }
776 
777   /**
778    * Returns all files belonging to the given region directory. Could return an
779    * empty list.
780    *
781    * @param fs  The file system reference.
782    * @param regionDir  The region directory to scan.
783    * @return The list of files found.
784    * @throws IOException When scanning the files fails.
785    */
786   static List<Path> getStoreFiles(FileSystem fs, Path regionDir)
787       throws IOException {
788     List<Path> res = new ArrayList<Path>();
789     PathFilter dirFilter = new FSUtils.DirFilter(fs);
790     FileStatus[] familyDirs = fs.listStatus(regionDir, dirFilter);
791     for(FileStatus dir : familyDirs) {
792       FileStatus[] files = fs.listStatus(dir.getPath());
793       for (FileStatus file : files) {
794         if (!file.isDirectory()) {
795           res.add(file.getPath());
796         }
797       }
798     }
799     return res;
800   }
801 
802   public static void main(String[] args) throws IOException {
803     HFilePrettyPrinter prettyPrinter = new HFilePrettyPrinter();
804     System.exit(prettyPrinter.run(args));
805   }
806 
807   /**
808    * Checks the given {@link HFile} format version, and throws an exception if
809    * invalid. Note that if the version number comes from an input file and has
810    * not been verified, the caller needs to re-throw an {@link IOException} to
811    * indicate that this is not a software error, but corrupted input.
812    *
813    * @param version an HFile version
814    * @throws IllegalArgumentException if the version is invalid
815    */
816   public static void checkFormatVersion(int version)
817       throws IllegalArgumentException {
818     if (version < MIN_FORMAT_VERSION || version > MAX_FORMAT_VERSION) {
819       throw new IllegalArgumentException("Invalid HFile version: " + version
820           + " (expected to be " + "between " + MIN_FORMAT_VERSION + " and "
821           + MAX_FORMAT_VERSION + ")");
822     }
823   }
824 }