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