View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.io.hfile;
19  
20  import java.io.DataInput;
21  import java.io.IOException;
22  import java.nio.ByteBuffer;
23  import java.util.ArrayList;
24  import java.util.List;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.hadoop.classification.InterfaceAudience;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.fs.Path;
31  import org.apache.hadoop.hbase.HConstants;
32  import org.apache.hadoop.hbase.KeyValue;
33  import org.apache.hadoop.hbase.KeyValue.KVComparator;
34  import org.apache.hadoop.hbase.fs.HFileSystem;
35  import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
36  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoder;
37  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
38  import org.apache.hadoop.hbase.io.encoding.HFileBlockDecodingContext;
39  import org.apache.hadoop.hbase.io.hfile.HFile.FileInfo;
40  import org.apache.hadoop.hbase.util.ByteBufferUtils;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.hbase.util.IdLock;
43  import org.apache.hadoop.io.WritableUtils;
44  import org.cloudera.htrace.Trace;
45  import org.cloudera.htrace.TraceScope;
46  
47  import com.google.common.annotations.VisibleForTesting;
48  
49  /**
50   * {@link HFile} reader for version 2.
51   */
52  @InterfaceAudience.Private
53  public class HFileReaderV2 extends AbstractHFileReader {
54  
55    private static final Log LOG = LogFactory.getLog(HFileReaderV2.class);
56  
57    /** Minor versions in HFile V2 starting with this number have hbase checksums */
58    public static final int MINOR_VERSION_WITH_CHECKSUM = 1;
59    /** In HFile V2 minor version that does not support checksums */
60    public static final int MINOR_VERSION_NO_CHECKSUM = 0;
61  
62    /** HFile minor version that introduced pbuf filetrailer */
63    public static final int PBUF_TRAILER_MINOR_VERSION = 2;
64  
65    /**
66     * The size of a (key length, value length) tuple that prefixes each entry in
67     * a data block.
68     */
69    public final static int KEY_VALUE_LEN_SIZE = 2 * Bytes.SIZEOF_INT;
70  
71    protected boolean includesMemstoreTS = false;
72    protected boolean decodeMemstoreTS = false;
73    protected boolean shouldIncludeMemstoreTS() {
74      return includesMemstoreTS;
75    }
76  
77    /** Filesystem-level block reader. */
78    protected HFileBlock.FSReader fsBlockReader;
79  
80    /**
81     * A "sparse lock" implementation allowing to lock on a particular block
82     * identified by offset. The purpose of this is to avoid two clients loading
83     * the same block, and have all but one client wait to get the block from the
84     * cache.
85     */
86    private IdLock offsetLock = new IdLock();
87  
88    /**
89     * Blocks read from the load-on-open section, excluding data root index, meta
90     * index, and file info.
91     */
92    private List<HFileBlock> loadOnOpenBlocks = new ArrayList<HFileBlock>();
93  
94    /** Minimum minor version supported by this HFile format */
95    static final int MIN_MINOR_VERSION = 0;
96  
97    /** Maximum minor version supported by this HFile format */
98    // We went to version 2 when we moved to pb'ing fileinfo and the trailer on
99    // the file. This version can read Writables version 1.
100   static final int MAX_MINOR_VERSION = 3;
101 
102   /** Minor versions starting with this number have faked index key */
103   static final int MINOR_VERSION_WITH_FAKED_KEY = 3;
104 
105   protected HFileContext hfileContext;
106 
107   /**
108    * Opens a HFile. You must load the index before you can use it by calling
109    * {@link #loadFileInfo()}.
110    *
111    * @param path Path to HFile.
112    * @param trailer File trailer.
113    * @param fsdis input stream.
114    * @param size Length of the stream.
115    * @param cacheConf Cache configuration.
116    * @param hfs
117    * @param conf
118    */
119   public HFileReaderV2(final Path path, final FixedFileTrailer trailer,
120       final FSDataInputStreamWrapper fsdis, final long size, final CacheConfig cacheConf,
121       final HFileSystem hfs, final Configuration conf) throws IOException {
122     super(path, trailer, size, cacheConf, hfs, conf);
123     this.conf = conf;
124     trailer.expectMajorVersion(getMajorVersion());
125     validateMinorVersion(path, trailer.getMinorVersion());
126     this.hfileContext = createHFileContext(fsdis, fileSize, hfs, path, trailer);
127     HFileBlock.FSReaderV2 fsBlockReaderV2 = new HFileBlock.FSReaderV2(fsdis, fileSize, hfs, path,
128         hfileContext);
129     this.fsBlockReader = fsBlockReaderV2; // upcast
130 
131     // Comparator class name is stored in the trailer in version 2.
132     comparator = trailer.createComparator();
133     dataBlockIndexReader = new HFileBlockIndex.BlockIndexReader(comparator,
134         trailer.getNumDataIndexLevels(), this);
135     metaBlockIndexReader = new HFileBlockIndex.BlockIndexReader(
136         KeyValue.RAW_COMPARATOR, 1);
137 
138     // Parse load-on-open data.
139 
140     HFileBlock.BlockIterator blockIter = fsBlockReaderV2.blockRange(
141         trailer.getLoadOnOpenDataOffset(),
142         fileSize - trailer.getTrailerSize());
143 
144     // Data index. We also read statistics about the block index written after
145     // the root level.
146     dataBlockIndexReader.readMultiLevelIndexRoot(
147         blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX),
148         trailer.getDataIndexCount());
149 
150     // Meta index.
151     metaBlockIndexReader.readRootIndex(
152         blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX),
153         trailer.getMetaIndexCount());
154 
155     // File info
156     fileInfo = new FileInfo();
157     fileInfo.read(blockIter.nextBlockWithBlockType(BlockType.FILE_INFO).getByteStream());
158     lastKey = fileInfo.get(FileInfo.LASTKEY);
159     avgKeyLen = Bytes.toInt(fileInfo.get(FileInfo.AVG_KEY_LEN));
160     avgValueLen = Bytes.toInt(fileInfo.get(FileInfo.AVG_VALUE_LEN));
161     byte [] keyValueFormatVersion =
162         fileInfo.get(HFileWriterV2.KEY_VALUE_VERSION);
163     includesMemstoreTS = keyValueFormatVersion != null &&
164         Bytes.toInt(keyValueFormatVersion) ==
165             HFileWriterV2.KEY_VALUE_VER_WITH_MEMSTORE;
166     fsBlockReaderV2.setIncludesMemstoreTS(includesMemstoreTS);
167     if (includesMemstoreTS) {
168       decodeMemstoreTS = Bytes.toLong(fileInfo.get(HFileWriterV2.MAX_MEMSTORE_TS_KEY)) > 0;
169     }
170 
171     // Read data block encoding algorithm name from file info.
172     dataBlockEncoder = HFileDataBlockEncoderImpl.createFromFileInfo(fileInfo);
173     fsBlockReaderV2.setDataBlockEncoder(dataBlockEncoder);
174 
175     // Store all other load-on-open blocks for further consumption.
176     HFileBlock b;
177     while ((b = blockIter.nextBlock()) != null) {
178       loadOnOpenBlocks.add(b);
179     }
180 
181     // Prefetch file blocks upon open if requested
182     if (cacheConf.shouldPrefetchOnOpen()) {
183       PrefetchExecutor.request(path, new Runnable() {
184         public void run() {
185           try {
186             long offset = 0;
187             long end = fileSize - getTrailer().getTrailerSize();
188             HFileBlock prevBlock = null;
189             while (offset < end) {
190               if (Thread.interrupted()) {
191                 break;
192               }
193               long onDiskSize = -1;
194               if (prevBlock != null) {
195                 onDiskSize = prevBlock.getNextBlockOnDiskSizeWithHeader();
196               }
197               HFileBlock block = readBlock(offset, onDiskSize, true, false, false, false, null);
198               prevBlock = block;
199               offset += block.getOnDiskSizeWithHeader();
200             }
201           } catch (IOException e) {
202             // IOExceptions are probably due to region closes (relocation, etc.)
203             if (LOG.isTraceEnabled()) {
204               LOG.trace("Exception encountered while prefetching " + path + ":", e);
205             }
206           } catch (Exception e) {
207             // Other exceptions are interesting
208             LOG.warn("Exception encountered while prefetching " + path + ":", e);
209           } finally {
210             PrefetchExecutor.complete(path);
211           }
212         }
213       });
214     }
215   }
216 
217   protected HFileContext createHFileContext(FSDataInputStreamWrapper fsdis, long fileSize,
218       HFileSystem hfs, Path path, FixedFileTrailer trailer) throws IOException {
219     return new HFileContextBuilder()
220       .withIncludesMvcc(this.includesMemstoreTS)
221       .withCompression(this.compressAlgo)
222       .withHBaseCheckSum(trailer.getMinorVersion() >= MINOR_VERSION_WITH_CHECKSUM)
223       .build();
224   }
225 
226   /**
227    * Create a Scanner on this file. No seeks or reads are done on creation. Call
228    * {@link HFileScanner#seekTo(byte[])} to position an start the read. There is
229    * nothing to clean up in a Scanner. Letting go of your references to the
230    * scanner is sufficient.
231    *
232    * @param cacheBlocks True if we should cache blocks read in by this scanner.
233    * @param pread Use positional read rather than seek+read if true (pread is
234    *          better for random reads, seek+read is better scanning).
235    * @param isCompaction is scanner being used for a compaction?
236    * @return Scanner on this file.
237    */
238    @Override
239    public HFileScanner getScanner(boolean cacheBlocks, final boolean pread,
240       final boolean isCompaction) {
241     if (dataBlockEncoder.useEncodedScanner()) {
242       return new EncodedScannerV2(this, cacheBlocks, pread, isCompaction,
243           hfileContext);
244     }
245 
246     return new ScannerV2(this, cacheBlocks, pread, isCompaction);
247   }
248 
249   /**
250    * @param metaBlockName
251    * @param cacheBlock Add block to cache, if found
252    * @return block wrapped in a ByteBuffer, with header skipped
253    * @throws IOException
254    */
255   @Override
256   public ByteBuffer getMetaBlock(String metaBlockName, boolean cacheBlock)
257       throws IOException {
258     if (trailer.getMetaIndexCount() == 0) {
259       return null; // there are no meta blocks
260     }
261     if (metaBlockIndexReader == null) {
262       throw new IOException("Meta index not loaded");
263     }
264 
265     byte[] mbname = Bytes.toBytes(metaBlockName);
266     int block = metaBlockIndexReader.rootBlockContainingKey(mbname, 0,
267         mbname.length);
268     if (block == -1)
269       return null;
270     long blockSize = metaBlockIndexReader.getRootBlockDataSize(block);
271 
272     // Per meta key from any given file, synchronize reads for said block. This
273     // is OK to do for meta blocks because the meta block index is always
274     // single-level.
275     synchronized (metaBlockIndexReader.getRootBlockKey(block)) {
276       // Check cache for block. If found return.
277       long metaBlockOffset = metaBlockIndexReader.getRootBlockOffset(block);
278       BlockCacheKey cacheKey = new BlockCacheKey(name, metaBlockOffset,
279           DataBlockEncoding.NONE, BlockType.META);
280 
281       cacheBlock &= cacheConf.shouldCacheDataOnRead();
282       if (cacheConf.isBlockCacheEnabled()) {
283         HFileBlock cachedBlock =
284           (HFileBlock) cacheConf.getBlockCache().getBlock(cacheKey, cacheBlock, false, true);
285         if (cachedBlock != null) {
286           // Return a distinct 'shallow copy' of the block,
287           // so pos does not get messed by the scanner
288           return cachedBlock.getBufferWithoutHeader();
289         }
290         // Cache Miss, please load.
291       }
292 
293       HFileBlock metaBlock = fsBlockReader.readBlockData(metaBlockOffset,
294           blockSize, -1, true);
295 
296       // Cache the block
297       if (cacheBlock) {
298         cacheConf.getBlockCache().cacheBlock(cacheKey, metaBlock,
299             cacheConf.isInMemory());
300       }
301 
302       return metaBlock.getBufferWithoutHeader();
303     }
304   }
305 
306   /**
307    * Read in a file block.
308    * @param dataBlockOffset offset to read.
309    * @param onDiskBlockSize size of the block
310    * @param cacheBlock
311    * @param pread Use positional read instead of seek+read (positional is
312    *          better doing random reads whereas seek+read is better scanning).
313    * @param isCompaction is this block being read as part of a compaction
314    * @param expectedBlockType the block type we are expecting to read with this
315    *          read operation, or null to read whatever block type is available
316    *          and avoid checking (that might reduce caching efficiency of
317    *          encoded data blocks)
318    * @return Block wrapped in a ByteBuffer.
319    * @throws IOException
320    */
321   @Override
322   public HFileBlock readBlock(long dataBlockOffset, long onDiskBlockSize,
323       final boolean cacheBlock, boolean pread, final boolean isCompaction,
324       final boolean updateCacheMetrics, BlockType expectedBlockType)
325       throws IOException {
326     if (dataBlockIndexReader == null) {
327       throw new IOException("Block index not loaded");
328     }
329     if (dataBlockOffset < 0
330         || dataBlockOffset >= trailer.getLoadOnOpenDataOffset()) {
331       throw new IOException("Requested block is out of range: "
332           + dataBlockOffset + ", lastDataBlockOffset: "
333           + trailer.getLastDataBlockOffset());
334     }
335     // For any given block from any given file, synchronize reads for said
336     // block.
337     // Without a cache, this synchronizing is needless overhead, but really
338     // the other choice is to duplicate work (which the cache would prevent you
339     // from doing).
340 
341     BlockCacheKey cacheKey =
342         new BlockCacheKey(name, dataBlockOffset,
343             dataBlockEncoder.getDataBlockEncoding(),
344             expectedBlockType);
345 
346     boolean useLock = false;
347     IdLock.Entry lockEntry = null;
348     TraceScope traceScope = Trace.startSpan("HFileReaderV2.readBlock");
349     try {
350       while (true) {
351         if (useLock) {
352           lockEntry = offsetLock.getLockEntry(dataBlockOffset);
353         }
354 
355         // Check cache for block. If found return.
356         if (cacheConf.isBlockCacheEnabled()) {
357           // Try and get the block from the block cache. If the useLock variable is true then this
358           // is the second time through the loop and it should not be counted as a block cache miss.
359           HFileBlock cachedBlock = (HFileBlock) cacheConf.getBlockCache().getBlock(cacheKey, 
360             cacheBlock, useLock, updateCacheMetrics);
361           if (cachedBlock != null) {
362             validateBlockType(cachedBlock, expectedBlockType);
363             if (cachedBlock.getBlockType().isData()) {
364               HFile.dataBlockReadCnt.incrementAndGet();
365 
366               // Validate encoding type for data blocks. We include encoding
367               // type in the cache key, and we expect it to match on a cache hit.
368               if (cachedBlock.getDataBlockEncoding() != dataBlockEncoder.getDataBlockEncoding()) {
369                 throw new IOException("Cached block under key " + cacheKey + " "
370                   + "has wrong encoding: " + cachedBlock.getDataBlockEncoding() + " (expected: "
371                   + dataBlockEncoder.getDataBlockEncoding() + ")");
372               }
373             }
374             return cachedBlock;
375           }
376           // Carry on, please load.
377         }
378         if (!useLock) {
379           // check cache again with lock
380           useLock = true;
381           continue;
382         }
383         if (Trace.isTracing()) {
384           traceScope.getSpan().addTimelineAnnotation("blockCacheMiss");
385         }
386         // Load block from filesystem.
387         HFileBlock hfileBlock = fsBlockReader.readBlockData(dataBlockOffset, onDiskBlockSize, -1,
388             pread);
389         validateBlockType(hfileBlock, expectedBlockType);
390 
391         // Cache the block if necessary
392         if (cacheBlock && cacheConf.shouldCacheBlockOnRead(hfileBlock.getBlockType().getCategory())) {
393           cacheConf.getBlockCache().cacheBlock(cacheKey, hfileBlock, cacheConf.isInMemory());
394         }
395 
396         if (updateCacheMetrics && hfileBlock.getBlockType().isData()) {
397           HFile.dataBlockReadCnt.incrementAndGet();
398         }
399 
400         return hfileBlock;
401       }
402     } finally {
403       traceScope.close();
404       if (lockEntry != null) {
405         offsetLock.releaseLockEntry(lockEntry);
406       }
407     }
408   }
409 
410   @Override
411   public boolean hasMVCCInfo() {
412     return includesMemstoreTS && decodeMemstoreTS;
413   }
414 
415   /**
416    * Compares the actual type of a block retrieved from cache or disk with its
417    * expected type and throws an exception in case of a mismatch. Expected
418    * block type of {@link BlockType#DATA} is considered to match the actual
419    * block type [@link {@link BlockType#ENCODED_DATA} as well.
420    * @param block a block retrieved from cache or disk
421    * @param expectedBlockType the expected block type, or null to skip the
422    *          check
423    */
424   private void validateBlockType(HFileBlock block,
425       BlockType expectedBlockType) throws IOException {
426     if (expectedBlockType == null) {
427       return;
428     }
429     BlockType actualBlockType = block.getBlockType();
430     if (actualBlockType == BlockType.ENCODED_DATA &&
431         expectedBlockType == BlockType.DATA) {
432       // We consider DATA to match ENCODED_DATA for the purpose of this
433       // verification.
434       return;
435     }
436     if (actualBlockType != expectedBlockType) {
437       throw new IOException("Expected block type " + expectedBlockType + ", " +
438           "but got " + actualBlockType + ": " + block);
439     }
440   }
441 
442   /**
443    * @return Last key in the file. May be null if file has no entries. Note that
444    *         this is not the last row key, but rather the byte form of the last
445    *         KeyValue.
446    */
447   @Override
448   public byte[] getLastKey() {
449     return dataBlockIndexReader.isEmpty() ? null : lastKey;
450   }
451 
452   /**
453    * @return Midkey for this file. We work with block boundaries only so
454    *         returned midkey is an approximation only.
455    * @throws IOException
456    */
457   @Override
458   public byte[] midkey() throws IOException {
459     return dataBlockIndexReader.midkey();
460   }
461 
462   @Override
463   public void close() throws IOException {
464     close(cacheConf.shouldEvictOnClose());
465   }
466 
467   public void close(boolean evictOnClose) throws IOException {
468     PrefetchExecutor.cancel(path);
469     if (evictOnClose && cacheConf.isBlockCacheEnabled()) {
470       int numEvicted = cacheConf.getBlockCache().evictBlocksByHfileName(name);
471       if (LOG.isTraceEnabled()) {
472         LOG.trace("On close, file=" + name + " evicted=" + numEvicted
473           + " block(s)");
474       }
475     }
476     fsBlockReader.closeStreams();
477   }
478 
479   /** For testing */
480   @Override
481   HFileBlock.FSReader getUncachedBlockReader() {
482     return fsBlockReader;
483   }
484 
485 
486   protected abstract static class AbstractScannerV2
487       extends AbstractHFileReader.Scanner {
488     protected HFileBlock block;
489 
490     /**
491      * The next indexed key is to keep track of the indexed key of the next data block.
492      * If the nextIndexedKey is HConstants.NO_NEXT_INDEXED_KEY, it means that the
493      * current data block is the last data block.
494      *
495      * If the nextIndexedKey is null, it means the nextIndexedKey has not been loaded yet.
496      */
497     protected byte[] nextIndexedKey;
498 
499     public AbstractScannerV2(HFileReaderV2 r, boolean cacheBlocks,
500         final boolean pread, final boolean isCompaction) {
501       super(r, cacheBlocks, pread, isCompaction);
502     }
503 
504     /**
505      * An internal API function. Seek to the given key, optionally rewinding to
506      * the first key of the block before doing the seek.
507      *
508      * @param key key byte array
509      * @param offset key offset in the key byte array
510      * @param length key length
511      * @param rewind whether to rewind to the first key of the block before
512      *        doing the seek. If this is false, we are assuming we never go
513      *        back, otherwise the result is undefined.
514      * @return -1 if the key is earlier than the first key of the file,
515      *         0 if we are at the given key, 1 if we are past the given key
516      *         -2 if the key is earlier than the first key of the file while
517      *         using a faked index key
518      * @throws IOException
519      */
520     protected int seekTo(byte[] key, int offset, int length, boolean rewind)
521         throws IOException {
522       HFileBlockIndex.BlockIndexReader indexReader =
523           reader.getDataBlockIndexReader();
524       BlockWithScanInfo blockWithScanInfo =
525         indexReader.loadDataBlockWithScanInfo(key, offset, length, block,
526             cacheBlocks, pread, isCompaction);
527       if (blockWithScanInfo == null || blockWithScanInfo.getHFileBlock() == null) {
528         // This happens if the key e.g. falls before the beginning of the file.
529         return -1;
530       }
531       return loadBlockAndSeekToKey(blockWithScanInfo.getHFileBlock(),
532           blockWithScanInfo.getNextIndexedKey(), rewind, key, offset, length, false);
533     }
534 
535     protected abstract ByteBuffer getFirstKeyInBlock(HFileBlock curBlock);
536 
537     protected abstract int loadBlockAndSeekToKey(HFileBlock seekToBlock, byte[] nextIndexedKey,
538         boolean rewind, byte[] key, int offset, int length, boolean seekBefore)
539         throws IOException;
540 
541     @Override
542     public int seekTo(byte[] key, int offset, int length) throws IOException {
543       // Always rewind to the first key of the block, because the given key
544       // might be before or after the current key.
545       return seekTo(key, offset, length, true);
546     }
547 
548     @Override
549     public int reseekTo(byte[] key, int offset, int length) throws IOException {
550       int compared;
551       if (isSeeked()) {
552         compared = compareKey(reader.getComparator(), key, offset, length);
553         if (compared < 1) {
554           // If the required key is less than or equal to current key, then
555           // don't do anything.
556           return compared;
557         } else {
558           if (this.nextIndexedKey != null &&
559               (this.nextIndexedKey == HConstants.NO_NEXT_INDEXED_KEY ||
560                reader.getComparator().compareFlatKey(key, offset, length,
561                    nextIndexedKey, 0, nextIndexedKey.length) < 0)) {
562             // The reader shall continue to scan the current data block instead of querying the
563             // block index as long as it knows the target key is strictly smaller than
564             // the next indexed key or the current data block is the last data block.
565             return loadBlockAndSeekToKey(this.block, this.nextIndexedKey,
566                 false, key, offset, length, false);
567           }
568         }
569       }
570       // Don't rewind on a reseek operation, because reseek implies that we are
571       // always going forward in the file.
572       return seekTo(key, offset, length, false);
573     }
574 
575     @Override
576     public boolean seekBefore(byte[] key, int offset, int length)
577         throws IOException {
578       HFileBlock seekToBlock =
579           reader.getDataBlockIndexReader().seekToDataBlock(key, offset, length,
580               block, cacheBlocks, pread, isCompaction);
581       if (seekToBlock == null) {
582         return false;
583       }
584       ByteBuffer firstKey = getFirstKeyInBlock(seekToBlock);
585 
586       if (reader.getComparator().compareFlatKey(firstKey.array(),
587           firstKey.arrayOffset(), firstKey.limit(), key, offset, length) >= 0)
588       {
589         long previousBlockOffset = seekToBlock.getPrevBlockOffset();
590         // The key we are interested in
591         if (previousBlockOffset == -1) {
592           // we have a 'problem', the key we want is the first of the file.
593           return false;
594         }
595 
596         // It is important that we compute and pass onDiskSize to the block
597         // reader so that it does not have to read the header separately to
598         // figure out the size.
599         seekToBlock = reader.readBlock(previousBlockOffset,
600             seekToBlock.getOffset() - previousBlockOffset, cacheBlocks,
601             pread, isCompaction, true, BlockType.DATA);
602         // TODO shortcut: seek forward in this block to the last key of the
603         // block.
604       }
605       byte[] firstKeyInCurrentBlock = Bytes.getBytes(firstKey);
606       loadBlockAndSeekToKey(seekToBlock, firstKeyInCurrentBlock, true, key, offset, length, true);
607       return true;
608     }
609 
610 
611     /**
612      * Scans blocks in the "scanned" section of the {@link HFile} until the next
613      * data block is found.
614      *
615      * @return the next block, or null if there are no more data blocks
616      * @throws IOException
617      */
618     protected HFileBlock readNextDataBlock() throws IOException {
619       long lastDataBlockOffset = reader.getTrailer().getLastDataBlockOffset();
620       if (block == null)
621         return null;
622 
623       HFileBlock curBlock = block;
624 
625       do {
626         if (curBlock.getOffset() >= lastDataBlockOffset)
627           return null;
628 
629         if (curBlock.getOffset() < 0) {
630           throw new IOException("Invalid block file offset: " + block);
631         }
632 
633         // We are reading the next block without block type validation, because
634         // it might turn out to be a non-data block.
635         curBlock = reader.readBlock(curBlock.getOffset()
636             + curBlock.getOnDiskSizeWithHeader(),
637             curBlock.getNextBlockOnDiskSizeWithHeader(), cacheBlocks, pread,
638             isCompaction, true, null);
639       } while (!curBlock.getBlockType().isData());
640 
641       return curBlock;
642     }
643     /**
644      * Compare the given key against the current key
645      * @param comparator
646      * @param key
647      * @param offset
648      * @param length
649      * @return -1 is the passed key is smaller than the current key, 0 if equal and 1 if greater
650      */
651     public abstract int compareKey(KVComparator comparator, byte[] key, int offset,
652         int length);
653   }
654 
655   /**
656    * Implementation of {@link HFileScanner} interface.
657    */
658   protected static class ScannerV2 extends AbstractScannerV2 {
659     private HFileReaderV2 reader;
660 
661     public ScannerV2(HFileReaderV2 r, boolean cacheBlocks,
662         final boolean pread, final boolean isCompaction) {
663       super(r, cacheBlocks, pread, isCompaction);
664       this.reader = r;
665     }
666 
667     @Override
668     public KeyValue getKeyValue() {
669       if (!isSeeked())
670         return null;
671 
672       KeyValue ret = new KeyValue(blockBuffer.array(), blockBuffer.arrayOffset()
673           + blockBuffer.position(), getCellBufSize());
674       if (this.reader.shouldIncludeMemstoreTS()) {
675         ret.setMvccVersion(currMemstoreTS);
676       }
677       return ret;
678     }
679 
680     protected int getCellBufSize() {
681       return KEY_VALUE_LEN_SIZE + currKeyLen + currValueLen;
682     }
683 
684     @Override
685     public ByteBuffer getKey() {
686       assertSeeked();
687       return ByteBuffer.wrap(
688           blockBuffer.array(),
689           blockBuffer.arrayOffset() + blockBuffer.position()
690               + KEY_VALUE_LEN_SIZE, currKeyLen).slice();
691     }
692 
693     @Override
694     public int compareKey(KVComparator comparator, byte[] key, int offset, int length) {
695       return comparator.compareFlatKey(key, offset, length, blockBuffer.array(),
696           blockBuffer.arrayOffset() + blockBuffer.position() + KEY_VALUE_LEN_SIZE, currKeyLen);
697     }
698 
699     @Override
700     public ByteBuffer getValue() {
701       assertSeeked();
702       return ByteBuffer.wrap(
703           blockBuffer.array(),
704           blockBuffer.arrayOffset() + blockBuffer.position()
705               + KEY_VALUE_LEN_SIZE + currKeyLen, currValueLen).slice();
706     }
707 
708     protected void setNonSeekedState() {
709       block = null;
710       blockBuffer = null;
711       currKeyLen = 0;
712       currValueLen = 0;
713       currMemstoreTS = 0;
714       currMemstoreTSLen = 0;
715     }
716 
717     /**
718      * Go to the next key/value in the block section. Loads the next block if
719      * necessary. If successful, {@link #getKey()} and {@link #getValue()} can
720      * be called.
721      *
722      * @return true if successfully navigated to the next key/value
723      */
724     @Override
725     public boolean next() throws IOException {
726       assertSeeked();
727 
728       try {
729         blockBuffer.position(getNextCellStartPosition());
730       } catch (IllegalArgumentException e) {
731         LOG.error("Current pos = " + blockBuffer.position()
732             + "; currKeyLen = " + currKeyLen + "; currValLen = "
733             + currValueLen + "; block limit = " + blockBuffer.limit()
734             + "; HFile name = " + reader.getName()
735             + "; currBlock currBlockOffset = " + block.getOffset());
736         throw e;
737       }
738 
739       if (blockBuffer.remaining() <= 0) {
740         long lastDataBlockOffset =
741             reader.getTrailer().getLastDataBlockOffset();
742 
743         if (block.getOffset() >= lastDataBlockOffset) {
744           setNonSeekedState();
745           return false;
746         }
747 
748         // read the next block
749         HFileBlock nextBlock = readNextDataBlock();
750         if (nextBlock == null) {
751           setNonSeekedState();
752           return false;
753         }
754 
755         updateCurrBlock(nextBlock);
756         return true;
757       }
758 
759       // We are still in the same block.
760       readKeyValueLen();
761       return true;
762     }
763 
764     protected int getNextCellStartPosition() {
765       return blockBuffer.position() + KEY_VALUE_LEN_SIZE + currKeyLen + currValueLen
766           + currMemstoreTSLen;
767     }
768 
769     /**
770      * Positions this scanner at the start of the file.
771      *
772      * @return false if empty file; i.e. a call to next would return false and
773      *         the current key and value are undefined.
774      * @throws IOException
775      */
776     @Override
777     public boolean seekTo() throws IOException {
778       if (reader == null) {
779         return false;
780       }
781 
782       if (reader.getTrailer().getEntryCount() == 0) {
783         // No data blocks.
784         return false;
785       }
786 
787       long firstDataBlockOffset =
788           reader.getTrailer().getFirstDataBlockOffset();
789       if (block != null && block.getOffset() == firstDataBlockOffset) {
790         blockBuffer.rewind();
791         readKeyValueLen();
792         return true;
793       }
794 
795       block = reader.readBlock(firstDataBlockOffset, -1, cacheBlocks, pread,
796           isCompaction, true, BlockType.DATA);
797       if (block.getOffset() < 0) {
798         throw new IOException("Invalid block offset: " + block.getOffset());
799       }
800       updateCurrBlock(block);
801       return true;
802     }
803 
804     @Override
805     protected int loadBlockAndSeekToKey(HFileBlock seekToBlock, byte[] nextIndexedKey,
806         boolean rewind, byte[] key, int offset, int length, boolean seekBefore)
807         throws IOException {
808       if (block == null || block.getOffset() != seekToBlock.getOffset()) {
809         updateCurrBlock(seekToBlock);
810       } else if (rewind) {
811         blockBuffer.rewind();
812       }
813 
814       // Update the nextIndexedKey
815       this.nextIndexedKey = nextIndexedKey;
816       return blockSeek(key, offset, length, seekBefore);
817     }
818 
819     /**
820      * Updates the current block to be the given {@link HFileBlock}. Seeks to
821      * the the first key/value pair.
822      *
823      * @param newBlock the block to make current
824      */
825     protected void updateCurrBlock(HFileBlock newBlock) {
826       block = newBlock;
827 
828       // sanity check
829       if (block.getBlockType() != BlockType.DATA) {
830         throw new IllegalStateException("ScannerV2 works only on data " +
831             "blocks, got " + block.getBlockType() + "; " +
832             "fileName=" + reader.name + ", " +
833             "dataBlockEncoder=" + reader.dataBlockEncoder + ", " +
834             "isCompaction=" + isCompaction);
835       }
836 
837       blockBuffer = block.getBufferWithoutHeader();
838       readKeyValueLen();
839       blockFetches++;
840 
841       // Reset the next indexed key
842       this.nextIndexedKey = null;
843     }
844 
845     protected void readKeyValueLen() {
846       blockBuffer.mark();
847       currKeyLen = blockBuffer.getInt();
848       currValueLen = blockBuffer.getInt();
849       ByteBufferUtils.skip(blockBuffer, currKeyLen + currValueLen);
850       readMvccVersion();
851       if (currKeyLen < 0 || currValueLen < 0
852           || currKeyLen > blockBuffer.limit()
853           || currValueLen > blockBuffer.limit()) {
854         throw new IllegalStateException("Invalid currKeyLen " + currKeyLen
855             + " or currValueLen " + currValueLen + ". Block offset: "
856             + block.getOffset() + ", block length: " + blockBuffer.limit()
857             + ", position: " + blockBuffer.position() + " (without header).");
858       }
859       blockBuffer.reset();
860     }
861 
862     protected void readMvccVersion() {
863       if (this.reader.shouldIncludeMemstoreTS()) {
864         if (this.reader.decodeMemstoreTS) {
865           try {
866             currMemstoreTS = Bytes.readVLong(blockBuffer.array(), blockBuffer.arrayOffset()
867                 + blockBuffer.position());
868             currMemstoreTSLen = WritableUtils.getVIntSize(currMemstoreTS);
869           } catch (Exception e) {
870             throw new RuntimeException("Error reading memstore timestamp", e);
871           }
872         } else {
873           currMemstoreTS = 0;
874           currMemstoreTSLen = 1;
875         }
876       }
877     }
878 
879     /**
880      * Within a loaded block, seek looking for the last key that is smaller
881      * than (or equal to?) the key we are interested in.
882      *
883      * A note on the seekBefore: if you have seekBefore = true, AND the first
884      * key in the block = key, then you'll get thrown exceptions. The caller has
885      * to check for that case and load the previous block as appropriate.
886      *
887      * @param key the key to find
888      * @param seekBefore find the key before the given key in case of exact
889      *          match.
890      * @return 0 in case of an exact key match, 1 in case of an inexact match,
891      *         -2 in case of an inexact match and furthermore, the input key less
892      *         than the first key of current block(e.g. using a faked index key)
893      */
894     protected int blockSeek(byte[] key, int offset, int length,
895         boolean seekBefore) {
896       int klen, vlen;
897       long memstoreTS = 0;
898       int memstoreTSLen = 0;
899       int lastKeyValueSize = -1;
900       do {
901         blockBuffer.mark();
902         klen = blockBuffer.getInt();
903         vlen = blockBuffer.getInt();
904         blockBuffer.reset();
905         if (this.reader.shouldIncludeMemstoreTS()) {
906           if (this.reader.decodeMemstoreTS) {
907             try {
908               int memstoreTSOffset = blockBuffer.arrayOffset()
909                   + blockBuffer.position() + KEY_VALUE_LEN_SIZE + klen + vlen;
910               memstoreTS = Bytes.readVLong(blockBuffer.array(),
911                   memstoreTSOffset);
912               memstoreTSLen = WritableUtils.getVIntSize(memstoreTS);
913             } catch (Exception e) {
914               throw new RuntimeException("Error reading memstore timestamp", e);
915             }
916           } else {
917             memstoreTS = 0;
918             memstoreTSLen = 1;
919           }
920         }
921 
922         int keyOffset = blockBuffer.arrayOffset() + blockBuffer.position()
923             + KEY_VALUE_LEN_SIZE;
924         int comp = reader.getComparator().compareFlatKey(key, offset, length,
925             blockBuffer.array(), keyOffset, klen);
926 
927         if (comp == 0) {
928           if (seekBefore) {
929             if (lastKeyValueSize < 0) {
930               throw new IllegalStateException("blockSeek with seekBefore "
931                   + "at the first key of the block: key="
932                   + Bytes.toStringBinary(key) + ", blockOffset="
933                   + block.getOffset() + ", onDiskSize="
934                   + block.getOnDiskSizeWithHeader());
935             }
936             blockBuffer.position(blockBuffer.position() - lastKeyValueSize);
937             readKeyValueLen();
938             return 1; // non exact match.
939           }
940           currKeyLen = klen;
941           currValueLen = vlen;
942           if (this.reader.shouldIncludeMemstoreTS()) {
943             currMemstoreTS = memstoreTS;
944             currMemstoreTSLen = memstoreTSLen;
945           }
946           return 0; // indicate exact match
947         } else if (comp < 0) {
948           if (lastKeyValueSize > 0)
949             blockBuffer.position(blockBuffer.position() - lastKeyValueSize);
950           readKeyValueLen();
951           if (lastKeyValueSize == -1 && blockBuffer.position() == 0
952               && this.reader.trailer.getMinorVersion() >= MINOR_VERSION_WITH_FAKED_KEY) {
953             return HConstants.INDEX_KEY_MAGIC;
954           }
955           return 1;
956         }
957 
958         // The size of this key/value tuple, including key/value length fields.
959         lastKeyValueSize = klen + vlen + memstoreTSLen + KEY_VALUE_LEN_SIZE;
960         blockBuffer.position(blockBuffer.position() + lastKeyValueSize);
961       } while (blockBuffer.remaining() > 0);
962 
963       // Seek to the last key we successfully read. This will happen if this is
964       // the last key/value pair in the file, in which case the following call
965       // to next() has to return false.
966       blockBuffer.position(blockBuffer.position() - lastKeyValueSize);
967       readKeyValueLen();
968       return 1; // didn't exactly find it.
969     }
970 
971     @Override
972     protected ByteBuffer getFirstKeyInBlock(HFileBlock curBlock) {
973       ByteBuffer buffer = curBlock.getBufferWithoutHeader();
974       // It is safe to manipulate this buffer because we own the buffer object.
975       buffer.rewind();
976       int klen = buffer.getInt();
977       buffer.getInt();
978       ByteBuffer keyBuff = buffer.slice();
979       keyBuff.limit(klen);
980       keyBuff.rewind();
981       return keyBuff;
982     }
983 
984     @Override
985     public String getKeyString() {
986       return Bytes.toStringBinary(blockBuffer.array(),
987           blockBuffer.arrayOffset() + blockBuffer.position()
988               + KEY_VALUE_LEN_SIZE, currKeyLen);
989     }
990 
991     @Override
992     public String getValueString() {
993       return Bytes.toString(blockBuffer.array(), blockBuffer.arrayOffset()
994           + blockBuffer.position() + KEY_VALUE_LEN_SIZE + currKeyLen,
995           currValueLen);
996     }
997   }
998 
999   /**
1000    * ScannerV2 that operates on encoded data blocks.
1001    */
1002   protected static class EncodedScannerV2 extends AbstractScannerV2 {
1003     private final HFileBlockDecodingContext decodingCtx;
1004     private final DataBlockEncoder.EncodedSeeker seeker;
1005     private final DataBlockEncoder dataBlockEncoder;
1006     protected final HFileContext meta;
1007 
1008     public EncodedScannerV2(HFileReaderV2 reader, boolean cacheBlocks,
1009         boolean pread, boolean isCompaction, HFileContext meta) {
1010       super(reader, cacheBlocks, pread, isCompaction);
1011       DataBlockEncoding encoding = reader.dataBlockEncoder.getDataBlockEncoding();
1012       dataBlockEncoder = encoding.getEncoder();
1013       decodingCtx = dataBlockEncoder.newDataBlockDecodingContext(meta);
1014       seeker = dataBlockEncoder.createSeeker(
1015         reader.getComparator(), decodingCtx);
1016       this.meta = meta;
1017     }
1018 
1019     @Override
1020     public boolean isSeeked(){
1021       return this.block != null;
1022     }
1023 
1024     /**
1025      * Updates the current block to be the given {@link HFileBlock}. Seeks to
1026      * the the first key/value pair.
1027      *
1028      * @param newBlock the block to make current
1029      * @throws CorruptHFileException
1030      */
1031     private void updateCurrentBlock(HFileBlock newBlock) throws CorruptHFileException {
1032       block = newBlock;
1033 
1034       // sanity checks
1035       if (block.getBlockType() != BlockType.ENCODED_DATA) {
1036         throw new IllegalStateException(
1037             "EncodedScanner works only on encoded data blocks");
1038       }
1039       short dataBlockEncoderId = block.getDataBlockEncodingId();
1040       if (!DataBlockEncoding.isCorrectEncoder(dataBlockEncoder, dataBlockEncoderId)) {
1041         String encoderCls = dataBlockEncoder.getClass().getName();
1042         throw new CorruptHFileException("Encoder " + encoderCls
1043           + " doesn't support data block encoding "
1044           + DataBlockEncoding.getNameFromId(dataBlockEncoderId));
1045       }
1046 
1047       seeker.setCurrentBuffer(getEncodedBuffer(newBlock));
1048       blockFetches++;
1049 
1050       // Reset the next indexed key
1051       this.nextIndexedKey = null;
1052     }
1053 
1054     private ByteBuffer getEncodedBuffer(HFileBlock newBlock) {
1055       ByteBuffer origBlock = newBlock.getBufferReadOnly();
1056       ByteBuffer encodedBlock = ByteBuffer.wrap(origBlock.array(),
1057           origBlock.arrayOffset() + newBlock.headerSize() +
1058           DataBlockEncoding.ID_SIZE,
1059           newBlock.getUncompressedSizeWithoutHeader() -
1060           DataBlockEncoding.ID_SIZE).slice();
1061       return encodedBlock;
1062     }
1063 
1064     @Override
1065     public boolean seekTo() throws IOException {
1066       if (reader == null) {
1067         return false;
1068       }
1069 
1070       if (reader.getTrailer().getEntryCount() == 0) {
1071         // No data blocks.
1072         return false;
1073       }
1074 
1075       long firstDataBlockOffset =
1076           reader.getTrailer().getFirstDataBlockOffset();
1077       if (block != null && block.getOffset() == firstDataBlockOffset) {
1078         seeker.rewind();
1079         return true;
1080       }
1081 
1082       block = reader.readBlock(firstDataBlockOffset, -1, cacheBlocks, pread,
1083           isCompaction, true, BlockType.DATA);
1084       if (block.getOffset() < 0) {
1085         throw new IOException("Invalid block offset: " + block.getOffset());
1086       }
1087       updateCurrentBlock(block);
1088       return true;
1089     }
1090 
1091     @Override
1092     public boolean next() throws IOException {
1093       boolean isValid = seeker.next();
1094       if (!isValid) {
1095         block = readNextDataBlock();
1096         isValid = block != null;
1097         if (isValid) {
1098           updateCurrentBlock(block);
1099         }
1100       }
1101       return isValid;
1102     }
1103 
1104     @Override
1105     public ByteBuffer getKey() {
1106       assertValidSeek();
1107       return seeker.getKeyDeepCopy();
1108     }
1109 
1110     @Override
1111     public int compareKey(KVComparator comparator, byte[] key, int offset, int length) {
1112       return seeker.compareKey(comparator, key, offset, length);
1113     }
1114 
1115     @Override
1116     public ByteBuffer getValue() {
1117       assertValidSeek();
1118       return seeker.getValueShallowCopy();
1119     }
1120 
1121     @Override
1122     public KeyValue getKeyValue() {
1123       if (block == null) {
1124         return null;
1125       }
1126       return seeker.getKeyValue();
1127     }
1128 
1129     @Override
1130     public String getKeyString() {
1131       ByteBuffer keyBuffer = getKey();
1132       return Bytes.toStringBinary(keyBuffer.array(),
1133           keyBuffer.arrayOffset(), keyBuffer.limit());
1134     }
1135 
1136     @Override
1137     public String getValueString() {
1138       ByteBuffer valueBuffer = getValue();
1139       return Bytes.toStringBinary(valueBuffer.array(),
1140           valueBuffer.arrayOffset(), valueBuffer.limit());
1141     }
1142 
1143     private void assertValidSeek() {
1144       if (block == null) {
1145         throw new NotSeekedException();
1146       }
1147     }
1148 
1149     @Override
1150     protected ByteBuffer getFirstKeyInBlock(HFileBlock curBlock) {
1151       return dataBlockEncoder.getFirstKeyInBlock(getEncodedBuffer(curBlock));
1152     }
1153 
1154     @Override
1155     protected int loadBlockAndSeekToKey(HFileBlock seekToBlock, byte[] nextIndexedKey,
1156         boolean rewind, byte[] key, int offset, int length, boolean seekBefore)
1157         throws IOException  {
1158       if (block == null || block.getOffset() != seekToBlock.getOffset()) {
1159         updateCurrentBlock(seekToBlock);
1160       } else if (rewind) {
1161         seeker.rewind();
1162       }
1163       this.nextIndexedKey = nextIndexedKey;
1164       return seeker.seekToKeyInBlock(key, offset, length, seekBefore);
1165     }
1166   }
1167 
1168   /**
1169    * Returns a buffer with the Bloom filter metadata. The caller takes
1170    * ownership of the buffer.
1171    */
1172   @Override
1173   public DataInput getGeneralBloomFilterMetadata() throws IOException {
1174     return this.getBloomFilterMetadata(BlockType.GENERAL_BLOOM_META);
1175   }
1176 
1177   @Override
1178   public DataInput getDeleteBloomFilterMetadata() throws IOException {
1179     return this.getBloomFilterMetadata(BlockType.DELETE_FAMILY_BLOOM_META);
1180   }
1181 
1182   private DataInput getBloomFilterMetadata(BlockType blockType)
1183   throws IOException {
1184     if (blockType != BlockType.GENERAL_BLOOM_META &&
1185         blockType != BlockType.DELETE_FAMILY_BLOOM_META) {
1186       throw new RuntimeException("Block Type: " + blockType.toString() +
1187           " is not supported") ;
1188     }
1189 
1190     for (HFileBlock b : loadOnOpenBlocks)
1191       if (b.getBlockType() == blockType)
1192         return b.getByteStream();
1193     return null;
1194   }
1195 
1196   @Override
1197   public boolean isFileInfoLoaded() {
1198     return true; // We load file info in constructor in version 2.
1199   }
1200 
1201   /**
1202    * Validates that the minor version is within acceptable limits.
1203    * Otherwise throws an Runtime exception
1204    */
1205   private void validateMinorVersion(Path path, int minorVersion) {
1206     if (minorVersion < MIN_MINOR_VERSION ||
1207         minorVersion > MAX_MINOR_VERSION) {
1208       String msg = "Minor version for path " + path + 
1209                    " is expected to be between " +
1210                    MIN_MINOR_VERSION + " and " + MAX_MINOR_VERSION +
1211                    " but is found to be " + minorVersion;
1212       LOG.error(msg);
1213       throw new RuntimeException(msg);
1214     }
1215   }
1216 
1217   @Override
1218   public int getMajorVersion() {
1219     return 2;
1220   }
1221 
1222   @Override
1223   public HFileContext getFileContext() {
1224     return hfileContext;
1225   }
1226 
1227   /**
1228    * Returns false if block prefetching was requested for this file and has
1229    * not completed, true otherwise
1230    */
1231   @VisibleForTesting
1232   boolean prefetchComplete() {
1233     return PrefetchExecutor.isCompleted(path);
1234   }
1235 }