View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.io.hfile;
19  
20  import java.io.ByteArrayOutputStream;
21  import java.io.DataInputStream;
22  import java.io.DataOutput;
23  import java.io.DataOutputStream;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.nio.ByteBuffer;
27  import java.util.concurrent.locks.Lock;
28  import java.util.concurrent.locks.ReentrantLock;
29  
30  import org.apache.hadoop.fs.FSDataInputStream;
31  import org.apache.hadoop.fs.FSDataOutputStream;
32  import org.apache.hadoop.fs.Path;
33  import org.apache.hadoop.hbase.Cell;
34  import org.apache.hadoop.hbase.HConstants;
35  import org.apache.hadoop.hbase.classification.InterfaceAudience;
36  import org.apache.hadoop.hbase.fs.HFileSystem;
37  import org.apache.hadoop.hbase.io.ByteBufferInputStream;
38  import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
39  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
40  import org.apache.hadoop.hbase.io.encoding.HFileBlockDecodingContext;
41  import org.apache.hadoop.hbase.io.encoding.HFileBlockDefaultDecodingContext;
42  import org.apache.hadoop.hbase.io.encoding.HFileBlockDefaultEncodingContext;
43  import org.apache.hadoop.hbase.io.encoding.HFileBlockEncodingContext;
44  import org.apache.hadoop.hbase.util.ByteBufferUtils;
45  import org.apache.hadoop.hbase.util.Bytes;
46  import org.apache.hadoop.hbase.util.ChecksumType;
47  import org.apache.hadoop.hbase.util.ClassSize;
48  import org.apache.hadoop.io.IOUtils;
49  
50  import com.google.common.base.Preconditions;
51  
52  /**
53   * Reading {@link HFile} version 1 and 2 blocks, and writing version 2 blocks.
54   * <ul>
55   * <li>In version 1 all blocks are always compressed or uncompressed, as
56   * specified by the {@link HFile}'s compression algorithm, with a type-specific
57   * magic record stored in the beginning of the compressed data (i.e. one needs
58   * to uncompress the compressed block to determine the block type). There is
59   * only a single compression algorithm setting for all blocks. Offset and size
60   * information from the block index are required to read a block.
61   * <li>In version 2 a block is structured as follows:
62   * <ul>
63   * <li>header (see Writer#finishBlock())
64   * <ul>
65   * <li>Magic record identifying the block type (8 bytes)
66   * <li>Compressed block size, excluding header, including checksum (4 bytes)
67   * <li>Uncompressed block size, excluding header, excluding checksum (4 bytes)
68   * <li>The offset of the previous block of the same type (8 bytes). This is
69   * used to be able to navigate to the previous block without going to the block
70   * <li>For minorVersions >=1, the ordinal describing checksum type (1 byte)
71   * <li>For minorVersions >=1, the number of data bytes/checksum chunk (4 bytes)
72   * <li>For minorVersions >=1, the size of data on disk, including header,
73   * excluding checksums (4 bytes)
74   * </ul>
75   * </li>
76   * <li>Raw/Compressed/Encrypted/Encoded data. The compression algorithm is the
77   * same for all the blocks in the {@link HFile}, similarly to what was done in
78   * version 1.
79   * <li>For minorVersions >=1, a series of 4 byte checksums, one each for
80   * the number of bytes specified by bytesPerChecksum.
81   * </ul>
82   * </ul>
83   */
84  @InterfaceAudience.Private
85  public class HFileBlock implements Cacheable {
86  
87    /**
88     * On a checksum failure on a Reader, these many suceeding read
89     * requests switch back to using hdfs checksums before auto-reenabling
90     * hbase checksum verification.
91     */
92    static final int CHECKSUM_VERIFICATION_NUM_IO_THRESHOLD = 3;
93  
94    public static final boolean FILL_HEADER = true;
95    public static final boolean DONT_FILL_HEADER = false;
96  
97    /**
98     * The size of block header when blockType is {@link BlockType#ENCODED_DATA}.
99     * This extends normal header by adding the id of encoder.
100    */
101   public static final int ENCODED_HEADER_SIZE = HConstants.HFILEBLOCK_HEADER_SIZE
102       + DataBlockEncoding.ID_SIZE;
103 
104   static final byte[] DUMMY_HEADER_NO_CHECKSUM =
105      new byte[HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM];
106 
107   public static final int BYTE_BUFFER_HEAP_SIZE = (int) ClassSize.estimateBase(
108       ByteBuffer.wrap(new byte[0], 0, 0).getClass(), false);
109 
110   // meta.usesHBaseChecksum+offset+nextBlockOnDiskSizeWithHeader
111   public static final int EXTRA_SERIALIZATION_SPACE = Bytes.SIZEOF_BYTE + Bytes.SIZEOF_INT
112       + Bytes.SIZEOF_LONG;
113 
114   /**
115    * Each checksum value is an integer that can be stored in 4 bytes.
116    */
117   static final int CHECKSUM_SIZE = Bytes.SIZEOF_INT;
118 
119   private static final CacheableDeserializer<Cacheable> blockDeserializer =
120       new CacheableDeserializer<Cacheable>() {
121         public HFileBlock deserialize(ByteBuffer buf, boolean reuse) throws IOException{
122           buf.limit(buf.limit() - HFileBlock.EXTRA_SERIALIZATION_SPACE).rewind();
123           ByteBuffer newByteBuffer;
124           if (reuse) {
125             newByteBuffer = buf.slice();
126           } else {
127            newByteBuffer = ByteBuffer.allocate(buf.limit());
128            newByteBuffer.put(buf);
129           }
130           buf.position(buf.limit());
131           buf.limit(buf.limit() + HFileBlock.EXTRA_SERIALIZATION_SPACE);
132           boolean usesChecksum = buf.get() == (byte)1;
133           HFileBlock ourBuffer = new HFileBlock(newByteBuffer, usesChecksum);
134           ourBuffer.offset = buf.getLong();
135           ourBuffer.nextBlockOnDiskSizeWithHeader = buf.getInt();
136           if (ourBuffer.hasNextBlockHeader()) {
137             ourBuffer.buf.limit(ourBuffer.buf.limit() - ourBuffer.headerSize());
138           }
139           return ourBuffer;
140         }
141 
142         @Override
143         public int getDeserialiserIdentifier() {
144           return deserializerIdentifier;
145         }
146 
147         @Override
148         public HFileBlock deserialize(ByteBuffer b) throws IOException {
149           return deserialize(b, false);
150         }
151       };
152   private static final int deserializerIdentifier;
153   static {
154     deserializerIdentifier = CacheableDeserializerIdManager
155         .registerDeserializer(blockDeserializer);
156   }
157 
158   /** Type of block. Header field 0. */
159   private BlockType blockType;
160 
161   /** Size on disk excluding header, including checksum. Header field 1. */
162   private int onDiskSizeWithoutHeader;
163 
164   /** Size of pure data. Does not include header or checksums. Header field 2. */
165   private final int uncompressedSizeWithoutHeader;
166 
167   /** The offset of the previous block on disk. Header field 3. */
168   private final long prevBlockOffset;
169 
170   /**
171    * Size on disk of header + data. Excludes checksum. Header field 6,
172    * OR calculated from {@link #onDiskSizeWithoutHeader} when using HDFS checksum.
173    */
174   private final int onDiskDataSizeWithHeader;
175 
176   /** The in-memory representation of the hfile block */
177   private ByteBuffer buf;
178 
179   /** Meta data that holds meta information on the hfileblock */
180   private HFileContext fileContext;
181 
182   /**
183    * The offset of this block in the file. Populated by the reader for
184    * convenience of access. This offset is not part of the block header.
185    */
186   private long offset = -1;
187 
188   /**
189    * The on-disk size of the next block, including the header, obtained by
190    * peeking into the first {@link HConstants#HFILEBLOCK_HEADER_SIZE} bytes of the next block's
191    * header, or -1 if unknown.
192    */
193   private int nextBlockOnDiskSizeWithHeader = -1;
194 
195   /**
196    * Creates a new {@link HFile} block from the given fields. This constructor
197    * is mostly used when the block data has already been read and uncompressed,
198    * and is sitting in a byte buffer.
199    *
200    * @param blockType the type of this block, see {@link BlockType}
201    * @param onDiskSizeWithoutHeader see {@link #onDiskSizeWithoutHeader}
202    * @param uncompressedSizeWithoutHeader see {@link #uncompressedSizeWithoutHeader}
203    * @param prevBlockOffset see {@link #prevBlockOffset}
204    * @param buf block header ({@link HConstants#HFILEBLOCK_HEADER_SIZE} bytes) followed by
205    *          uncompressed data. This
206    * @param fillHeader when true, parse {@code buf} and override the first 4 header fields.
207    * @param offset the file offset the block was read from
208    * @param onDiskDataSizeWithHeader see {@link #onDiskDataSizeWithHeader}
209    * @param fileContext HFile meta data
210    */
211   HFileBlock(BlockType blockType, int onDiskSizeWithoutHeader, int uncompressedSizeWithoutHeader,
212       long prevBlockOffset, ByteBuffer buf, boolean fillHeader, long offset,
213       int onDiskDataSizeWithHeader, HFileContext fileContext) {
214     this.blockType = blockType;
215     this.onDiskSizeWithoutHeader = onDiskSizeWithoutHeader;
216     this.uncompressedSizeWithoutHeader = uncompressedSizeWithoutHeader;
217     this.prevBlockOffset = prevBlockOffset;
218     this.buf = buf;
219     if (fillHeader)
220       overwriteHeader();
221     this.offset = offset;
222     this.onDiskDataSizeWithHeader = onDiskDataSizeWithHeader;
223     this.fileContext = fileContext;
224     this.buf.rewind();
225   }
226 
227   /**
228    * Copy constructor. Creates a shallow copy of {@code that}'s buffer.
229    */
230   HFileBlock(HFileBlock that) {
231     this.blockType = that.blockType;
232     this.onDiskSizeWithoutHeader = that.onDiskSizeWithoutHeader;
233     this.uncompressedSizeWithoutHeader = that.uncompressedSizeWithoutHeader;
234     this.prevBlockOffset = that.prevBlockOffset;
235     this.buf = that.buf.duplicate();
236     this.offset = that.offset;
237     this.onDiskDataSizeWithHeader = that.onDiskDataSizeWithHeader;
238     this.fileContext = that.fileContext;
239     this.nextBlockOnDiskSizeWithHeader = that.nextBlockOnDiskSizeWithHeader;
240   }
241 
242   /**
243    * Creates a block from an existing buffer starting with a header. Rewinds
244    * and takes ownership of the buffer. By definition of rewind, ignores the
245    * buffer position, but if you slice the buffer beforehand, it will rewind
246    * to that point. The reason this has a minorNumber and not a majorNumber is
247    * because majorNumbers indicate the format of a HFile whereas minorNumbers
248    * indicate the format inside a HFileBlock.
249    */
250   HFileBlock(ByteBuffer b, boolean usesHBaseChecksum) throws IOException {
251     b.rewind();
252     blockType = BlockType.read(b);
253     onDiskSizeWithoutHeader = b.getInt();
254     uncompressedSizeWithoutHeader = b.getInt();
255     prevBlockOffset = b.getLong();
256     HFileContextBuilder contextBuilder = new HFileContextBuilder();
257     contextBuilder.withHBaseCheckSum(usesHBaseChecksum);
258     if (usesHBaseChecksum) {
259       contextBuilder.withChecksumType(ChecksumType.codeToType(b.get()));
260       contextBuilder.withBytesPerCheckSum(b.getInt());
261       this.onDiskDataSizeWithHeader = b.getInt();
262     } else {
263       contextBuilder.withChecksumType(ChecksumType.NULL);
264       contextBuilder.withBytesPerCheckSum(0);
265       this.onDiskDataSizeWithHeader = onDiskSizeWithoutHeader +
266                                        HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM;
267     }
268     this.fileContext = contextBuilder.build();
269     buf = b;
270     buf.rewind();
271   }
272 
273   public BlockType getBlockType() {
274     return blockType;
275   }
276 
277   /** @return get data block encoding id that was used to encode this block */
278   public short getDataBlockEncodingId() {
279     if (blockType != BlockType.ENCODED_DATA) {
280       throw new IllegalArgumentException("Querying encoder ID of a block " +
281           "of type other than " + BlockType.ENCODED_DATA + ": " + blockType);
282     }
283     return buf.getShort(headerSize());
284   }
285 
286   /**
287    * @return the on-disk size of header + data part + checksum.
288    */
289   public int getOnDiskSizeWithHeader() {
290     return onDiskSizeWithoutHeader + headerSize();
291   }
292 
293   /**
294    * @return the on-disk size of the data part + checksum (header excluded).
295    */
296   public int getOnDiskSizeWithoutHeader() {
297     return onDiskSizeWithoutHeader;
298   }
299 
300   /**
301    * @return the uncompressed size of data part (header and checksum excluded).
302    */
303    public int getUncompressedSizeWithoutHeader() {
304     return uncompressedSizeWithoutHeader;
305   }
306 
307   /**
308    * @return the offset of the previous block of the same type in the file, or
309    *         -1 if unknown
310    */
311   public long getPrevBlockOffset() {
312     return prevBlockOffset;
313   }
314 
315   /**
316    * Rewinds {@code buf} and writes first 4 header fields. {@code buf} position
317    * is modified as side-effect.
318    */
319   private void overwriteHeader() {
320     buf.rewind();
321     blockType.write(buf);
322     buf.putInt(onDiskSizeWithoutHeader);
323     buf.putInt(uncompressedSizeWithoutHeader);
324     buf.putLong(prevBlockOffset);
325   }
326 
327   /**
328    * Returns a buffer that does not include the header or checksum.
329    *
330    * @return the buffer with header skipped and checksum omitted.
331    */
332   public ByteBuffer getBufferWithoutHeader() {
333     ByteBuffer dup = this.buf.duplicate();
334     dup.position(headerSize());
335     dup.limit(buf.limit() - totalChecksumBytes());
336     return dup.slice();
337   }
338 
339   /**
340    * Returns the buffer this block stores internally. The clients must not
341    * modify the buffer object. This method has to be public because it is
342    * used in {@link org.apache.hadoop.hbase.util.CompoundBloomFilter} to avoid object
343    *  creation on every Bloom filter lookup, but has to be used with caution.
344    *   Checksum data is not included in the returned buffer but header data is.
345    *
346    * @return the buffer of this block for read-only operations
347    */
348   public ByteBuffer getBufferReadOnly() {
349     ByteBuffer dup = this.buf.duplicate();
350     dup.limit(buf.limit() - totalChecksumBytes());
351     return dup.slice();
352   }
353 
354   /**
355    * Returns the buffer of this block, including header data. The clients must
356    * not modify the buffer object. This method has to be public because it is
357    * used in {@link org.apache.hadoop.hbase.io.hfile.bucket.BucketCache} to avoid buffer copy.
358    *
359    * @return the buffer with header and checksum included for read-only operations
360    */
361   public ByteBuffer getBufferReadOnlyWithHeader() {
362     ByteBuffer dup = this.buf.duplicate();
363     return dup.slice();
364   }
365 
366   /**
367    * Returns a byte buffer of this block, including header data and checksum, positioned at
368    * the beginning of header. The underlying data array is not copied.
369    *
370    * @return the byte buffer with header and checksum included
371    */
372   ByteBuffer getBufferWithHeader() {
373     ByteBuffer dupBuf = buf.duplicate();
374     dupBuf.rewind();
375     return dupBuf;
376   }
377 
378   private void sanityCheckAssertion(long valueFromBuf, long valueFromField,
379       String fieldName) throws IOException {
380     if (valueFromBuf != valueFromField) {
381       throw new AssertionError(fieldName + " in the buffer (" + valueFromBuf
382           + ") is different from that in the field (" + valueFromField + ")");
383     }
384   }
385 
386   private void sanityCheckAssertion(BlockType valueFromBuf, BlockType valueFromField)
387       throws IOException {
388     if (valueFromBuf != valueFromField) {
389       throw new IOException("Block type stored in the buffer: " +
390         valueFromBuf + ", block type field: " + valueFromField);
391     }
392   }
393 
394   /**
395    * Checks if the block is internally consistent, i.e. the first
396    * {@link HConstants#HFILEBLOCK_HEADER_SIZE} bytes of the buffer contain a
397    * valid header consistent with the fields. Assumes a packed block structure.
398    * This function is primary for testing and debugging, and is not
399    * thread-safe, because it alters the internal buffer pointer.
400    */
401   void sanityCheck() throws IOException {
402     buf.rewind();
403 
404     sanityCheckAssertion(BlockType.read(buf), blockType);
405 
406     sanityCheckAssertion(buf.getInt(), onDiskSizeWithoutHeader,
407         "onDiskSizeWithoutHeader");
408 
409     sanityCheckAssertion(buf.getInt(), uncompressedSizeWithoutHeader,
410         "uncompressedSizeWithoutHeader");
411 
412     sanityCheckAssertion(buf.getLong(), prevBlockOffset, "prevBlocKOffset");
413     if (this.fileContext.isUseHBaseChecksum()) {
414       sanityCheckAssertion(buf.get(), this.fileContext.getChecksumType().getCode(), "checksumType");
415       sanityCheckAssertion(buf.getInt(), this.fileContext.getBytesPerChecksum(), "bytesPerChecksum");
416       sanityCheckAssertion(buf.getInt(), onDiskDataSizeWithHeader, "onDiskDataSizeWithHeader");
417     }
418 
419     int cksumBytes = totalChecksumBytes();
420     int expectedBufLimit = onDiskDataSizeWithHeader + cksumBytes;
421     if (buf.limit() != expectedBufLimit) {
422       throw new AssertionError("Expected buffer limit " + expectedBufLimit
423           + ", got " + buf.limit());
424     }
425 
426     // We might optionally allocate HFILEBLOCK_HEADER_SIZE more bytes to read the next
427     // block's header, so there are two sensible values for buffer capacity.
428     int hdrSize = headerSize();
429     if (buf.capacity() != expectedBufLimit &&
430         buf.capacity() != expectedBufLimit + hdrSize) {
431       throw new AssertionError("Invalid buffer capacity: " + buf.capacity() +
432           ", expected " + expectedBufLimit + " or " + (expectedBufLimit + hdrSize));
433     }
434   }
435 
436   @Override
437   public String toString() {
438     StringBuilder sb = new StringBuilder()
439       .append("HFileBlock [")
440       .append(" fileOffset=").append(offset)
441       .append(" headerSize()=").append(headerSize())
442       .append(" blockType=").append(blockType)
443       .append(" onDiskSizeWithoutHeader=").append(onDiskSizeWithoutHeader)
444       .append(" uncompressedSizeWithoutHeader=").append(uncompressedSizeWithoutHeader)
445       .append(" prevBlockOffset=").append(prevBlockOffset)
446       .append(" isUseHBaseChecksum()=").append(fileContext.isUseHBaseChecksum());
447     if (fileContext.isUseHBaseChecksum()) {
448       sb.append(" checksumType=").append(ChecksumType.codeToType(this.buf.get(24)))
449         .append(" bytesPerChecksum=").append(this.buf.getInt(24 + 1))
450         .append(" onDiskDataSizeWithHeader=").append(onDiskDataSizeWithHeader);
451     } else {
452       sb.append(" onDiskDataSizeWithHeader=").append(onDiskDataSizeWithHeader)
453         .append("(").append(onDiskSizeWithoutHeader)
454         .append("+").append(HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM).append(")");
455     }
456     String dataBegin = null;
457     if (buf.hasArray()) {
458       dataBegin = Bytes.toStringBinary(buf.array(), buf.arrayOffset() + headerSize(),
459           Math.min(32, buf.limit() - buf.arrayOffset() - headerSize()));
460     } else {
461       ByteBuffer bufWithoutHeader = getBufferWithoutHeader();
462       byte[] dataBeginBytes = new byte[Math.min(32,
463           bufWithoutHeader.limit() - bufWithoutHeader.position())];
464       bufWithoutHeader.get(dataBeginBytes);
465       dataBegin = Bytes.toStringBinary(dataBeginBytes);
466     }
467     sb.append(" getOnDiskSizeWithHeader()=").append(getOnDiskSizeWithHeader())
468       .append(" totalChecksumBytes()=").append(totalChecksumBytes())
469       .append(" isUnpacked()=").append(isUnpacked())
470       .append(" buf=[ ").append(buf).append(" ]")
471       .append(" dataBeginsWith=").append(dataBegin)
472       .append(" fileContext=").append(fileContext)
473       .append(" ]");
474     return sb.toString();
475   }
476 
477   /**
478    * Called after reading a block with provided onDiskSizeWithHeader.
479    */
480   private void validateOnDiskSizeWithoutHeader(int expectedOnDiskSizeWithoutHeader)
481   throws IOException {
482     if (onDiskSizeWithoutHeader != expectedOnDiskSizeWithoutHeader) {
483       String dataBegin = null;
484       if (buf.hasArray()) {
485         dataBegin = Bytes.toStringBinary(buf.array(), buf.arrayOffset(), Math.min(32, buf.limit()));
486       } else {
487         ByteBuffer bufDup = getBufferReadOnly();
488         byte[] dataBeginBytes = new byte[Math.min(32, bufDup.limit() - bufDup.position())];
489         bufDup.get(dataBeginBytes);
490         dataBegin = Bytes.toStringBinary(dataBeginBytes);
491       }
492       String blockInfoMsg =
493         "Block offset: " + offset + ", data starts with: " + dataBegin;
494       throw new IOException("On-disk size without header provided is "
495           + expectedOnDiskSizeWithoutHeader + ", but block "
496           + "header contains " + onDiskSizeWithoutHeader + ". " +
497           blockInfoMsg);
498     }
499   }
500 
501   /**
502    * Retrieves the decompressed/decrypted view of this block. An encoded block remains in its
503    * encoded structure. Internal structures are shared between instances where applicable.
504    */
505   HFileBlock unpack(HFileContext fileContext, FSReader reader) throws IOException {
506     if (!fileContext.isCompressedOrEncrypted()) {
507       // TODO: cannot use our own fileContext here because HFileBlock(ByteBuffer, boolean),
508       // which is used for block serialization to L2 cache, does not preserve encoding and
509       // encryption details.
510       return this;
511     }
512 
513     HFileBlock unpacked = new HFileBlock(this);
514     unpacked.allocateBuffer(); // allocates space for the decompressed block
515 
516     HFileBlockDecodingContext ctx = blockType == BlockType.ENCODED_DATA ?
517       reader.getBlockDecodingContext() : reader.getDefaultBlockDecodingContext();
518 
519     ByteBuffer dup = this.buf.duplicate();
520     dup.position(this.headerSize());
521     dup = dup.slice();
522     ctx.prepareDecoding(unpacked.getOnDiskSizeWithoutHeader(),
523       unpacked.getUncompressedSizeWithoutHeader(), unpacked.getBufferWithoutHeader(),
524       dup);
525 
526     // Preserve the next block's header bytes in the new block if we have them.
527     if (unpacked.hasNextBlockHeader()) {
528       // Both the buffers are limited till checksum bytes and avoid the next block's header.
529       // Below call to copyFromBufferToBuffer() will try positional read/write from/to buffers when
530       // any of the buffer is DBB. So we change the limit on a dup buffer. No copying just create
531       // new BB objects
532       ByteBuffer inDup = this.buf.duplicate();
533       inDup.limit(inDup.limit() + headerSize());
534       ByteBuffer outDup = unpacked.buf.duplicate();
535       outDup.limit(outDup.limit() + unpacked.headerSize());
536       ByteBufferUtils.copyFromBufferToBuffer(
537           outDup,
538           inDup,
539           this.onDiskDataSizeWithHeader,
540           unpacked.headerSize() + unpacked.uncompressedSizeWithoutHeader
541               + unpacked.totalChecksumBytes(), unpacked.headerSize());
542     }
543     return unpacked;
544   }
545 
546   /**
547    * Return true when this buffer includes next block's header.
548    */
549   private boolean hasNextBlockHeader() {
550     return nextBlockOnDiskSizeWithHeader > 0;
551   }
552 
553   /**
554    * Always allocates a new buffer of the correct size. Copies header bytes
555    * from the existing buffer. Does not change header fields.
556    * Reserve room to keep checksum bytes too.
557    */
558   private void allocateBuffer() {
559     int cksumBytes = totalChecksumBytes();
560     int headerSize = headerSize();
561     int capacityNeeded = headerSize + uncompressedSizeWithoutHeader +
562         cksumBytes + (hasNextBlockHeader() ? headerSize : 0);
563 
564     // TODO we need consider allocating offheap here?
565     ByteBuffer newBuf = ByteBuffer.allocate(capacityNeeded);
566 
567     // Copy header bytes into newBuf.
568     // newBuf is HBB so no issue in calling array()
569     ByteBuffer dup = buf.duplicate();
570     dup.position(0);
571     dup.get(newBuf.array(), newBuf.arrayOffset(), headerSize);
572 
573     buf = newBuf;
574     // set limit to exclude next block's header
575     buf.limit(headerSize + uncompressedSizeWithoutHeader + cksumBytes);
576   }
577 
578   /**
579    * Return true when this block's buffer has been unpacked, false otherwise. Note this is a
580    * calculated heuristic, not tracked attribute of the block.
581    */
582   public boolean isUnpacked() {
583     final int cksumBytes = totalChecksumBytes();
584     final int headerSize = headerSize();
585     final int expectedCapacity = headerSize + uncompressedSizeWithoutHeader + cksumBytes;
586     final int bufCapacity = buf.capacity();
587     return bufCapacity == expectedCapacity || bufCapacity == expectedCapacity + headerSize;
588   }
589 
590   /** An additional sanity-check in case no compression or encryption is being used. */
591   public void assumeUncompressed() throws IOException {
592     if (onDiskSizeWithoutHeader != uncompressedSizeWithoutHeader +
593         totalChecksumBytes()) {
594       throw new IOException("Using no compression but "
595           + "onDiskSizeWithoutHeader=" + onDiskSizeWithoutHeader + ", "
596           + "uncompressedSizeWithoutHeader=" + uncompressedSizeWithoutHeader
597           + ", numChecksumbytes=" + totalChecksumBytes());
598     }
599   }
600 
601   /**
602    * @param expectedType the expected type of this block
603    * @throws IOException if this block's type is different than expected
604    */
605   public void expectType(BlockType expectedType) throws IOException {
606     if (blockType != expectedType) {
607       throw new IOException("Invalid block type: expected=" + expectedType
608           + ", actual=" + blockType);
609     }
610   }
611 
612   /** @return the offset of this block in the file it was read from */
613   public long getOffset() {
614     if (offset < 0) {
615       throw new IllegalStateException(
616           "HFile block offset not initialized properly");
617     }
618     return offset;
619   }
620 
621   /**
622    * @return a byte stream reading the data + checksum of this block
623    */
624   public DataInputStream getByteStream() {
625     ByteBuffer dup = this.buf.duplicate();
626     dup.position(this.headerSize());
627     return new DataInputStream(new ByteBufferInputStream(dup));
628   }
629 
630   @Override
631   public long heapSize() {
632     long size = ClassSize.align(
633         ClassSize.OBJECT +
634         // Block type, byte buffer and meta references
635         3 * ClassSize.REFERENCE +
636         // On-disk size, uncompressed size, and next block's on-disk size
637         // bytePerChecksum and onDiskDataSize
638         4 * Bytes.SIZEOF_INT +
639         // This and previous block offset
640         2 * Bytes.SIZEOF_LONG +
641         // Heap size of the meta object. meta will be always not null.
642         fileContext.heapSize()
643     );
644 
645     if (buf != null) {
646       // Deep overhead of the byte buffer. Needs to be aligned separately.
647       size += ClassSize.align(buf.capacity() + BYTE_BUFFER_HEAP_SIZE);
648     }
649 
650     return ClassSize.align(size);
651   }
652 
653   /**
654    * Read from an input stream. Analogous to
655    * {@link IOUtils#readFully(InputStream, byte[], int, int)}, but specifies a
656    * number of "extra" bytes that would be desirable but not absolutely
657    * necessary to read.
658    *
659    * @param in the input stream to read from
660    * @param buf the buffer to read into
661    * @param bufOffset the destination offset in the buffer
662    * @param necessaryLen the number of bytes that are absolutely necessary to
663    *          read
664    * @param extraLen the number of extra bytes that would be nice to read
665    * @return true if succeeded reading the extra bytes
666    * @throws IOException if failed to read the necessary bytes
667    */
668   public static boolean readWithExtra(InputStream in, byte buf[],
669       int bufOffset, int necessaryLen, int extraLen) throws IOException {
670     int bytesRemaining = necessaryLen + extraLen;
671     while (bytesRemaining > 0) {
672       int ret = in.read(buf, bufOffset, bytesRemaining);
673       if (ret == -1 && bytesRemaining <= extraLen) {
674         // We could not read the "extra data", but that is OK.
675         break;
676       }
677 
678       if (ret < 0) {
679         throw new IOException("Premature EOF from inputStream (read "
680             + "returned " + ret + ", was trying to read " + necessaryLen
681             + " necessary bytes and " + extraLen + " extra bytes, "
682             + "successfully read "
683             + (necessaryLen + extraLen - bytesRemaining));
684       }
685       bufOffset += ret;
686       bytesRemaining -= ret;
687     }
688     return bytesRemaining <= 0;
689   }
690 
691   /**
692    * @return the on-disk size of the next block (including the header size)
693    *         that was read by peeking into the next block's header
694    */
695   public int getNextBlockOnDiskSizeWithHeader() {
696     return nextBlockOnDiskSizeWithHeader;
697   }
698 
699   /**
700    * Unified version 2 {@link HFile} block writer. The intended usage pattern
701    * is as follows:
702    * <ol>
703    * <li>Construct an {@link HFileBlock.Writer}, providing a compression algorithm.
704    * <li>Call {@link Writer#startWriting} and get a data stream to write to.
705    * <li>Write your data into the stream.
706    * <li>Call {@link Writer#writeHeaderAndData(FSDataOutputStream)} as many times as you need to.
707    * store the serialized block into an external stream.
708    * <li>Repeat to write more blocks.
709    * </ol>
710    * <p>
711    */
712   public static class Writer {
713 
714     private enum State {
715       INIT,
716       WRITING,
717       BLOCK_READY
718     };
719 
720     /** Writer state. Used to ensure the correct usage protocol. */
721     private State state = State.INIT;
722 
723     /** Data block encoder used for data blocks */
724     private final HFileDataBlockEncoder dataBlockEncoder;
725 
726     private HFileBlockEncodingContext dataBlockEncodingCtx;
727 
728     /** block encoding context for non-data blocks */
729     private HFileBlockDefaultEncodingContext defaultBlockEncodingCtx;
730 
731     /**
732      * The stream we use to accumulate data in uncompressed format for each
733      * block. We reset this stream at the end of each block and reuse it. The
734      * header is written as the first {@link HConstants#HFILEBLOCK_HEADER_SIZE} bytes into this
735      * stream.
736      */
737     private ByteArrayOutputStream baosInMemory;
738 
739     /**
740      * Current block type. Set in {@link #startWriting(BlockType)}. Could be
741      * changed in {@link #finishBlock()} from {@link BlockType#DATA}
742      * to {@link BlockType#ENCODED_DATA}.
743      */
744     private BlockType blockType;
745 
746     /**
747      * A stream that we write uncompressed bytes to, which compresses them and
748      * writes them to {@link #baosInMemory}.
749      */
750     private DataOutputStream userDataStream;
751 
752     // Size of actual data being written. Not considering the block encoding/compression. This
753     // includes the header size also.
754     private int unencodedDataSizeWritten;
755 
756     /**
757      * Bytes to be written to the file system, including the header. Compressed
758      * if compression is turned on. It also includes the checksum data that
759      * immediately follows the block data. (header + data + checksums)
760      */
761     private byte[] onDiskBytesWithHeader;
762 
763     /**
764      * The size of the checksum data on disk. It is used only if data is
765      * not compressed. If data is compressed, then the checksums are already
766      * part of onDiskBytesWithHeader. If data is uncompressed, then this
767      * variable stores the checksum data for this block.
768      */
769     private byte[] onDiskChecksum;
770 
771     /**
772      * Valid in the READY state. Contains the header and the uncompressed (but
773      * potentially encoded, if this is a data block) bytes, so the length is
774      * {@link #uncompressedSizeWithoutHeader} + {@link org.apache.hadoop.hbase.HConstants#HFILEBLOCK_HEADER_SIZE}.
775      * Does not store checksums.
776      */
777     private byte[] uncompressedBytesWithHeader;
778 
779     /**
780      * Current block's start offset in the {@link HFile}. Set in
781      * {@link #writeHeaderAndData(FSDataOutputStream)}.
782      */
783     private long startOffset;
784 
785     /**
786      * Offset of previous block by block type. Updated when the next block is
787      * started.
788      */
789     private long[] prevOffsetByType;
790 
791     /** The offset of the previous block of the same type */
792     private long prevOffset;
793     /** Meta data that holds information about the hfileblock**/
794     private HFileContext fileContext;
795 
796     /**
797      * @param dataBlockEncoder data block encoding algorithm to use
798      */
799     public Writer(HFileDataBlockEncoder dataBlockEncoder, HFileContext fileContext) {
800       this.dataBlockEncoder = dataBlockEncoder != null
801           ? dataBlockEncoder : NoOpDataBlockEncoder.INSTANCE;
802       defaultBlockEncodingCtx = new HFileBlockDefaultEncodingContext(null,
803           HConstants.HFILEBLOCK_DUMMY_HEADER, fileContext);
804       dataBlockEncodingCtx = this.dataBlockEncoder
805           .newDataBlockEncodingContext(HConstants.HFILEBLOCK_DUMMY_HEADER, fileContext);
806 
807       if (fileContext.getBytesPerChecksum() < HConstants.HFILEBLOCK_HEADER_SIZE) {
808         throw new RuntimeException("Unsupported value of bytesPerChecksum. " +
809             " Minimum is " + HConstants.HFILEBLOCK_HEADER_SIZE + " but the configured value is " +
810             fileContext.getBytesPerChecksum());
811       }
812 
813       baosInMemory = new ByteArrayOutputStream();
814 
815       prevOffsetByType = new long[BlockType.values().length];
816       for (int i = 0; i < prevOffsetByType.length; ++i)
817         prevOffsetByType[i] = -1;
818 
819       this.fileContext = fileContext;
820     }
821 
822     /**
823      * Starts writing into the block. The previous block's data is discarded.
824      *
825      * @return the stream the user can write their data into
826      * @throws IOException
827      */
828     public DataOutputStream startWriting(BlockType newBlockType)
829         throws IOException {
830       if (state == State.BLOCK_READY && startOffset != -1) {
831         // We had a previous block that was written to a stream at a specific
832         // offset. Save that offset as the last offset of a block of that type.
833         prevOffsetByType[blockType.getId()] = startOffset;
834       }
835 
836       startOffset = -1;
837       blockType = newBlockType;
838 
839       baosInMemory.reset();
840       baosInMemory.write(HConstants.HFILEBLOCK_DUMMY_HEADER);
841 
842       state = State.WRITING;
843 
844       // We will compress it later in finishBlock()
845       userDataStream = new DataOutputStream(baosInMemory);
846       if (newBlockType == BlockType.DATA) {
847         this.dataBlockEncoder.startBlockEncoding(dataBlockEncodingCtx, userDataStream);
848       }
849       this.unencodedDataSizeWritten = 0;
850       return userDataStream;
851     }
852 
853     /**
854      * Writes the Cell to this block
855      * @param cell
856      * @throws IOException
857      */
858     public void write(Cell cell) throws IOException{
859       expectState(State.WRITING);
860       this.unencodedDataSizeWritten += this.dataBlockEncoder.encode(cell, dataBlockEncodingCtx,
861           this.userDataStream);
862     }
863 
864     /**
865      * Returns the stream for the user to write to. The block writer takes care
866      * of handling compression and buffering for caching on write. Can only be
867      * called in the "writing" state.
868      *
869      * @return the data output stream for the user to write to
870      */
871     DataOutputStream getUserDataStream() {
872       expectState(State.WRITING);
873       return userDataStream;
874     }
875 
876     /**
877      * Transitions the block writer from the "writing" state to the "block
878      * ready" state.  Does nothing if a block is already finished.
879      */
880     void ensureBlockReady() throws IOException {
881       Preconditions.checkState(state != State.INIT,
882           "Unexpected state: " + state);
883 
884       if (state == State.BLOCK_READY)
885         return;
886 
887       // This will set state to BLOCK_READY.
888       finishBlock();
889     }
890 
891     /**
892      * An internal method that flushes the compressing stream (if using
893      * compression), serializes the header, and takes care of the separate
894      * uncompressed stream for caching on write, if applicable. Sets block
895      * write state to "block ready".
896      */
897     private void finishBlock() throws IOException {
898       if (blockType == BlockType.DATA) {
899         BufferGrabbingByteArrayOutputStream baosInMemoryCopy =
900             new BufferGrabbingByteArrayOutputStream();
901         baosInMemory.writeTo(baosInMemoryCopy);
902         this.dataBlockEncoder.endBlockEncoding(dataBlockEncodingCtx, userDataStream,
903             baosInMemoryCopy.buf, blockType);
904         blockType = dataBlockEncodingCtx.getBlockType();
905       }
906       userDataStream.flush();
907       // This does an array copy, so it is safe to cache this byte array.
908       uncompressedBytesWithHeader = baosInMemory.toByteArray();
909       prevOffset = prevOffsetByType[blockType.getId()];
910 
911       // We need to set state before we can package the block up for
912       // cache-on-write. In a way, the block is ready, but not yet encoded or
913       // compressed.
914       state = State.BLOCK_READY;
915       if (blockType == BlockType.DATA || blockType == BlockType.ENCODED_DATA) {
916         onDiskBytesWithHeader = dataBlockEncodingCtx
917             .compressAndEncrypt(uncompressedBytesWithHeader);
918       } else {
919         onDiskBytesWithHeader = defaultBlockEncodingCtx
920             .compressAndEncrypt(uncompressedBytesWithHeader);
921       }
922       int numBytes = (int) ChecksumUtil.numBytes(
923           onDiskBytesWithHeader.length,
924           fileContext.getBytesPerChecksum());
925 
926       // put the header for on disk bytes
927       putHeader(onDiskBytesWithHeader, 0,
928           onDiskBytesWithHeader.length + numBytes,
929           uncompressedBytesWithHeader.length, onDiskBytesWithHeader.length);
930       // set the header for the uncompressed bytes (for cache-on-write)
931       putHeader(uncompressedBytesWithHeader, 0,
932           onDiskBytesWithHeader.length + numBytes,
933           uncompressedBytesWithHeader.length, onDiskBytesWithHeader.length);
934 
935       onDiskChecksum = new byte[numBytes];
936       ChecksumUtil.generateChecksums(
937           onDiskBytesWithHeader, 0, onDiskBytesWithHeader.length,
938           onDiskChecksum, 0, fileContext.getChecksumType(), fileContext.getBytesPerChecksum());
939     }
940 
941     public static class BufferGrabbingByteArrayOutputStream extends ByteArrayOutputStream {
942       private byte[] buf;
943 
944       @Override
945       public void write(byte[] b, int off, int len) {
946         this.buf = b;
947       }
948 
949       public byte[] getBuffer() {
950         return this.buf;
951       }
952     }
953 
954     /**
955      * Put the header into the given byte array at the given offset.
956      * @param onDiskSize size of the block on disk header + data + checksum
957      * @param uncompressedSize size of the block after decompression (but
958      *          before optional data block decoding) including header
959      * @param onDiskDataSize size of the block on disk with header
960      *        and data but not including the checksums
961      */
962     private void putHeader(byte[] dest, int offset, int onDiskSize,
963         int uncompressedSize, int onDiskDataSize) {
964       offset = blockType.put(dest, offset);
965       offset = Bytes.putInt(dest, offset, onDiskSize - HConstants.HFILEBLOCK_HEADER_SIZE);
966       offset = Bytes.putInt(dest, offset, uncompressedSize - HConstants.HFILEBLOCK_HEADER_SIZE);
967       offset = Bytes.putLong(dest, offset, prevOffset);
968       offset = Bytes.putByte(dest, offset, fileContext.getChecksumType().getCode());
969       offset = Bytes.putInt(dest, offset, fileContext.getBytesPerChecksum());
970       Bytes.putInt(dest, offset, onDiskDataSize);
971     }
972 
973     /**
974      * Similar to {@link #writeHeaderAndData(FSDataOutputStream)}, but records
975      * the offset of this block so that it can be referenced in the next block
976      * of the same type.
977      *
978      * @param out
979      * @throws IOException
980      */
981     public void writeHeaderAndData(FSDataOutputStream out) throws IOException {
982       long offset = out.getPos();
983       if (startOffset != -1 && offset != startOffset) {
984         throw new IOException("A " + blockType + " block written to a "
985             + "stream twice, first at offset " + startOffset + ", then at "
986             + offset);
987       }
988       startOffset = offset;
989 
990       finishBlockAndWriteHeaderAndData((DataOutputStream) out);
991     }
992 
993     /**
994      * Writes the header and the compressed data of this block (or uncompressed
995      * data when not using compression) into the given stream. Can be called in
996      * the "writing" state or in the "block ready" state. If called in the
997      * "writing" state, transitions the writer to the "block ready" state.
998      *
999      * @param out the output stream to write the
1000      * @throws IOException
1001      */
1002     protected void finishBlockAndWriteHeaderAndData(DataOutputStream out)
1003       throws IOException {
1004       ensureBlockReady();
1005       out.write(onDiskBytesWithHeader);
1006       out.write(onDiskChecksum);
1007     }
1008 
1009     /**
1010      * Returns the header or the compressed data (or uncompressed data when not
1011      * using compression) as a byte array. Can be called in the "writing" state
1012      * or in the "block ready" state. If called in the "writing" state,
1013      * transitions the writer to the "block ready" state. This returns
1014      * the header + data + checksums stored on disk.
1015      *
1016      * @return header and data as they would be stored on disk in a byte array
1017      * @throws IOException
1018      */
1019     byte[] getHeaderAndDataForTest() throws IOException {
1020       ensureBlockReady();
1021       // This is not very optimal, because we are doing an extra copy.
1022       // But this method is used only by unit tests.
1023       byte[] output =
1024           new byte[onDiskBytesWithHeader.length
1025               + onDiskChecksum.length];
1026       System.arraycopy(onDiskBytesWithHeader, 0, output, 0,
1027           onDiskBytesWithHeader.length);
1028       System.arraycopy(onDiskChecksum, 0, output,
1029           onDiskBytesWithHeader.length, onDiskChecksum.length);
1030       return output;
1031     }
1032 
1033     /**
1034      * Releases resources used by this writer.
1035      */
1036     public void release() {
1037       if (dataBlockEncodingCtx != null) {
1038         dataBlockEncodingCtx.close();
1039         dataBlockEncodingCtx = null;
1040       }
1041       if (defaultBlockEncodingCtx != null) {
1042         defaultBlockEncodingCtx.close();
1043         defaultBlockEncodingCtx = null;
1044       }
1045     }
1046 
1047     /**
1048      * Returns the on-disk size of the data portion of the block. This is the
1049      * compressed size if compression is enabled. Can only be called in the
1050      * "block ready" state. Header is not compressed, and its size is not
1051      * included in the return value.
1052      *
1053      * @return the on-disk size of the block, not including the header.
1054      */
1055     int getOnDiskSizeWithoutHeader() {
1056       expectState(State.BLOCK_READY);
1057       return onDiskBytesWithHeader.length + onDiskChecksum.length - HConstants.HFILEBLOCK_HEADER_SIZE;
1058     }
1059 
1060     /**
1061      * Returns the on-disk size of the block. Can only be called in the
1062      * "block ready" state.
1063      *
1064      * @return the on-disk size of the block ready to be written, including the
1065      *         header size, the data and the checksum data.
1066      */
1067     int getOnDiskSizeWithHeader() {
1068       expectState(State.BLOCK_READY);
1069       return onDiskBytesWithHeader.length + onDiskChecksum.length;
1070     }
1071 
1072     /**
1073      * The uncompressed size of the block data. Does not include header size.
1074      */
1075     int getUncompressedSizeWithoutHeader() {
1076       expectState(State.BLOCK_READY);
1077       return uncompressedBytesWithHeader.length - HConstants.HFILEBLOCK_HEADER_SIZE;
1078     }
1079 
1080     /**
1081      * The uncompressed size of the block data, including header size.
1082      */
1083     int getUncompressedSizeWithHeader() {
1084       expectState(State.BLOCK_READY);
1085       return uncompressedBytesWithHeader.length;
1086     }
1087 
1088     /** @return true if a block is being written  */
1089     public boolean isWriting() {
1090       return state == State.WRITING;
1091     }
1092 
1093     /**
1094      * Returns the number of bytes written into the current block so far, or
1095      * zero if not writing the block at the moment. Note that this will return
1096      * zero in the "block ready" state as well.
1097      *
1098      * @return the number of bytes written
1099      */
1100     public int blockSizeWritten() {
1101       if (state != State.WRITING) return 0;
1102       return this.unencodedDataSizeWritten;
1103     }
1104 
1105     /**
1106      * Returns the header followed by the uncompressed data, even if using
1107      * compression. This is needed for storing uncompressed blocks in the block
1108      * cache. Can be called in the "writing" state or the "block ready" state.
1109      * Returns only the header and data, does not include checksum data.
1110      *
1111      * @return uncompressed block bytes for caching on write
1112      */
1113     ByteBuffer getUncompressedBufferWithHeader() {
1114       expectState(State.BLOCK_READY);
1115       return ByteBuffer.wrap(uncompressedBytesWithHeader);
1116     }
1117 
1118     /**
1119      * Returns the header followed by the on-disk (compressed/encoded/encrypted) data. This is
1120      * needed for storing packed blocks in the block cache. Expects calling semantics identical to
1121      * {@link #getUncompressedBufferWithHeader()}. Returns only the header and data,
1122      * Does not include checksum data.
1123      *
1124      * @return packed block bytes for caching on write
1125      */
1126     ByteBuffer getOnDiskBufferWithHeader() {
1127       expectState(State.BLOCK_READY);
1128       return ByteBuffer.wrap(onDiskBytesWithHeader);
1129     }
1130 
1131     private void expectState(State expectedState) {
1132       if (state != expectedState) {
1133         throw new IllegalStateException("Expected state: " + expectedState +
1134             ", actual state: " + state);
1135       }
1136     }
1137 
1138     /**
1139      * Takes the given {@link BlockWritable} instance, creates a new block of
1140      * its appropriate type, writes the writable into this block, and flushes
1141      * the block into the output stream. The writer is instructed not to buffer
1142      * uncompressed bytes for cache-on-write.
1143      *
1144      * @param bw the block-writable object to write as a block
1145      * @param out the file system output stream
1146      * @throws IOException
1147      */
1148     public void writeBlock(BlockWritable bw, FSDataOutputStream out)
1149         throws IOException {
1150       bw.writeToBlock(startWriting(bw.getBlockType()));
1151       writeHeaderAndData(out);
1152     }
1153 
1154     /**
1155      * Creates a new HFileBlock. Checksums have already been validated, so
1156      * the byte buffer passed into the constructor of this newly created
1157      * block does not have checksum data even though the header minor
1158      * version is MINOR_VERSION_WITH_CHECKSUM. This is indicated by setting a
1159      * 0 value in bytesPerChecksum.
1160      */
1161     public HFileBlock getBlockForCaching(CacheConfig cacheConf) {
1162       HFileContext newContext = new HFileContextBuilder()
1163                                 .withBlockSize(fileContext.getBlocksize())
1164                                 .withBytesPerCheckSum(0)
1165                                 .withChecksumType(ChecksumType.NULL) // no checksums in cached data
1166                                 .withCompression(fileContext.getCompression())
1167                                 .withDataBlockEncoding(fileContext.getDataBlockEncoding())
1168                                 .withHBaseCheckSum(fileContext.isUseHBaseChecksum())
1169                                 .withCompressTags(fileContext.isCompressTags())
1170                                 .withIncludesMvcc(fileContext.isIncludesMvcc())
1171                                 .withIncludesTags(fileContext.isIncludesTags())
1172                                 .build();
1173       return new HFileBlock(blockType, getOnDiskSizeWithoutHeader(),
1174           getUncompressedSizeWithoutHeader(), prevOffset,
1175           cacheConf.shouldCacheCompressed(blockType.getCategory()) ?
1176             getOnDiskBufferWithHeader() :
1177             getUncompressedBufferWithHeader(),
1178           DONT_FILL_HEADER, startOffset,
1179           onDiskBytesWithHeader.length + onDiskChecksum.length, newContext);
1180     }
1181   }
1182 
1183   /** Something that can be written into a block. */
1184   public interface BlockWritable {
1185 
1186     /** The type of block this data should use. */
1187     BlockType getBlockType();
1188 
1189     /**
1190      * Writes the block to the provided stream. Must not write any magic
1191      * records.
1192      *
1193      * @param out a stream to write uncompressed data into
1194      */
1195     void writeToBlock(DataOutput out) throws IOException;
1196   }
1197 
1198   // Block readers and writers
1199 
1200   /** An interface allowing to iterate {@link HFileBlock}s. */
1201   public interface BlockIterator {
1202 
1203     /**
1204      * Get the next block, or null if there are no more blocks to iterate.
1205      */
1206     HFileBlock nextBlock() throws IOException;
1207 
1208     /**
1209      * Similar to {@link #nextBlock()} but checks block type, throws an
1210      * exception if incorrect, and returns the HFile block
1211      */
1212     HFileBlock nextBlockWithBlockType(BlockType blockType) throws IOException;
1213   }
1214 
1215   /** A full-fledged reader with iteration ability. */
1216   public interface FSReader {
1217 
1218     /**
1219      * Reads the block at the given offset in the file with the given on-disk
1220      * size and uncompressed size.
1221      *
1222      * @param offset
1223      * @param onDiskSize the on-disk size of the entire block, including all
1224      *          applicable headers, or -1 if unknown
1225      * @param uncompressedSize the uncompressed size of the compressed part of
1226      *          the block, or -1 if unknown
1227      * @return the newly read block
1228      */
1229     HFileBlock readBlockData(long offset, long onDiskSize,
1230         int uncompressedSize, boolean pread) throws IOException;
1231 
1232     /**
1233      * Creates a block iterator over the given portion of the {@link HFile}.
1234      * The iterator returns blocks starting with offset such that offset <=
1235      * startOffset < endOffset. Returned blocks are always unpacked.
1236      *
1237      * @param startOffset the offset of the block to start iteration with
1238      * @param endOffset the offset to end iteration at (exclusive)
1239      * @return an iterator of blocks between the two given offsets
1240      */
1241     BlockIterator blockRange(long startOffset, long endOffset);
1242 
1243     /** Closes the backing streams */
1244     void closeStreams() throws IOException;
1245 
1246     /** Get a decoder for {@link BlockType#ENCODED_DATA} blocks from this file. */
1247     HFileBlockDecodingContext getBlockDecodingContext();
1248 
1249     /** Get the default decoder for blocks from this file. */
1250     HFileBlockDecodingContext getDefaultBlockDecodingContext();
1251   }
1252 
1253   /**
1254    * A common implementation of some methods of {@link FSReader} and some
1255    * tools for implementing HFile format version-specific block readers.
1256    */
1257   private abstract static class AbstractFSReader implements FSReader {
1258     /** Compression algorithm used by the {@link HFile} */
1259 
1260     /** The size of the file we are reading from, or -1 if unknown. */
1261     protected long fileSize;
1262 
1263     /** The size of the header */
1264     protected final int hdrSize;
1265 
1266     /** The filesystem used to access data */
1267     protected HFileSystem hfs;
1268 
1269     /** The path (if any) where this data is coming from */
1270     protected Path path;
1271 
1272     private final Lock streamLock = new ReentrantLock();
1273 
1274     /** The default buffer size for our buffered streams */
1275     public static final int DEFAULT_BUFFER_SIZE = 1 << 20;
1276 
1277     protected HFileContext fileContext;
1278 
1279     public AbstractFSReader(long fileSize, HFileSystem hfs, Path path, HFileContext fileContext)
1280         throws IOException {
1281       this.fileSize = fileSize;
1282       this.hfs = hfs;
1283       this.path = path;
1284       this.fileContext = fileContext;
1285       this.hdrSize = headerSize(fileContext.isUseHBaseChecksum());
1286     }
1287 
1288     @Override
1289     public BlockIterator blockRange(final long startOffset,
1290         final long endOffset) {
1291       final FSReader owner = this; // handle for inner class
1292       return new BlockIterator() {
1293         private long offset = startOffset;
1294 
1295         @Override
1296         public HFileBlock nextBlock() throws IOException {
1297           if (offset >= endOffset)
1298             return null;
1299           HFileBlock b = readBlockData(offset, -1, -1, false);
1300           offset += b.getOnDiskSizeWithHeader();
1301           return b.unpack(fileContext, owner);
1302         }
1303 
1304         @Override
1305         public HFileBlock nextBlockWithBlockType(BlockType blockType)
1306             throws IOException {
1307           HFileBlock blk = nextBlock();
1308           if (blk.getBlockType() != blockType) {
1309             throw new IOException("Expected block of type " + blockType
1310                 + " but found " + blk.getBlockType());
1311           }
1312           return blk;
1313         }
1314       };
1315     }
1316 
1317     /**
1318      * Does a positional read or a seek and read into the given buffer. Returns
1319      * the on-disk size of the next block, or -1 if it could not be determined.
1320      *
1321      * @param dest destination buffer
1322      * @param destOffset offset in the destination buffer
1323      * @param size size of the block to be read
1324      * @param peekIntoNextBlock whether to read the next block's on-disk size
1325      * @param fileOffset position in the stream to read at
1326      * @param pread whether we should do a positional read
1327      * @param istream The input source of data
1328      * @return the on-disk size of the next block with header size included, or
1329      *         -1 if it could not be determined
1330      * @throws IOException
1331      */
1332     protected int readAtOffset(FSDataInputStream istream,
1333         byte[] dest, int destOffset, int size,
1334         boolean peekIntoNextBlock, long fileOffset, boolean pread)
1335         throws IOException {
1336       if (peekIntoNextBlock &&
1337           destOffset + size + hdrSize > dest.length) {
1338         // We are asked to read the next block's header as well, but there is
1339         // not enough room in the array.
1340         throw new IOException("Attempted to read " + size + " bytes and " +
1341             hdrSize + " bytes of next header into a " + dest.length +
1342             "-byte array at offset " + destOffset);
1343       }
1344 
1345       if (!pread && streamLock.tryLock()) {
1346         // Seek + read. Better for scanning.
1347         try {
1348           istream.seek(fileOffset);
1349 
1350           long realOffset = istream.getPos();
1351           if (realOffset != fileOffset) {
1352             throw new IOException("Tried to seek to " + fileOffset + " to "
1353                 + "read " + size + " bytes, but pos=" + realOffset
1354                 + " after seek");
1355           }
1356 
1357           if (!peekIntoNextBlock) {
1358             IOUtils.readFully(istream, dest, destOffset, size);
1359             return -1;
1360           }
1361 
1362           // Try to read the next block header.
1363           if (!readWithExtra(istream, dest, destOffset, size, hdrSize))
1364             return -1;
1365         } finally {
1366           streamLock.unlock();
1367         }
1368       } else {
1369         // Positional read. Better for random reads; or when the streamLock is already locked.
1370         int extraSize = peekIntoNextBlock ? hdrSize : 0;
1371         int ret = istream.read(fileOffset, dest, destOffset, size + extraSize);
1372         if (ret < size) {
1373           throw new IOException("Positional read of " + size + " bytes " +
1374               "failed at offset " + fileOffset + " (returned " + ret + ")");
1375         }
1376 
1377         if (ret == size || ret < size + extraSize) {
1378           // Could not read the next block's header, or did not try.
1379           return -1;
1380         }
1381       }
1382 
1383       assert peekIntoNextBlock;
1384       return Bytes.toInt(dest, destOffset + size + BlockType.MAGIC_LENGTH) + hdrSize;
1385     }
1386 
1387   }
1388 
1389   /**
1390    * We always prefetch the header of the next block, so that we know its
1391    * on-disk size in advance and can read it in one operation.
1392    */
1393   private static class PrefetchedHeader {
1394     long offset = -1;
1395     byte[] header = new byte[HConstants.HFILEBLOCK_HEADER_SIZE];
1396     final ByteBuffer buf = ByteBuffer.wrap(header, 0, HConstants.HFILEBLOCK_HEADER_SIZE);
1397   }
1398 
1399   /** Reads version 2 blocks from the filesystem. */
1400   static class FSReaderImpl extends AbstractFSReader {
1401     /** The file system stream of the underlying {@link HFile} that
1402      * does or doesn't do checksum validations in the filesystem */
1403     protected FSDataInputStreamWrapper streamWrapper;
1404 
1405     private HFileBlockDecodingContext encodedBlockDecodingCtx;
1406 
1407     /** Default context used when BlockType != {@link BlockType#ENCODED_DATA}. */
1408     private final HFileBlockDefaultDecodingContext defaultDecodingCtx;
1409 
1410     private ThreadLocal<PrefetchedHeader> prefetchedHeaderForThread =
1411         new ThreadLocal<PrefetchedHeader>() {
1412           @Override
1413           public PrefetchedHeader initialValue() {
1414             return new PrefetchedHeader();
1415           }
1416         };
1417 
1418     public FSReaderImpl(FSDataInputStreamWrapper stream, long fileSize, HFileSystem hfs, Path path,
1419         HFileContext fileContext) throws IOException {
1420       super(fileSize, hfs, path, fileContext);
1421       this.streamWrapper = stream;
1422       // Older versions of HBase didn't support checksum.
1423       this.streamWrapper.prepareForBlockReader(!fileContext.isUseHBaseChecksum());
1424       defaultDecodingCtx = new HFileBlockDefaultDecodingContext(fileContext);
1425       encodedBlockDecodingCtx = defaultDecodingCtx;
1426     }
1427 
1428     /**
1429      * A constructor that reads files with the latest minor version.
1430      * This is used by unit tests only.
1431      */
1432     FSReaderImpl(FSDataInputStream istream, long fileSize, HFileContext fileContext)
1433     throws IOException {
1434       this(new FSDataInputStreamWrapper(istream), fileSize, null, null, fileContext);
1435     }
1436 
1437     /**
1438      * Reads a version 2 block (version 1 blocks not supported and not expected). Tries to do as
1439      * little memory allocation as possible, using the provided on-disk size.
1440      *
1441      * @param offset the offset in the stream to read at
1442      * @param onDiskSizeWithHeaderL the on-disk size of the block, including
1443      *          the header, or -1 if unknown
1444      * @param uncompressedSize the uncompressed size of the the block. Always
1445      *          expected to be -1. This parameter is only used in version 1.
1446      * @param pread whether to use a positional read
1447      */
1448     @Override
1449     public HFileBlock readBlockData(long offset, long onDiskSizeWithHeaderL,
1450         int uncompressedSize, boolean pread)
1451     throws IOException {
1452 
1453       // get a copy of the current state of whether to validate
1454       // hbase checksums or not for this read call. This is not
1455       // thread-safe but the one constaint is that if we decide
1456       // to skip hbase checksum verification then we are
1457       // guaranteed to use hdfs checksum verification.
1458       boolean doVerificationThruHBaseChecksum = streamWrapper.shouldUseHBaseChecksum();
1459       FSDataInputStream is = streamWrapper.getStream(doVerificationThruHBaseChecksum);
1460 
1461       HFileBlock blk = readBlockDataInternal(is, offset,
1462                          onDiskSizeWithHeaderL,
1463                          uncompressedSize, pread,
1464                          doVerificationThruHBaseChecksum);
1465       if (blk == null) {
1466         HFile.LOG.warn("HBase checksum verification failed for file " +
1467                        path + " at offset " +
1468                        offset + " filesize " + fileSize +
1469                        ". Retrying read with HDFS checksums turned on...");
1470 
1471         if (!doVerificationThruHBaseChecksum) {
1472           String msg = "HBase checksum verification failed for file " +
1473                        path + " at offset " +
1474                        offset + " filesize " + fileSize +
1475                        " but this cannot happen because doVerify is " +
1476                        doVerificationThruHBaseChecksum;
1477           HFile.LOG.warn(msg);
1478           throw new IOException(msg); // cannot happen case here
1479         }
1480         HFile.checksumFailures.incrementAndGet(); // update metrics
1481 
1482         // If we have a checksum failure, we fall back into a mode where
1483         // the next few reads use HDFS level checksums. We aim to make the
1484         // next CHECKSUM_VERIFICATION_NUM_IO_THRESHOLD reads avoid
1485         // hbase checksum verification, but since this value is set without
1486         // holding any locks, it can so happen that we might actually do
1487         // a few more than precisely this number.
1488         is = this.streamWrapper.fallbackToFsChecksum(CHECKSUM_VERIFICATION_NUM_IO_THRESHOLD);
1489         doVerificationThruHBaseChecksum = false;
1490         blk = readBlockDataInternal(is, offset, onDiskSizeWithHeaderL,
1491                                     uncompressedSize, pread,
1492                                     doVerificationThruHBaseChecksum);
1493         if (blk != null) {
1494           HFile.LOG.warn("HDFS checksum verification suceeded for file " +
1495                          path + " at offset " +
1496                          offset + " filesize " + fileSize);
1497         }
1498       }
1499       if (blk == null && !doVerificationThruHBaseChecksum) {
1500         String msg = "readBlockData failed, possibly due to " +
1501                      "checksum verification failed for file " + path +
1502                      " at offset " + offset + " filesize " + fileSize;
1503         HFile.LOG.warn(msg);
1504         throw new IOException(msg);
1505       }
1506 
1507       // If there is a checksum mismatch earlier, then retry with
1508       // HBase checksums switched off and use HDFS checksum verification.
1509       // This triggers HDFS to detect and fix corrupt replicas. The
1510       // next checksumOffCount read requests will use HDFS checksums.
1511       // The decrementing of this.checksumOffCount is not thread-safe,
1512       // but it is harmless because eventually checksumOffCount will be
1513       // a negative number.
1514       streamWrapper.checksumOk();
1515       return blk;
1516     }
1517 
1518     /**
1519      * Reads a version 2 block.
1520      *
1521      * @param offset the offset in the stream to read at
1522      * @param onDiskSizeWithHeaderL the on-disk size of the block, including
1523      *          the header, or -1 if unknown
1524      * @param uncompressedSize the uncompressed size of the the block. Always
1525      *          expected to be -1. This parameter is only used in version 1.
1526      * @param pread whether to use a positional read
1527      * @param verifyChecksum Whether to use HBase checksums.
1528      *        If HBase checksum is switched off, then use HDFS checksum.
1529      * @return the HFileBlock or null if there is a HBase checksum mismatch
1530      */
1531     private HFileBlock readBlockDataInternal(FSDataInputStream is, long offset,
1532         long onDiskSizeWithHeaderL, int uncompressedSize, boolean pread,
1533         boolean verifyChecksum)
1534     throws IOException {
1535       if (offset < 0) {
1536         throw new IOException("Invalid offset=" + offset + " trying to read "
1537             + "block (onDiskSize=" + onDiskSizeWithHeaderL
1538             + ", uncompressedSize=" + uncompressedSize + ")");
1539       }
1540 
1541       if (uncompressedSize != -1) {
1542         throw new IOException("Version 2 block reader API does not need " +
1543             "the uncompressed size parameter");
1544       }
1545 
1546       if ((onDiskSizeWithHeaderL < hdrSize && onDiskSizeWithHeaderL != -1)
1547           || onDiskSizeWithHeaderL >= Integer.MAX_VALUE) {
1548         throw new IOException("Invalid onDisksize=" + onDiskSizeWithHeaderL
1549             + ": expected to be at least " + hdrSize
1550             + " and at most " + Integer.MAX_VALUE + ", or -1 (offset="
1551             + offset + ", uncompressedSize=" + uncompressedSize + ")");
1552       }
1553 
1554       int onDiskSizeWithHeader = (int) onDiskSizeWithHeaderL;
1555       // See if we can avoid reading the header. This is desirable, because
1556       // we will not incur a backward seek operation if we have already
1557       // read this block's header as part of the previous read's look-ahead.
1558       // And we also want to skip reading the header again if it has already
1559       // been read.
1560       // TODO: How often does this optimization fire? Has to be same thread so the thread local
1561       // is pertinent and we have to be reading next block as in a big scan.
1562       PrefetchedHeader prefetchedHeader = prefetchedHeaderForThread.get();
1563       ByteBuffer headerBuf = prefetchedHeader.offset == offset? prefetchedHeader.buf: null;
1564 
1565       // Allocate enough space to fit the next block's header too.
1566       int nextBlockOnDiskSize = 0;
1567       byte[] onDiskBlock = null;
1568 
1569       HFileBlock b = null;
1570       if (onDiskSizeWithHeader > 0) {
1571         // We know the total on-disk size. Read the entire block into memory,
1572         // then parse the header. This code path is used when
1573         // doing a random read operation relying on the block index, as well as
1574         // when the client knows the on-disk size from peeking into the next
1575         // block's header (e.g. this block's header) when reading the previous
1576         // block. This is the faster and more preferable case.
1577 
1578         // Size that we have to skip in case we have already read the header.
1579         int preReadHeaderSize = headerBuf == null ? 0 : hdrSize;
1580         onDiskBlock = new byte[onDiskSizeWithHeader + hdrSize]; // room for this block plus the
1581                                                                 // next block's header
1582         nextBlockOnDiskSize = readAtOffset(is, onDiskBlock,
1583             preReadHeaderSize, onDiskSizeWithHeader - preReadHeaderSize,
1584             true, offset + preReadHeaderSize, pread);
1585         if (headerBuf != null) {
1586           // the header has been read when reading the previous block, copy
1587           // to this block's header
1588           // headerBuf is HBB
1589           assert headerBuf.hasArray();
1590           System.arraycopy(headerBuf.array(),
1591               headerBuf.arrayOffset(), onDiskBlock, 0, hdrSize);
1592         } else {
1593           headerBuf = ByteBuffer.wrap(onDiskBlock, 0, hdrSize);
1594         }
1595         // We know the total on-disk size but not the uncompressed size. Parse the header.
1596         try {
1597           // TODO: FIX!!! Expensive parse just to get a length
1598           b = new HFileBlock(headerBuf, fileContext.isUseHBaseChecksum());
1599         } catch (IOException ex) {
1600           // Seen in load testing. Provide comprehensive debug info.
1601           throw new IOException("Failed to read compressed block at "
1602               + offset
1603               + ", onDiskSizeWithoutHeader="
1604               + onDiskSizeWithHeader
1605               + ", preReadHeaderSize="
1606               + hdrSize
1607               + ", header.length="
1608               + prefetchedHeader.header.length
1609               + ", header bytes: "
1610               + Bytes.toStringBinary(prefetchedHeader.header, 0,
1611                   hdrSize), ex);
1612         }
1613         // if the caller specifies a onDiskSizeWithHeader, validate it.
1614         int onDiskSizeWithoutHeader = onDiskSizeWithHeader - hdrSize;
1615         assert onDiskSizeWithoutHeader >= 0;
1616         b.validateOnDiskSizeWithoutHeader(onDiskSizeWithoutHeader);
1617       } else {
1618         // Check headerBuf to see if we have read this block's header as part of
1619         // reading the previous block. This is an optimization of peeking into
1620         // the next block's header (e.g.this block's header) when reading the
1621         // previous block. This is the faster and more preferable case. If the
1622         // header is already there, don't read the header again.
1623 
1624         // Unfortunately, we still have to do a separate read operation to
1625         // read the header.
1626         if (headerBuf == null) {
1627           // From the header, determine the on-disk size of the given hfile
1628           // block, and read the remaining data, thereby incurring two read
1629           // operations. This might happen when we are doing the first read
1630           // in a series of reads or a random read, and we don't have access
1631           // to the block index. This is costly and should happen very rarely.
1632           headerBuf = ByteBuffer.allocate(hdrSize);
1633           // headerBuf is HBB
1634           readAtOffset(is, headerBuf.array(), headerBuf.arrayOffset(),
1635               hdrSize, false, offset, pread);
1636         }
1637         // TODO: FIX!!! Expensive parse just to get a length
1638         b = new HFileBlock(headerBuf, fileContext.isUseHBaseChecksum());
1639         onDiskBlock = new byte[b.getOnDiskSizeWithHeader() + hdrSize];
1640         // headerBuf is HBB
1641         System.arraycopy(headerBuf.array(), headerBuf.arrayOffset(), onDiskBlock, 0, hdrSize);
1642         nextBlockOnDiskSize =
1643           readAtOffset(is, onDiskBlock, hdrSize, b.getOnDiskSizeWithHeader()
1644               - hdrSize, true, offset + hdrSize, pread);
1645         onDiskSizeWithHeader = b.onDiskSizeWithoutHeader + hdrSize;
1646       }
1647 
1648       if (!fileContext.isCompressedOrEncrypted()) {
1649         b.assumeUncompressed();
1650       }
1651 
1652       if (verifyChecksum && !validateBlockChecksum(b, onDiskBlock, hdrSize)) {
1653         return null;             // checksum mismatch
1654       }
1655 
1656       // The onDiskBlock will become the headerAndDataBuffer for this block.
1657       // If nextBlockOnDiskSizeWithHeader is not zero, the onDiskBlock already
1658       // contains the header of next block, so no need to set next
1659       // block's header in it.
1660       b = new HFileBlock(ByteBuffer.wrap(onDiskBlock, 0, onDiskSizeWithHeader),
1661         this.fileContext.isUseHBaseChecksum());
1662 
1663       b.nextBlockOnDiskSizeWithHeader = nextBlockOnDiskSize;
1664 
1665       // Set prefetched header
1666       if (b.hasNextBlockHeader()) {
1667         prefetchedHeader.offset = offset + b.getOnDiskSizeWithHeader();
1668         System.arraycopy(onDiskBlock, onDiskSizeWithHeader, prefetchedHeader.header, 0, hdrSize);
1669       }
1670 
1671       b.offset = offset;
1672       b.fileContext.setIncludesTags(this.fileContext.isIncludesTags());
1673       b.fileContext.setIncludesMvcc(this.fileContext.isIncludesMvcc());
1674       return b;
1675     }
1676 
1677     void setIncludesMemstoreTS(boolean includesMemstoreTS) {
1678       this.fileContext.setIncludesMvcc(includesMemstoreTS);
1679     }
1680 
1681     void setDataBlockEncoder(HFileDataBlockEncoder encoder) {
1682       encodedBlockDecodingCtx = encoder.newDataBlockDecodingContext(this.fileContext);
1683     }
1684 
1685     @Override
1686     public HFileBlockDecodingContext getBlockDecodingContext() {
1687       return this.encodedBlockDecodingCtx;
1688     }
1689 
1690     @Override
1691     public HFileBlockDecodingContext getDefaultBlockDecodingContext() {
1692       return this.defaultDecodingCtx;
1693     }
1694 
1695     /**
1696      * Generates the checksum for the header as well as the data and
1697      * then validates that it matches the value stored in the header.
1698      * If there is a checksum mismatch, then return false. Otherwise
1699      * return true.
1700      */
1701     protected boolean validateBlockChecksum(HFileBlock block,  byte[] data, int hdrSize)
1702         throws IOException {
1703       return ChecksumUtil.validateBlockChecksum(path, block, data, hdrSize);
1704     }
1705 
1706     @Override
1707     public void closeStreams() throws IOException {
1708       streamWrapper.close();
1709     }
1710 
1711     @Override
1712     public String toString() {
1713       return "hfs=" + hfs + ", path=" + path + ", fileContext=" + fileContext;
1714     }
1715   }
1716 
1717   @Override
1718   public int getSerializedLength() {
1719     if (buf != null) {
1720       // include extra bytes for the next header when it's available.
1721       int extraSpace = hasNextBlockHeader() ? headerSize() : 0;
1722       return this.buf.limit() + extraSpace + HFileBlock.EXTRA_SERIALIZATION_SPACE;
1723     }
1724     return 0;
1725   }
1726 
1727   @Override
1728   public void serialize(ByteBuffer destination) {
1729     ByteBufferUtils.copyFromBufferToBuffer(destination, this.buf, 0, getSerializedLength()
1730         - EXTRA_SERIALIZATION_SPACE);
1731     serializeExtraInfo(destination);
1732   }
1733 
1734   public void serializeExtraInfo(ByteBuffer destination) {
1735     destination.put(this.fileContext.isUseHBaseChecksum() ? (byte) 1 : (byte) 0);
1736     destination.putLong(this.offset);
1737     destination.putInt(this.nextBlockOnDiskSizeWithHeader);
1738     destination.rewind();
1739   }
1740 
1741   @Override
1742   public CacheableDeserializer<Cacheable> getDeserializer() {
1743     return HFileBlock.blockDeserializer;
1744   }
1745 
1746   @Override
1747   public boolean equals(Object comparison) {
1748     if (this == comparison) {
1749       return true;
1750     }
1751     if (comparison == null) {
1752       return false;
1753     }
1754     if (comparison.getClass() != this.getClass()) {
1755       return false;
1756     }
1757 
1758     HFileBlock castedComparison = (HFileBlock) comparison;
1759 
1760     if (castedComparison.blockType != this.blockType) {
1761       return false;
1762     }
1763     if (castedComparison.nextBlockOnDiskSizeWithHeader != this.nextBlockOnDiskSizeWithHeader) {
1764       return false;
1765     }
1766     if (castedComparison.offset != this.offset) {
1767       return false;
1768     }
1769     if (castedComparison.onDiskSizeWithoutHeader != this.onDiskSizeWithoutHeader) {
1770       return false;
1771     }
1772     if (castedComparison.prevBlockOffset != this.prevBlockOffset) {
1773       return false;
1774     }
1775     if (castedComparison.uncompressedSizeWithoutHeader != this.uncompressedSizeWithoutHeader) {
1776       return false;
1777     }
1778     if (ByteBufferUtils.compareTo(this.buf, 0, this.buf.limit(), castedComparison.buf, 0,
1779         castedComparison.buf.limit()) != 0) {
1780       return false;
1781     }
1782     return true;
1783   }
1784 
1785   public DataBlockEncoding getDataBlockEncoding() {
1786     if (blockType == BlockType.ENCODED_DATA) {
1787       return DataBlockEncoding.getEncodingById(getDataBlockEncodingId());
1788     }
1789     return DataBlockEncoding.NONE;
1790   }
1791 
1792   byte getChecksumType() {
1793     return this.fileContext.getChecksumType().getCode();
1794   }
1795 
1796   int getBytesPerChecksum() {
1797     return this.fileContext.getBytesPerChecksum();
1798   }
1799 
1800   /** @return the size of data on disk + header. Excludes checksum. */
1801   int getOnDiskDataSizeWithHeader() {
1802     return this.onDiskDataSizeWithHeader;
1803   }
1804 
1805   /**
1806    * Calcuate the number of bytes required to store all the checksums
1807    * for this block. Each checksum value is a 4 byte integer.
1808    */
1809   int totalChecksumBytes() {
1810     // If the hfile block has minorVersion 0, then there are no checksum
1811     // data to validate. Similarly, a zero value in this.bytesPerChecksum
1812     // indicates that cached blocks do not have checksum data because
1813     // checksums were already validated when the block was read from disk.
1814     if (!fileContext.isUseHBaseChecksum() || this.fileContext.getBytesPerChecksum() == 0) {
1815       return 0;
1816     }
1817     return (int)ChecksumUtil.numBytes(onDiskDataSizeWithHeader, this.fileContext.getBytesPerChecksum());
1818   }
1819 
1820   /**
1821    * Returns the size of this block header.
1822    */
1823   public int headerSize() {
1824     return headerSize(this.fileContext.isUseHBaseChecksum());
1825   }
1826 
1827   /**
1828    * Maps a minor version to the size of the header.
1829    */
1830   public static int headerSize(boolean usesHBaseChecksum) {
1831     if (usesHBaseChecksum) {
1832       return HConstants.HFILEBLOCK_HEADER_SIZE;
1833     }
1834     return HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM;
1835   }
1836 
1837   /**
1838    * Return the appropriate DUMMY_HEADER for the minor version
1839    */
1840   public byte[] getDummyHeaderForVersion() {
1841     return getDummyHeaderForVersion(this.fileContext.isUseHBaseChecksum());
1842   }
1843 
1844   /**
1845    * Return the appropriate DUMMY_HEADER for the minor version
1846    */
1847   static private byte[] getDummyHeaderForVersion(boolean usesHBaseChecksum) {
1848     if (usesHBaseChecksum) {
1849       return HConstants.HFILEBLOCK_DUMMY_HEADER;
1850     }
1851     return DUMMY_HEADER_NO_CHECKSUM;
1852   }
1853 
1854   /**
1855    * @return the HFileContext used to create this HFileBlock. Not necessary the
1856    * fileContext for the file from which this block's data was originally read.
1857    */
1858   public HFileContext getHFileContext() {
1859     return this.fileContext;
1860   }
1861 
1862   /**
1863    * Convert the contents of the block header into a human readable string.
1864    * This is mostly helpful for debugging. This assumes that the block
1865    * has minor version > 0.
1866    */
1867   static String toStringHeader(ByteBuffer buf) throws IOException {
1868     byte[] magicBuf = new byte[Math.min(buf.limit() - buf.position(), BlockType.MAGIC_LENGTH)];
1869     buf.get(magicBuf);
1870     BlockType bt = BlockType.parse(magicBuf, 0, BlockType.MAGIC_LENGTH);
1871     int compressedBlockSizeNoHeader = buf.getInt();;
1872     int uncompressedBlockSizeNoHeader = buf.getInt();;
1873     long prevBlockOffset = buf.getLong();
1874     byte cksumtype = buf.get();
1875     long bytesPerChecksum = buf.getInt();
1876     long onDiskDataSizeWithHeader = buf.getInt();
1877     return " Header dump: magic: " + Bytes.toString(magicBuf) +
1878                    " blockType " + bt +
1879                    " compressedBlockSizeNoHeader " +
1880                    compressedBlockSizeNoHeader +
1881                    " uncompressedBlockSizeNoHeader " +
1882                    uncompressedBlockSizeNoHeader +
1883                    " prevBlockOffset " + prevBlockOffset +
1884                    " checksumType " + ChecksumType.codeToType(cksumtype) +
1885                    " bytesPerChecksum " + bytesPerChecksum +
1886                    " onDiskDataSizeWithHeader " + onDiskDataSizeWithHeader;
1887   }
1888 }