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