1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
52
53 @InterfaceAudience.Private
54 public class HFileReaderV2 extends AbstractHFileReader {
55
56 private static final Log LOG = LogFactory.getLog(HFileReaderV2.class);
57
58
59 public static final int MINOR_VERSION_WITH_CHECKSUM = 1;
60
61 public static final int MINOR_VERSION_NO_CHECKSUM = 0;
62
63
64 public static final int PBUF_TRAILER_MINOR_VERSION = 2;
65
66
67
68
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
80 private HFileBlock.FSReader fsBlockReader;
81
82
83
84
85
86
87
88 private IdLock offsetLock = new IdLock();
89
90
91
92
93
94 private List<HFileBlock> loadOnOpenBlocks = new ArrayList<HFileBlock>();
95
96
97 static final int MIN_MINOR_VERSION = 0;
98
99
100
101
102 static final int MAX_MINOR_VERSION = 3;
103
104
105 static final int MINOR_VERSION_WITH_FAKED_KEY = 3;
106
107 HFileContext hfileContext;
108
109
110
111
112
113
114
115
116
117
118
119
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;
132
133
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
141
142 HFileBlock.BlockIterator blockIter = fsBlockReaderV2.blockRange(
143 trailer.getLoadOnOpenDataOffset(),
144 fileSize - trailer.getTrailerSize());
145
146
147
148 dataBlockIndexReader.readMultiLevelIndexRoot(
149 blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX),
150 trailer.getDataIndexCount());
151
152
153 metaBlockIndexReader.readRootIndex(
154 blockIter.nextBlockWithBlockType(BlockType.ROOT_INDEX),
155 trailer.getMetaIndexCount());
156
157
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
177 dataBlockEncoder = HFileDataBlockEncoderImpl.createFromFileInfo(fileInfo);
178 fsBlockReaderV2.setDataBlockEncoder(dataBlockEncoder);
179
180
181 HFileBlock b;
182 while ((b = blockIter.nextBlock()) != null) {
183 loadOnOpenBlocks.add(b);
184 }
185
186
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
209 if (LOG.isTraceEnabled()) {
210 LOG.trace("Exception encountered while prefetching " + path + ":", e);
211 }
212 } catch (Exception e) {
213
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
234
235
236
237
238
239
240
241
242
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
257
258
259 private HFileBlock getCachedBlock(BlockCacheKey cacheKey, boolean cacheBlock, boolean useLock,
260 boolean isCompaction, boolean updateCacheMetrics, BlockType expectedBlockType,
261 DataBlockEncoding expectedDataBlockEncoding) throws IOException {
262
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
279
280
281 if (cachedBlock.getBlockType().isData() &&
282 !actualDataBlockEncoding.equals(expectedDataBlockEncoding)) {
283
284
285
286
287
288
289
290
291
292
293 if (!expectedDataBlockEncoding.equals(DataBlockEncoding.NONE) &&
294 !actualDataBlockEncoding.equals(DataBlockEncoding.NONE)) {
295
296
297
298
299
300
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
316
317
318
319
320 @Override
321 public ByteBuffer getMetaBlock(String metaBlockName, boolean cacheBlock)
322 throws IOException {
323 if (trailer.getMetaIndexCount() == 0) {
324 return null;
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
338
339
340 synchronized (metaBlockIndexReader.getRootBlockKey(block)) {
341
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
352
353 return cachedBlock.getBufferWithoutHeader();
354 }
355
356 }
357
358 HFileBlock metaBlock = fsBlockReader.readBlockData(metaBlockOffset,
359 blockSize, -1, true).unpack(hfileContext, fsBlockReader);
360
361
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
386
387
388
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
400 if (cacheConf.isBlockCacheEnabled()) {
401
402
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
415
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
423 return cachedBlock;
424 }
425
426 }
427 if (!useLock) {
428
429 useLock = true;
430 continue;
431 }
432 if (Trace.isTracing()) {
433 traceScope.getSpan().addTimelineAnnotation("blockCacheMiss");
434 }
435
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
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
470
471
472
473
474
475
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
485
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
496
497
498
499 @Override
500 public byte[] getLastKey() {
501 return dataBlockIndexReader.isEmpty() ? null : lastKey;
502 }
503
504
505
506
507
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
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
552
553
554
555
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
572
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
593
594 return compared;
595 } else {
596
597 if (this.nextIndexedKey != null &&
598 (this.nextIndexedKey == HConstants.NO_NEXT_INDEXED_KEY || reader
599 .getComparator()
600 .compareOnlyKeyPortion(key, nextIndexedKey) < 0)) {
601
602
603
604
605
606
607 return loadBlockAndSeekToKey(this.block, nextIndexedKey, false, key, false);
608 }
609 }
610 }
611
612
613 return seekTo(key, false);
614 }
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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
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
664 if (previousBlockOffset == -1) {
665
666 return false;
667 }
668
669
670
671
672 seekToBlock = reader.readBlock(previousBlockOffset,
673 seekToBlock.getOffset() - previousBlockOffset, cacheBlocks,
674 pread, isCompaction, true, BlockType.DATA, getEffectiveDataBlockEncoding());
675
676
677 }
678 Cell firstKeyInCurrentBlock = new KeyValue.KeyOnlyKeyValue(Bytes.getBytes(firstKey));
679 loadBlockAndSeekToKey(seekToBlock, firstKeyInCurrentBlock, true, key, true);
680 return true;
681 }
682
683
684
685
686
687
688
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
706
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
721
722
723
724
725
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
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
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
813
814
815
816 private boolean positionForNextBlock() throws IOException {
817
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
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
839 if (blockBuffer.remaining() <= 0) {
840 return positionForNextBlock();
841 }
842
843 readKeyValueLen();
844 return true;
845 }
846
847
848
849
850
851
852
853
854 @Override
855 public boolean next() throws IOException {
856
857
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
870
871
872
873
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
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
913 this.nextIndexedKey = nextIndexedKey;
914 return blockSeek(key, seekBefore);
915 }
916
917
918
919
920
921
922
923 protected void updateCurrBlock(HFileBlock newBlock) {
924 block = newBlock;
925
926
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
940 this.nextIndexedKey = null;
941 }
942
943
944
945
946
947 protected final boolean checkLen(final int v) {
948 return v < 0 || v > this.blockBuffer.limit();
949 }
950
951
952
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
965
966
967
968
969 int p = blockBuffer.position() + blockBuffer.arrayOffset();
970
971
972 long ll = Bytes.toLong(blockBuffer.array(), p);
973
974 this.currKeyLen = (int)(ll >> Integer.SIZE);
975 this.currValueLen = (int)(Bytes.MASK_FOR_LOWER_INT_IN_LONG ^ ll);
976 checkKeyValueLen();
977
978 p += (Bytes.SIZEOF_LONG + currKeyLen + currValueLen);
979 readMvccVersion(p);
980 }
981
982
983
984
985
986 protected void readMvccVersion(final int position) {
987
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
999
1000
1001 private void _readMvccVersion(final int position) {
1002
1003
1004
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
1023 readMvccVersion(blockBuffer.arrayOffset() + blockBuffer.position());
1024 }
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
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;
1082 }
1083 currKeyLen = klen;
1084 currValueLen = vlen;
1085 if (this.reader.shouldIncludeMemstoreTS()) {
1086 currMemstoreTS = memstoreTS;
1087 currMemstoreTSLen = memstoreTSLen;
1088 }
1089 return 0;
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
1102 lastKeyValueSize = klen + vlen + memstoreTSLen + KEY_VALUE_LEN_SIZE;
1103 blockBuffer.position(blockBuffer.position() + lastKeyValueSize);
1104 } while (blockBuffer.remaining() > 0);
1105
1106
1107
1108
1109 blockBuffer.position(blockBuffer.position() - lastKeyValueSize);
1110 readKeyValueLen();
1111 return 1;
1112 }
1113
1114 @Override
1115 protected ByteBuffer getFirstKeyInBlock(HFileBlock curBlock) {
1116 ByteBuffer buffer = curBlock.getBufferWithoutHeader();
1117
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
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
1177
1178
1179
1180
1181
1182 private void updateCurrentBlock(HFileBlock newBlock) throws CorruptHFileException {
1183 block = newBlock;
1184
1185
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
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
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
1325
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;
1354 }
1355
1356
1357
1358
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
1384
1385
1386 @VisibleForTesting
1387 boolean prefetchComplete() {
1388 return PrefetchExecutor.isCompleted(path);
1389 }
1390 }