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