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