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