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.ByteArrayOutputStream;
21 import java.io.DataInputStream;
22 import java.io.DataOutput;
23 import java.io.DataOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.nio.ByteBuffer;
27 import java.util.concurrent.locks.Lock;
28 import java.util.concurrent.locks.ReentrantLock;
29
30 import org.apache.hadoop.fs.FSDataInputStream;
31 import org.apache.hadoop.fs.FSDataOutputStream;
32 import org.apache.hadoop.fs.Path;
33 import org.apache.hadoop.hbase.Cell;
34 import org.apache.hadoop.hbase.HConstants;
35 import org.apache.hadoop.hbase.classification.InterfaceAudience;
36 import org.apache.hadoop.hbase.fs.HFileSystem;
37 import org.apache.hadoop.hbase.io.ByteBufferInputStream;
38 import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
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.encoding.HFileBlockDefaultDecodingContext;
42 import org.apache.hadoop.hbase.io.encoding.HFileBlockDefaultEncodingContext;
43 import org.apache.hadoop.hbase.io.encoding.HFileBlockEncodingContext;
44 import org.apache.hadoop.hbase.util.ByteBufferUtils;
45 import org.apache.hadoop.hbase.util.Bytes;
46 import org.apache.hadoop.hbase.util.ChecksumType;
47 import org.apache.hadoop.hbase.util.ClassSize;
48 import org.apache.hadoop.io.IOUtils;
49
50 import com.google.common.base.Preconditions;
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84 @InterfaceAudience.Private
85 public class HFileBlock implements Cacheable {
86
87
88
89
90
91
92 static final int CHECKSUM_VERIFICATION_NUM_IO_THRESHOLD = 3;
93
94 public static final boolean FILL_HEADER = true;
95 public static final boolean DONT_FILL_HEADER = false;
96
97
98
99
100
101 public static final int ENCODED_HEADER_SIZE = HConstants.HFILEBLOCK_HEADER_SIZE
102 + DataBlockEncoding.ID_SIZE;
103
104 static final byte[] DUMMY_HEADER_NO_CHECKSUM =
105 new byte[HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM];
106
107 public static final int BYTE_BUFFER_HEAP_SIZE = (int) ClassSize.estimateBase(
108 ByteBuffer.wrap(new byte[0], 0, 0).getClass(), false);
109
110
111 public static final int EXTRA_SERIALIZATION_SPACE = Bytes.SIZEOF_BYTE + Bytes.SIZEOF_INT
112 + Bytes.SIZEOF_LONG;
113
114
115
116
117 static final int CHECKSUM_SIZE = Bytes.SIZEOF_INT;
118
119 static final CacheableDeserializer<Cacheable> blockDeserializer =
120 new CacheableDeserializer<Cacheable>() {
121 public HFileBlock deserialize(ByteBuffer buf, boolean reuse) throws IOException{
122 buf.limit(buf.limit() - HFileBlock.EXTRA_SERIALIZATION_SPACE).rewind();
123 ByteBuffer newByteBuffer;
124 if (reuse) {
125 newByteBuffer = buf.slice();
126 } else {
127 newByteBuffer = ByteBuffer.allocate(buf.limit());
128 newByteBuffer.put(buf);
129 }
130 buf.position(buf.limit());
131 buf.limit(buf.limit() + HFileBlock.EXTRA_SERIALIZATION_SPACE);
132 boolean usesChecksum = buf.get() == (byte)1;
133 HFileBlock hFileBlock = new HFileBlock(newByteBuffer, usesChecksum);
134 hFileBlock.offset = buf.getLong();
135 hFileBlock.nextBlockOnDiskSizeWithHeader = buf.getInt();
136 if (hFileBlock.hasNextBlockHeader()) {
137 hFileBlock.buf.limit(hFileBlock.buf.limit() - hFileBlock.headerSize());
138 }
139 return hFileBlock;
140 }
141
142 @Override
143 public int getDeserialiserIdentifier() {
144 return deserializerIdentifier;
145 }
146
147 @Override
148 public HFileBlock deserialize(ByteBuffer b) throws IOException {
149 return deserialize(b, false);
150 }
151 };
152 private static final int deserializerIdentifier;
153 static {
154 deserializerIdentifier = CacheableDeserializerIdManager
155 .registerDeserializer(blockDeserializer);
156 }
157
158
159 private BlockType blockType;
160
161
162 private int onDiskSizeWithoutHeader;
163
164
165 private final int uncompressedSizeWithoutHeader;
166
167
168 private final long prevBlockOffset;
169
170
171
172
173
174 private final int onDiskDataSizeWithHeader;
175
176
177 private ByteBuffer buf;
178
179
180 private HFileContext fileContext;
181
182
183
184
185
186 private long offset = -1;
187
188
189
190
191
192
193 private int nextBlockOnDiskSizeWithHeader = -1;
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211 HFileBlock(BlockType blockType, int onDiskSizeWithoutHeader, int uncompressedSizeWithoutHeader,
212 long prevBlockOffset, ByteBuffer buf, boolean fillHeader, long offset,
213 int onDiskDataSizeWithHeader, HFileContext fileContext) {
214 this.blockType = blockType;
215 this.onDiskSizeWithoutHeader = onDiskSizeWithoutHeader;
216 this.uncompressedSizeWithoutHeader = uncompressedSizeWithoutHeader;
217 this.prevBlockOffset = prevBlockOffset;
218 this.buf = buf;
219 this.offset = offset;
220 this.onDiskDataSizeWithHeader = onDiskDataSizeWithHeader;
221 this.fileContext = fileContext;
222 if (fillHeader)
223 overwriteHeader();
224 this.buf.rewind();
225 }
226
227
228
229
230 HFileBlock(HFileBlock that) {
231 this.blockType = that.blockType;
232 this.onDiskSizeWithoutHeader = that.onDiskSizeWithoutHeader;
233 this.uncompressedSizeWithoutHeader = that.uncompressedSizeWithoutHeader;
234 this.prevBlockOffset = that.prevBlockOffset;
235 this.buf = that.buf.duplicate();
236 this.offset = that.offset;
237 this.onDiskDataSizeWithHeader = that.onDiskDataSizeWithHeader;
238 this.fileContext = that.fileContext;
239 this.nextBlockOnDiskSizeWithHeader = that.nextBlockOnDiskSizeWithHeader;
240 }
241
242
243
244
245
246
247
248
249
250 HFileBlock(ByteBuffer b, boolean usesHBaseChecksum) throws IOException {
251 b.rewind();
252 blockType = BlockType.read(b);
253 onDiskSizeWithoutHeader = b.getInt();
254 uncompressedSizeWithoutHeader = b.getInt();
255 prevBlockOffset = b.getLong();
256 HFileContextBuilder contextBuilder = new HFileContextBuilder();
257 contextBuilder.withHBaseCheckSum(usesHBaseChecksum);
258 if (usesHBaseChecksum) {
259 contextBuilder.withChecksumType(ChecksumType.codeToType(b.get()));
260 contextBuilder.withBytesPerCheckSum(b.getInt());
261 this.onDiskDataSizeWithHeader = b.getInt();
262 } else {
263 contextBuilder.withChecksumType(ChecksumType.NULL);
264 contextBuilder.withBytesPerCheckSum(0);
265 this.onDiskDataSizeWithHeader = onDiskSizeWithoutHeader +
266 HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM;
267 }
268 this.fileContext = contextBuilder.build();
269 buf = b;
270 buf.rewind();
271 }
272
273 public BlockType getBlockType() {
274 return blockType;
275 }
276
277
278 public short getDataBlockEncodingId() {
279 if (blockType != BlockType.ENCODED_DATA) {
280 throw new IllegalArgumentException("Querying encoder ID of a block " +
281 "of type other than " + BlockType.ENCODED_DATA + ": " + blockType);
282 }
283 return buf.getShort(headerSize());
284 }
285
286
287
288
289 public int getOnDiskSizeWithHeader() {
290 return onDiskSizeWithoutHeader + headerSize();
291 }
292
293
294
295
296 public int getOnDiskSizeWithoutHeader() {
297 return onDiskSizeWithoutHeader;
298 }
299
300
301
302
303 public int getUncompressedSizeWithoutHeader() {
304 return uncompressedSizeWithoutHeader;
305 }
306
307
308
309
310
311 public long getPrevBlockOffset() {
312 return prevBlockOffset;
313 }
314
315
316
317
318
319 private void overwriteHeader() {
320 buf.rewind();
321 blockType.write(buf);
322 buf.putInt(onDiskSizeWithoutHeader);
323 buf.putInt(uncompressedSizeWithoutHeader);
324 buf.putLong(prevBlockOffset);
325 if (this.fileContext.isUseHBaseChecksum()) {
326 buf.put(fileContext.getChecksumType().getCode());
327 buf.putInt(fileContext.getBytesPerChecksum());
328 buf.putInt(onDiskDataSizeWithHeader);
329 }
330 }
331
332
333
334
335
336
337 public ByteBuffer getBufferWithoutHeader() {
338 ByteBuffer dup = this.buf.duplicate();
339 dup.position(headerSize());
340 dup.limit(buf.limit() - totalChecksumBytes());
341 return dup.slice();
342 }
343
344
345
346
347
348
349
350
351
352
353
354 public ByteBuffer getBufferReadOnly() {
355 ByteBuffer dup = this.buf.duplicate();
356 dup.limit(buf.limit() - totalChecksumBytes());
357 return dup.slice();
358 }
359
360
361
362
363
364
365
366
367 public ByteBuffer getBufferReadOnlyWithHeader() {
368 ByteBuffer dup = this.buf.duplicate();
369 return dup.slice();
370 }
371
372
373
374
375
376
377
378 ByteBuffer getBufferWithHeader() {
379 ByteBuffer dupBuf = buf.duplicate();
380 dupBuf.rewind();
381 return dupBuf;
382 }
383
384 private void sanityCheckAssertion(long valueFromBuf, long valueFromField,
385 String fieldName) throws IOException {
386 if (valueFromBuf != valueFromField) {
387 throw new AssertionError(fieldName + " in the buffer (" + valueFromBuf
388 + ") is different from that in the field (" + valueFromField + ")");
389 }
390 }
391
392 private void sanityCheckAssertion(BlockType valueFromBuf, BlockType valueFromField)
393 throws IOException {
394 if (valueFromBuf != valueFromField) {
395 throw new IOException("Block type stored in the buffer: " +
396 valueFromBuf + ", block type field: " + valueFromField);
397 }
398 }
399
400
401
402
403
404
405
406
407 void sanityCheck() throws IOException {
408 buf.rewind();
409
410 sanityCheckAssertion(BlockType.read(buf), blockType);
411
412 sanityCheckAssertion(buf.getInt(), onDiskSizeWithoutHeader,
413 "onDiskSizeWithoutHeader");
414
415 sanityCheckAssertion(buf.getInt(), uncompressedSizeWithoutHeader,
416 "uncompressedSizeWithoutHeader");
417
418 sanityCheckAssertion(buf.getLong(), prevBlockOffset, "prevBlocKOffset");
419 if (this.fileContext.isUseHBaseChecksum()) {
420 sanityCheckAssertion(buf.get(), this.fileContext.getChecksumType().getCode(), "checksumType");
421 sanityCheckAssertion(buf.getInt(), this.fileContext.getBytesPerChecksum(), "bytesPerChecksum");
422 sanityCheckAssertion(buf.getInt(), onDiskDataSizeWithHeader, "onDiskDataSizeWithHeader");
423 }
424
425 int cksumBytes = totalChecksumBytes();
426 int expectedBufLimit = onDiskDataSizeWithHeader + cksumBytes;
427 if (buf.limit() != expectedBufLimit) {
428 throw new AssertionError("Expected buffer limit " + expectedBufLimit
429 + ", got " + buf.limit());
430 }
431
432
433
434 int hdrSize = headerSize();
435 if (buf.capacity() != expectedBufLimit &&
436 buf.capacity() != expectedBufLimit + hdrSize) {
437 throw new AssertionError("Invalid buffer capacity: " + buf.capacity() +
438 ", expected " + expectedBufLimit + " or " + (expectedBufLimit + hdrSize));
439 }
440 }
441
442 @Override
443 public String toString() {
444 StringBuilder sb = new StringBuilder()
445 .append("HFileBlock [")
446 .append(" fileOffset=").append(offset)
447 .append(" headerSize()=").append(headerSize())
448 .append(" blockType=").append(blockType)
449 .append(" onDiskSizeWithoutHeader=").append(onDiskSizeWithoutHeader)
450 .append(" uncompressedSizeWithoutHeader=").append(uncompressedSizeWithoutHeader)
451 .append(" prevBlockOffset=").append(prevBlockOffset)
452 .append(" isUseHBaseChecksum()=").append(fileContext.isUseHBaseChecksum());
453 if (fileContext.isUseHBaseChecksum()) {
454 sb.append(" checksumType=").append(ChecksumType.codeToType(this.buf.get(24)))
455 .append(" bytesPerChecksum=").append(this.buf.getInt(24 + 1))
456 .append(" onDiskDataSizeWithHeader=").append(onDiskDataSizeWithHeader);
457 } else {
458 sb.append(" onDiskDataSizeWithHeader=").append(onDiskDataSizeWithHeader)
459 .append("(").append(onDiskSizeWithoutHeader)
460 .append("+").append(HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM).append(")");
461 }
462 String dataBegin = null;
463 if (buf.hasArray()) {
464 dataBegin = Bytes.toStringBinary(buf.array(), buf.arrayOffset() + headerSize(),
465 Math.min(32, buf.limit() - buf.arrayOffset() - headerSize()));
466 } else {
467 ByteBuffer bufWithoutHeader = getBufferWithoutHeader();
468 byte[] dataBeginBytes = new byte[Math.min(32,
469 bufWithoutHeader.limit() - bufWithoutHeader.position())];
470 bufWithoutHeader.get(dataBeginBytes);
471 dataBegin = Bytes.toStringBinary(dataBeginBytes);
472 }
473 sb.append(" getOnDiskSizeWithHeader()=").append(getOnDiskSizeWithHeader())
474 .append(" totalChecksumBytes()=").append(totalChecksumBytes())
475 .append(" isUnpacked()=").append(isUnpacked())
476 .append(" buf=[ ").append(buf).append(" ]")
477 .append(" dataBeginsWith=").append(dataBegin)
478 .append(" fileContext=").append(fileContext)
479 .append(" ]");
480 return sb.toString();
481 }
482
483
484
485
486 private void validateOnDiskSizeWithoutHeader(int expectedOnDiskSizeWithoutHeader)
487 throws IOException {
488 if (onDiskSizeWithoutHeader != expectedOnDiskSizeWithoutHeader) {
489 String dataBegin = null;
490 if (buf.hasArray()) {
491 dataBegin = Bytes.toStringBinary(buf.array(), buf.arrayOffset(), Math.min(32, buf.limit()));
492 } else {
493 ByteBuffer bufDup = getBufferReadOnly();
494 byte[] dataBeginBytes = new byte[Math.min(32, bufDup.limit() - bufDup.position())];
495 bufDup.get(dataBeginBytes);
496 dataBegin = Bytes.toStringBinary(dataBeginBytes);
497 }
498 String blockInfoMsg =
499 "Block offset: " + offset + ", data starts with: " + dataBegin;
500 throw new IOException("On-disk size without header provided is "
501 + expectedOnDiskSizeWithoutHeader + ", but block "
502 + "header contains " + onDiskSizeWithoutHeader + ". " +
503 blockInfoMsg);
504 }
505 }
506
507
508
509
510
511 HFileBlock unpack(HFileContext fileContext, FSReader reader) throws IOException {
512 if (!fileContext.isCompressedOrEncrypted()) {
513
514
515
516 return this;
517 }
518
519 HFileBlock unpacked = new HFileBlock(this);
520 unpacked.allocateBuffer();
521
522 HFileBlockDecodingContext ctx = blockType == BlockType.ENCODED_DATA ?
523 reader.getBlockDecodingContext() : reader.getDefaultBlockDecodingContext();
524
525 ByteBuffer dup = this.buf.duplicate();
526 dup.position(this.headerSize());
527 dup = dup.slice();
528 ctx.prepareDecoding(unpacked.getOnDiskSizeWithoutHeader(),
529 unpacked.getUncompressedSizeWithoutHeader(), unpacked.getBufferWithoutHeader(),
530 dup);
531
532
533 if (unpacked.hasNextBlockHeader()) {
534
535
536
537
538 ByteBuffer inDup = this.buf.duplicate();
539 inDup.limit(inDup.limit() + headerSize());
540 ByteBuffer outDup = unpacked.buf.duplicate();
541 outDup.limit(outDup.limit() + unpacked.headerSize());
542 ByteBufferUtils.copyFromBufferToBuffer(
543 outDup,
544 inDup,
545 this.onDiskDataSizeWithHeader,
546 unpacked.headerSize() + unpacked.uncompressedSizeWithoutHeader
547 + unpacked.totalChecksumBytes(), unpacked.headerSize());
548 }
549 return unpacked;
550 }
551
552
553
554
555 private boolean hasNextBlockHeader() {
556 return nextBlockOnDiskSizeWithHeader > 0;
557 }
558
559
560
561
562
563
564 private void allocateBuffer() {
565 int cksumBytes = totalChecksumBytes();
566 int headerSize = headerSize();
567 int capacityNeeded = headerSize + uncompressedSizeWithoutHeader +
568 cksumBytes + (hasNextBlockHeader() ? headerSize : 0);
569
570
571 ByteBuffer newBuf = ByteBuffer.allocate(capacityNeeded);
572
573
574
575 ByteBuffer dup = buf.duplicate();
576 dup.position(0);
577 dup.get(newBuf.array(), newBuf.arrayOffset(), headerSize);
578
579 buf = newBuf;
580
581 buf.limit(headerSize + uncompressedSizeWithoutHeader + cksumBytes);
582 }
583
584
585
586
587
588 public boolean isUnpacked() {
589 final int cksumBytes = totalChecksumBytes();
590 final int headerSize = headerSize();
591 final int expectedCapacity = headerSize + uncompressedSizeWithoutHeader + cksumBytes;
592 final int bufCapacity = buf.capacity();
593 return bufCapacity == expectedCapacity || bufCapacity == expectedCapacity + headerSize;
594 }
595
596
597 public void assumeUncompressed() throws IOException {
598 if (onDiskSizeWithoutHeader != uncompressedSizeWithoutHeader +
599 totalChecksumBytes()) {
600 throw new IOException("Using no compression but "
601 + "onDiskSizeWithoutHeader=" + onDiskSizeWithoutHeader + ", "
602 + "uncompressedSizeWithoutHeader=" + uncompressedSizeWithoutHeader
603 + ", numChecksumbytes=" + totalChecksumBytes());
604 }
605 }
606
607
608
609
610
611 public void expectType(BlockType expectedType) throws IOException {
612 if (blockType != expectedType) {
613 throw new IOException("Invalid block type: expected=" + expectedType
614 + ", actual=" + blockType);
615 }
616 }
617
618
619 public long getOffset() {
620 if (offset < 0) {
621 throw new IllegalStateException(
622 "HFile block offset not initialized properly");
623 }
624 return offset;
625 }
626
627
628
629
630 public DataInputStream getByteStream() {
631 ByteBuffer dup = this.buf.duplicate();
632 dup.position(this.headerSize());
633 return new DataInputStream(new ByteBufferInputStream(dup));
634 }
635
636 @Override
637 public long heapSize() {
638 long size = ClassSize.align(
639 ClassSize.OBJECT +
640
641 3 * ClassSize.REFERENCE +
642
643
644 4 * Bytes.SIZEOF_INT +
645
646 2 * Bytes.SIZEOF_LONG +
647
648 fileContext.heapSize()
649 );
650
651 if (buf != null) {
652
653 size += ClassSize.align(buf.capacity() + BYTE_BUFFER_HEAP_SIZE);
654 }
655
656 return ClassSize.align(size);
657 }
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674 public static boolean readWithExtra(InputStream in, byte[] buf,
675 int bufOffset, int necessaryLen, int extraLen) throws IOException {
676 int bytesRemaining = necessaryLen + extraLen;
677 while (bytesRemaining > 0) {
678 int ret = in.read(buf, bufOffset, bytesRemaining);
679 if (ret == -1 && bytesRemaining <= extraLen) {
680
681 break;
682 }
683
684 if (ret < 0) {
685 throw new IOException("Premature EOF from inputStream (read "
686 + "returned " + ret + ", was trying to read " + necessaryLen
687 + " necessary bytes and " + extraLen + " extra bytes, "
688 + "successfully read "
689 + (necessaryLen + extraLen - bytesRemaining));
690 }
691 bufOffset += ret;
692 bytesRemaining -= ret;
693 }
694 return bytesRemaining <= 0;
695 }
696
697
698
699
700
701 public int getNextBlockOnDiskSizeWithHeader() {
702 return nextBlockOnDiskSizeWithHeader;
703 }
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718 public static class Writer {
719
720 private enum State {
721 INIT,
722 WRITING,
723 BLOCK_READY
724 };
725
726
727 private State state = State.INIT;
728
729
730 private final HFileDataBlockEncoder dataBlockEncoder;
731
732 private HFileBlockEncodingContext dataBlockEncodingCtx;
733
734
735 private HFileBlockDefaultEncodingContext defaultBlockEncodingCtx;
736
737
738
739
740
741
742
743 private ByteArrayOutputStream baosInMemory;
744
745
746
747
748
749
750 private BlockType blockType;
751
752
753
754
755
756 private DataOutputStream userDataStream;
757
758
759
760 private int unencodedDataSizeWritten;
761
762
763
764
765
766
767 private byte[] onDiskBytesWithHeader;
768
769
770
771
772
773
774
775 private byte[] onDiskChecksum;
776
777
778
779
780
781
782
783
784 private byte[] uncompressedBytesWithHeader;
785
786
787
788
789
790 private long startOffset;
791
792
793
794
795
796 private long[] prevOffsetByType;
797
798
799 private long prevOffset;
800
801 private HFileContext fileContext;
802
803
804
805
806 public Writer(HFileDataBlockEncoder dataBlockEncoder, HFileContext fileContext) {
807 this.dataBlockEncoder = dataBlockEncoder != null
808 ? dataBlockEncoder : NoOpDataBlockEncoder.INSTANCE;
809 defaultBlockEncodingCtx = new HFileBlockDefaultEncodingContext(null,
810 HConstants.HFILEBLOCK_DUMMY_HEADER, fileContext);
811 dataBlockEncodingCtx = this.dataBlockEncoder
812 .newDataBlockEncodingContext(HConstants.HFILEBLOCK_DUMMY_HEADER, fileContext);
813
814 if (fileContext.getBytesPerChecksum() < HConstants.HFILEBLOCK_HEADER_SIZE) {
815 throw new RuntimeException("Unsupported value of bytesPerChecksum. " +
816 " Minimum is " + HConstants.HFILEBLOCK_HEADER_SIZE + " but the configured value is " +
817 fileContext.getBytesPerChecksum());
818 }
819
820 baosInMemory = new ByteArrayOutputStream();
821
822 prevOffsetByType = new long[BlockType.values().length];
823 for (int i = 0; i < prevOffsetByType.length; ++i)
824 prevOffsetByType[i] = -1;
825
826 this.fileContext = fileContext;
827 }
828
829
830
831
832
833
834
835 public DataOutputStream startWriting(BlockType newBlockType)
836 throws IOException {
837 if (state == State.BLOCK_READY && startOffset != -1) {
838
839
840 prevOffsetByType[blockType.getId()] = startOffset;
841 }
842
843 startOffset = -1;
844 blockType = newBlockType;
845
846 baosInMemory.reset();
847 baosInMemory.write(HConstants.HFILEBLOCK_DUMMY_HEADER);
848
849 state = State.WRITING;
850
851
852 userDataStream = new DataOutputStream(baosInMemory);
853 if (newBlockType == BlockType.DATA) {
854 this.dataBlockEncoder.startBlockEncoding(dataBlockEncodingCtx, userDataStream);
855 }
856 this.unencodedDataSizeWritten = 0;
857 return userDataStream;
858 }
859
860
861
862
863
864
865 public void write(Cell cell) throws IOException{
866 expectState(State.WRITING);
867 this.unencodedDataSizeWritten += this.dataBlockEncoder.encode(cell, dataBlockEncodingCtx,
868 this.userDataStream);
869 }
870
871
872
873
874
875
876
877
878 DataOutputStream getUserDataStream() {
879 expectState(State.WRITING);
880 return userDataStream;
881 }
882
883
884
885
886
887 void ensureBlockReady() throws IOException {
888 Preconditions.checkState(state != State.INIT,
889 "Unexpected state: " + state);
890
891 if (state == State.BLOCK_READY)
892 return;
893
894
895 finishBlock();
896 }
897
898
899
900
901
902
903
904 private void finishBlock() throws IOException {
905 if (blockType == BlockType.DATA) {
906 BufferGrabbingByteArrayOutputStream baosInMemoryCopy =
907 new BufferGrabbingByteArrayOutputStream();
908 baosInMemory.writeTo(baosInMemoryCopy);
909 this.dataBlockEncoder.endBlockEncoding(dataBlockEncodingCtx, userDataStream,
910 baosInMemoryCopy.buf, blockType);
911 blockType = dataBlockEncodingCtx.getBlockType();
912 }
913 userDataStream.flush();
914
915 uncompressedBytesWithHeader = baosInMemory.toByteArray();
916 prevOffset = prevOffsetByType[blockType.getId()];
917
918
919
920
921 state = State.BLOCK_READY;
922 if (blockType == BlockType.DATA || blockType == BlockType.ENCODED_DATA) {
923 onDiskBytesWithHeader = dataBlockEncodingCtx
924 .compressAndEncrypt(uncompressedBytesWithHeader);
925 } else {
926 onDiskBytesWithHeader = defaultBlockEncodingCtx
927 .compressAndEncrypt(uncompressedBytesWithHeader);
928 }
929 int numBytes = (int) ChecksumUtil.numBytes(
930 onDiskBytesWithHeader.length,
931 fileContext.getBytesPerChecksum());
932
933
934 putHeader(onDiskBytesWithHeader, 0,
935 onDiskBytesWithHeader.length + numBytes,
936 uncompressedBytesWithHeader.length, onDiskBytesWithHeader.length);
937
938 putHeader(uncompressedBytesWithHeader, 0,
939 onDiskBytesWithHeader.length + numBytes,
940 uncompressedBytesWithHeader.length, onDiskBytesWithHeader.length);
941
942 onDiskChecksum = new byte[numBytes];
943 ChecksumUtil.generateChecksums(
944 onDiskBytesWithHeader, 0, onDiskBytesWithHeader.length,
945 onDiskChecksum, 0, fileContext.getChecksumType(), fileContext.getBytesPerChecksum());
946 }
947
948 public static class BufferGrabbingByteArrayOutputStream extends ByteArrayOutputStream {
949 private byte[] buf;
950
951 @Override
952 public void write(byte[] b, int off, int len) {
953 this.buf = b;
954 }
955
956 public byte[] getBuffer() {
957 return this.buf;
958 }
959 }
960
961
962
963
964
965
966
967
968
969 private void putHeader(byte[] dest, int offset, int onDiskSize,
970 int uncompressedSize, int onDiskDataSize) {
971 offset = blockType.put(dest, offset);
972 offset = Bytes.putInt(dest, offset, onDiskSize - HConstants.HFILEBLOCK_HEADER_SIZE);
973 offset = Bytes.putInt(dest, offset, uncompressedSize - HConstants.HFILEBLOCK_HEADER_SIZE);
974 offset = Bytes.putLong(dest, offset, prevOffset);
975 offset = Bytes.putByte(dest, offset, fileContext.getChecksumType().getCode());
976 offset = Bytes.putInt(dest, offset, fileContext.getBytesPerChecksum());
977 Bytes.putInt(dest, offset, onDiskDataSize);
978 }
979
980
981
982
983
984
985
986
987
988 public void writeHeaderAndData(FSDataOutputStream out) throws IOException {
989 long offset = out.getPos();
990 if (startOffset != -1 && offset != startOffset) {
991 throw new IOException("A " + blockType + " block written to a "
992 + "stream twice, first at offset " + startOffset + ", then at "
993 + offset);
994 }
995 startOffset = offset;
996
997 finishBlockAndWriteHeaderAndData((DataOutputStream) out);
998 }
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009 protected void finishBlockAndWriteHeaderAndData(DataOutputStream out)
1010 throws IOException {
1011 ensureBlockReady();
1012 out.write(onDiskBytesWithHeader);
1013 out.write(onDiskChecksum);
1014 }
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026 byte[] getHeaderAndDataForTest() throws IOException {
1027 ensureBlockReady();
1028
1029
1030 byte[] output =
1031 new byte[onDiskBytesWithHeader.length
1032 + onDiskChecksum.length];
1033 System.arraycopy(onDiskBytesWithHeader, 0, output, 0,
1034 onDiskBytesWithHeader.length);
1035 System.arraycopy(onDiskChecksum, 0, output,
1036 onDiskBytesWithHeader.length, onDiskChecksum.length);
1037 return output;
1038 }
1039
1040
1041
1042
1043 public void release() {
1044 if (dataBlockEncodingCtx != null) {
1045 dataBlockEncodingCtx.close();
1046 dataBlockEncodingCtx = null;
1047 }
1048 if (defaultBlockEncodingCtx != null) {
1049 defaultBlockEncodingCtx.close();
1050 defaultBlockEncodingCtx = null;
1051 }
1052 }
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062 int getOnDiskSizeWithoutHeader() {
1063 expectState(State.BLOCK_READY);
1064 return onDiskBytesWithHeader.length
1065 + onDiskChecksum.length
1066 - HConstants.HFILEBLOCK_HEADER_SIZE;
1067 }
1068
1069
1070
1071
1072
1073
1074
1075
1076 int getOnDiskSizeWithHeader() {
1077 expectState(State.BLOCK_READY);
1078 return onDiskBytesWithHeader.length + onDiskChecksum.length;
1079 }
1080
1081
1082
1083
1084 int getUncompressedSizeWithoutHeader() {
1085 expectState(State.BLOCK_READY);
1086 return uncompressedBytesWithHeader.length - HConstants.HFILEBLOCK_HEADER_SIZE;
1087 }
1088
1089
1090
1091
1092 int getUncompressedSizeWithHeader() {
1093 expectState(State.BLOCK_READY);
1094 return uncompressedBytesWithHeader.length;
1095 }
1096
1097
1098 public boolean isWriting() {
1099 return state == State.WRITING;
1100 }
1101
1102
1103
1104
1105
1106
1107
1108
1109 public int blockSizeWritten() {
1110 if (state != State.WRITING) return 0;
1111 return this.unencodedDataSizeWritten;
1112 }
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122 ByteBuffer getUncompressedBufferWithHeader() {
1123 expectState(State.BLOCK_READY);
1124 return ByteBuffer.wrap(uncompressedBytesWithHeader);
1125 }
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135 ByteBuffer getOnDiskBufferWithHeader() {
1136 expectState(State.BLOCK_READY);
1137 return ByteBuffer.wrap(onDiskBytesWithHeader);
1138 }
1139
1140 private void expectState(State expectedState) {
1141 if (state != expectedState) {
1142 throw new IllegalStateException("Expected state: " + expectedState +
1143 ", actual state: " + state);
1144 }
1145 }
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157 public void writeBlock(BlockWritable bw, FSDataOutputStream out)
1158 throws IOException {
1159 bw.writeToBlock(startWriting(bw.getBlockType()));
1160 writeHeaderAndData(out);
1161 }
1162
1163
1164
1165
1166
1167
1168
1169
1170 public HFileBlock getBlockForCaching(CacheConfig cacheConf) {
1171 HFileContext newContext = new HFileContextBuilder()
1172 .withBlockSize(fileContext.getBlocksize())
1173 .withBytesPerCheckSum(0)
1174 .withChecksumType(ChecksumType.NULL)
1175 .withCompression(fileContext.getCompression())
1176 .withDataBlockEncoding(fileContext.getDataBlockEncoding())
1177 .withHBaseCheckSum(fileContext.isUseHBaseChecksum())
1178 .withCompressTags(fileContext.isCompressTags())
1179 .withIncludesMvcc(fileContext.isIncludesMvcc())
1180 .withIncludesTags(fileContext.isIncludesTags())
1181 .build();
1182 return new HFileBlock(blockType, getOnDiskSizeWithoutHeader(),
1183 getUncompressedSizeWithoutHeader(), prevOffset,
1184 cacheConf.shouldCacheCompressed(blockType.getCategory()) ?
1185 getOnDiskBufferWithHeader() :
1186 getUncompressedBufferWithHeader(),
1187 FILL_HEADER, startOffset,
1188 onDiskBytesWithHeader.length + onDiskChecksum.length, newContext);
1189 }
1190 }
1191
1192
1193 public interface BlockWritable {
1194
1195
1196 BlockType getBlockType();
1197
1198
1199
1200
1201
1202
1203
1204 void writeToBlock(DataOutput out) throws IOException;
1205 }
1206
1207
1208
1209
1210 public interface BlockIterator {
1211
1212
1213
1214
1215 HFileBlock nextBlock() throws IOException;
1216
1217
1218
1219
1220
1221 HFileBlock nextBlockWithBlockType(BlockType blockType) throws IOException;
1222 }
1223
1224
1225 public interface FSReader {
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238 HFileBlock readBlockData(long offset, long onDiskSize,
1239 int uncompressedSize, boolean pread) throws IOException;
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250 BlockIterator blockRange(long startOffset, long endOffset);
1251
1252
1253 void closeStreams() throws IOException;
1254
1255
1256 HFileBlockDecodingContext getBlockDecodingContext();
1257
1258
1259 HFileBlockDecodingContext getDefaultBlockDecodingContext();
1260 }
1261
1262
1263
1264
1265
1266 private abstract static class AbstractFSReader implements FSReader {
1267
1268
1269
1270 protected long fileSize;
1271
1272
1273 protected final int hdrSize;
1274
1275
1276 protected HFileSystem hfs;
1277
1278
1279 protected Path path;
1280
1281 private final Lock streamLock = new ReentrantLock();
1282
1283
1284 public static final int DEFAULT_BUFFER_SIZE = 1 << 20;
1285
1286 protected HFileContext fileContext;
1287
1288 public AbstractFSReader(long fileSize, HFileSystem hfs, Path path, HFileContext fileContext)
1289 throws IOException {
1290 this.fileSize = fileSize;
1291 this.hfs = hfs;
1292 this.path = path;
1293 this.fileContext = fileContext;
1294 this.hdrSize = headerSize(fileContext.isUseHBaseChecksum());
1295 }
1296
1297 @Override
1298 public BlockIterator blockRange(final long startOffset,
1299 final long endOffset) {
1300 final FSReader owner = this;
1301 return new BlockIterator() {
1302 private long offset = startOffset;
1303
1304 @Override
1305 public HFileBlock nextBlock() throws IOException {
1306 if (offset >= endOffset)
1307 return null;
1308 HFileBlock b = readBlockData(offset, -1, -1, false);
1309 offset += b.getOnDiskSizeWithHeader();
1310 return b.unpack(fileContext, owner);
1311 }
1312
1313 @Override
1314 public HFileBlock nextBlockWithBlockType(BlockType blockType)
1315 throws IOException {
1316 HFileBlock blk = nextBlock();
1317 if (blk.getBlockType() != blockType) {
1318 throw new IOException("Expected block of type " + blockType
1319 + " but found " + blk.getBlockType());
1320 }
1321 return blk;
1322 }
1323 };
1324 }
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341 protected int readAtOffset(FSDataInputStream istream,
1342 byte[] dest, int destOffset, int size,
1343 boolean peekIntoNextBlock, long fileOffset, boolean pread)
1344 throws IOException {
1345 if (peekIntoNextBlock &&
1346 destOffset + size + hdrSize > dest.length) {
1347
1348
1349 throw new IOException("Attempted to read " + size + " bytes and " +
1350 hdrSize + " bytes of next header into a " + dest.length +
1351 "-byte array at offset " + destOffset);
1352 }
1353
1354 if (!pread && streamLock.tryLock()) {
1355
1356 try {
1357 istream.seek(fileOffset);
1358
1359 long realOffset = istream.getPos();
1360 if (realOffset != fileOffset) {
1361 throw new IOException("Tried to seek to " + fileOffset + " to "
1362 + "read " + size + " bytes, but pos=" + realOffset
1363 + " after seek");
1364 }
1365
1366 if (!peekIntoNextBlock) {
1367 IOUtils.readFully(istream, dest, destOffset, size);
1368 return -1;
1369 }
1370
1371
1372 if (!readWithExtra(istream, dest, destOffset, size, hdrSize))
1373 return -1;
1374 } finally {
1375 streamLock.unlock();
1376 }
1377 } else {
1378
1379 int extraSize = peekIntoNextBlock ? hdrSize : 0;
1380 int ret = istream.read(fileOffset, dest, destOffset, size + extraSize);
1381 if (ret < size) {
1382 throw new IOException("Positional read of " + size + " bytes " +
1383 "failed at offset " + fileOffset + " (returned " + ret + ")");
1384 }
1385
1386 if (ret == size || ret < size + extraSize) {
1387
1388 return -1;
1389 }
1390 }
1391
1392 assert peekIntoNextBlock;
1393 return Bytes.toInt(dest, destOffset + size + BlockType.MAGIC_LENGTH) + hdrSize;
1394 }
1395
1396 }
1397
1398
1399
1400
1401
1402 private static class PrefetchedHeader {
1403 long offset = -1;
1404 byte[] header = new byte[HConstants.HFILEBLOCK_HEADER_SIZE];
1405 final ByteBuffer buf = ByteBuffer.wrap(header, 0, HConstants.HFILEBLOCK_HEADER_SIZE);
1406 }
1407
1408
1409 static class FSReaderImpl extends AbstractFSReader {
1410
1411
1412 protected FSDataInputStreamWrapper streamWrapper;
1413
1414 private HFileBlockDecodingContext encodedBlockDecodingCtx;
1415
1416
1417 private final HFileBlockDefaultDecodingContext defaultDecodingCtx;
1418
1419 private ThreadLocal<PrefetchedHeader> prefetchedHeaderForThread =
1420 new ThreadLocal<PrefetchedHeader>() {
1421 @Override
1422 public PrefetchedHeader initialValue() {
1423 return new PrefetchedHeader();
1424 }
1425 };
1426
1427 public FSReaderImpl(FSDataInputStreamWrapper stream, long fileSize, HFileSystem hfs, Path path,
1428 HFileContext fileContext) throws IOException {
1429 super(fileSize, hfs, path, fileContext);
1430 this.streamWrapper = stream;
1431
1432 this.streamWrapper.prepareForBlockReader(!fileContext.isUseHBaseChecksum());
1433 defaultDecodingCtx = new HFileBlockDefaultDecodingContext(fileContext);
1434 encodedBlockDecodingCtx = defaultDecodingCtx;
1435 }
1436
1437
1438
1439
1440
1441 FSReaderImpl(FSDataInputStream istream, long fileSize, HFileContext fileContext)
1442 throws IOException {
1443 this(new FSDataInputStreamWrapper(istream), fileSize, null, null, fileContext);
1444 }
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457 @Override
1458 public HFileBlock readBlockData(long offset, long onDiskSizeWithHeaderL,
1459 int uncompressedSize, boolean pread)
1460 throws IOException {
1461
1462
1463
1464
1465
1466
1467 boolean doVerificationThruHBaseChecksum = streamWrapper.shouldUseHBaseChecksum();
1468 FSDataInputStream is = streamWrapper.getStream(doVerificationThruHBaseChecksum);
1469
1470 HFileBlock blk = readBlockDataInternal(is, offset,
1471 onDiskSizeWithHeaderL,
1472 uncompressedSize, pread,
1473 doVerificationThruHBaseChecksum);
1474 if (blk == null) {
1475 HFile.LOG.warn("HBase checksum verification failed for file " +
1476 path + " at offset " +
1477 offset + " filesize " + fileSize +
1478 ". Retrying read with HDFS checksums turned on...");
1479
1480 if (!doVerificationThruHBaseChecksum) {
1481 String msg = "HBase checksum verification failed for file " +
1482 path + " at offset " +
1483 offset + " filesize " + fileSize +
1484 " but this cannot happen because doVerify is " +
1485 doVerificationThruHBaseChecksum;
1486 HFile.LOG.warn(msg);
1487 throw new IOException(msg);
1488 }
1489 HFile.checksumFailures.incrementAndGet();
1490
1491
1492
1493
1494
1495
1496
1497 is = this.streamWrapper.fallbackToFsChecksum(CHECKSUM_VERIFICATION_NUM_IO_THRESHOLD);
1498 doVerificationThruHBaseChecksum = false;
1499 blk = readBlockDataInternal(is, offset, onDiskSizeWithHeaderL,
1500 uncompressedSize, pread,
1501 doVerificationThruHBaseChecksum);
1502 if (blk != null) {
1503 HFile.LOG.warn("HDFS checksum verification suceeded for file " +
1504 path + " at offset " +
1505 offset + " filesize " + fileSize);
1506 }
1507 }
1508 if (blk == null && !doVerificationThruHBaseChecksum) {
1509 String msg = "readBlockData failed, possibly due to " +
1510 "checksum verification failed for file " + path +
1511 " at offset " + offset + " filesize " + fileSize;
1512 HFile.LOG.warn(msg);
1513 throw new IOException(msg);
1514 }
1515
1516
1517
1518
1519
1520
1521
1522
1523 streamWrapper.checksumOk();
1524 return blk;
1525 }
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540 private HFileBlock readBlockDataInternal(FSDataInputStream is, long offset,
1541 long onDiskSizeWithHeaderL, int uncompressedSize, boolean pread,
1542 boolean verifyChecksum)
1543 throws IOException {
1544 if (offset < 0) {
1545 throw new IOException("Invalid offset=" + offset + " trying to read "
1546 + "block (onDiskSize=" + onDiskSizeWithHeaderL
1547 + ", uncompressedSize=" + uncompressedSize + ")");
1548 }
1549
1550 if (uncompressedSize != -1) {
1551 throw new IOException("Version 2 block reader API does not need " +
1552 "the uncompressed size parameter");
1553 }
1554
1555 if ((onDiskSizeWithHeaderL < hdrSize && onDiskSizeWithHeaderL != -1)
1556 || onDiskSizeWithHeaderL >= Integer.MAX_VALUE) {
1557 throw new IOException("Invalid onDisksize=" + onDiskSizeWithHeaderL
1558 + ": expected to be at least " + hdrSize
1559 + " and at most " + Integer.MAX_VALUE + ", or -1 (offset="
1560 + offset + ", uncompressedSize=" + uncompressedSize + ")");
1561 }
1562
1563 int onDiskSizeWithHeader = (int) onDiskSizeWithHeaderL;
1564
1565
1566
1567
1568
1569
1570
1571 PrefetchedHeader prefetchedHeader = prefetchedHeaderForThread.get();
1572 ByteBuffer headerBuf = prefetchedHeader.offset == offset? prefetchedHeader.buf: null;
1573
1574
1575 int nextBlockOnDiskSize = 0;
1576 byte[] onDiskBlock = null;
1577
1578 HFileBlock b = null;
1579 if (onDiskSizeWithHeader > 0) {
1580
1581
1582
1583
1584
1585
1586
1587
1588 int preReadHeaderSize = headerBuf == null ? 0 : hdrSize;
1589 onDiskBlock = new byte[onDiskSizeWithHeader + hdrSize];
1590
1591 nextBlockOnDiskSize = readAtOffset(is, onDiskBlock,
1592 preReadHeaderSize, onDiskSizeWithHeader - preReadHeaderSize,
1593 true, offset + preReadHeaderSize, pread);
1594 if (headerBuf != null) {
1595
1596
1597
1598 assert headerBuf.hasArray();
1599 System.arraycopy(headerBuf.array(),
1600 headerBuf.arrayOffset(), onDiskBlock, 0, hdrSize);
1601 } else {
1602 headerBuf = ByteBuffer.wrap(onDiskBlock, 0, hdrSize);
1603 }
1604
1605 try {
1606
1607 b = new HFileBlock(headerBuf, fileContext.isUseHBaseChecksum());
1608 } catch (IOException ex) {
1609
1610 throw new IOException("Failed to read compressed block at "
1611 + offset
1612 + ", onDiskSizeWithoutHeader="
1613 + onDiskSizeWithHeader
1614 + ", preReadHeaderSize="
1615 + hdrSize
1616 + ", header.length="
1617 + prefetchedHeader.header.length
1618 + ", header bytes: "
1619 + Bytes.toStringBinary(prefetchedHeader.header, 0,
1620 hdrSize), ex);
1621 }
1622
1623 int onDiskSizeWithoutHeader = onDiskSizeWithHeader - hdrSize;
1624 assert onDiskSizeWithoutHeader >= 0;
1625 b.validateOnDiskSizeWithoutHeader(onDiskSizeWithoutHeader);
1626 } else {
1627
1628
1629
1630
1631
1632
1633
1634
1635 if (headerBuf == null) {
1636
1637
1638
1639
1640
1641 headerBuf = ByteBuffer.allocate(hdrSize);
1642
1643 readAtOffset(is, headerBuf.array(), headerBuf.arrayOffset(),
1644 hdrSize, false, offset, pread);
1645 }
1646
1647 b = new HFileBlock(headerBuf, fileContext.isUseHBaseChecksum());
1648 onDiskBlock = new byte[b.getOnDiskSizeWithHeader() + hdrSize];
1649
1650 System.arraycopy(headerBuf.array(), headerBuf.arrayOffset(), onDiskBlock, 0, hdrSize);
1651 nextBlockOnDiskSize =
1652 readAtOffset(is, onDiskBlock, hdrSize, b.getOnDiskSizeWithHeader()
1653 - hdrSize, true, offset + hdrSize, pread);
1654 onDiskSizeWithHeader = b.onDiskSizeWithoutHeader + hdrSize;
1655 }
1656
1657 if (!fileContext.isCompressedOrEncrypted()) {
1658 b.assumeUncompressed();
1659 }
1660
1661 if (verifyChecksum && !validateBlockChecksum(b, onDiskBlock, hdrSize)) {
1662 return null;
1663 }
1664
1665
1666
1667
1668
1669 b = new HFileBlock(ByteBuffer.wrap(onDiskBlock, 0, onDiskSizeWithHeader),
1670 this.fileContext.isUseHBaseChecksum());
1671
1672 b.nextBlockOnDiskSizeWithHeader = nextBlockOnDiskSize;
1673
1674
1675 if (b.hasNextBlockHeader()) {
1676 prefetchedHeader.offset = offset + b.getOnDiskSizeWithHeader();
1677 System.arraycopy(onDiskBlock, onDiskSizeWithHeader, prefetchedHeader.header, 0, hdrSize);
1678 }
1679
1680 b.offset = offset;
1681 b.fileContext.setIncludesTags(this.fileContext.isIncludesTags());
1682 b.fileContext.setIncludesMvcc(this.fileContext.isIncludesMvcc());
1683 return b;
1684 }
1685
1686 void setIncludesMemstoreTS(boolean includesMemstoreTS) {
1687 this.fileContext.setIncludesMvcc(includesMemstoreTS);
1688 }
1689
1690 void setDataBlockEncoder(HFileDataBlockEncoder encoder) {
1691 encodedBlockDecodingCtx = encoder.newDataBlockDecodingContext(this.fileContext);
1692 }
1693
1694 @Override
1695 public HFileBlockDecodingContext getBlockDecodingContext() {
1696 return this.encodedBlockDecodingCtx;
1697 }
1698
1699 @Override
1700 public HFileBlockDecodingContext getDefaultBlockDecodingContext() {
1701 return this.defaultDecodingCtx;
1702 }
1703
1704
1705
1706
1707
1708
1709
1710 protected boolean validateBlockChecksum(HFileBlock block, byte[] data, int hdrSize)
1711 throws IOException {
1712 return ChecksumUtil.validateBlockChecksum(path, block, data, hdrSize);
1713 }
1714
1715 @Override
1716 public void closeStreams() throws IOException {
1717 streamWrapper.close();
1718 }
1719
1720 @Override
1721 public String toString() {
1722 return "hfs=" + hfs + ", path=" + path + ", fileContext=" + fileContext;
1723 }
1724 }
1725
1726 @Override
1727 public int getSerializedLength() {
1728 if (buf != null) {
1729
1730 int extraSpace = hasNextBlockHeader() ? headerSize() : 0;
1731 return this.buf.limit() + extraSpace + HFileBlock.EXTRA_SERIALIZATION_SPACE;
1732 }
1733 return 0;
1734 }
1735
1736 @Override
1737 public void serialize(ByteBuffer destination) {
1738 ByteBufferUtils.copyFromBufferToBuffer(destination, this.buf, 0, getSerializedLength()
1739 - EXTRA_SERIALIZATION_SPACE);
1740 serializeExtraInfo(destination);
1741 }
1742
1743 public void serializeExtraInfo(ByteBuffer destination) {
1744 destination.put(this.fileContext.isUseHBaseChecksum() ? (byte) 1 : (byte) 0);
1745 destination.putLong(this.offset);
1746 destination.putInt(this.nextBlockOnDiskSizeWithHeader);
1747 destination.rewind();
1748 }
1749
1750 @Override
1751 public CacheableDeserializer<Cacheable> getDeserializer() {
1752 return HFileBlock.blockDeserializer;
1753 }
1754
1755 @Override
1756 public boolean equals(Object comparison) {
1757 if (this == comparison) {
1758 return true;
1759 }
1760 if (comparison == null) {
1761 return false;
1762 }
1763 if (comparison.getClass() != this.getClass()) {
1764 return false;
1765 }
1766
1767 HFileBlock castedComparison = (HFileBlock) comparison;
1768
1769 if (castedComparison.blockType != this.blockType) {
1770 return false;
1771 }
1772 if (castedComparison.nextBlockOnDiskSizeWithHeader != this.nextBlockOnDiskSizeWithHeader) {
1773 return false;
1774 }
1775 if (castedComparison.offset != this.offset) {
1776 return false;
1777 }
1778 if (castedComparison.onDiskSizeWithoutHeader != this.onDiskSizeWithoutHeader) {
1779 return false;
1780 }
1781 if (castedComparison.prevBlockOffset != this.prevBlockOffset) {
1782 return false;
1783 }
1784 if (castedComparison.uncompressedSizeWithoutHeader != this.uncompressedSizeWithoutHeader) {
1785 return false;
1786 }
1787 if (ByteBufferUtils.compareTo(this.buf, 0, this.buf.limit(), castedComparison.buf, 0,
1788 castedComparison.buf.limit()) != 0) {
1789 return false;
1790 }
1791 return true;
1792 }
1793
1794 public DataBlockEncoding getDataBlockEncoding() {
1795 if (blockType == BlockType.ENCODED_DATA) {
1796 return DataBlockEncoding.getEncodingById(getDataBlockEncodingId());
1797 }
1798 return DataBlockEncoding.NONE;
1799 }
1800
1801 byte getChecksumType() {
1802 return this.fileContext.getChecksumType().getCode();
1803 }
1804
1805 int getBytesPerChecksum() {
1806 return this.fileContext.getBytesPerChecksum();
1807 }
1808
1809
1810 int getOnDiskDataSizeWithHeader() {
1811 return this.onDiskDataSizeWithHeader;
1812 }
1813
1814
1815
1816
1817
1818 int totalChecksumBytes() {
1819
1820
1821
1822
1823 if (!fileContext.isUseHBaseChecksum() || this.fileContext.getBytesPerChecksum() == 0) {
1824 return 0;
1825 }
1826 return (int) ChecksumUtil.numBytes(onDiskDataSizeWithHeader,
1827 this.fileContext.getBytesPerChecksum());
1828 }
1829
1830
1831
1832
1833 public int headerSize() {
1834 return headerSize(this.fileContext.isUseHBaseChecksum());
1835 }
1836
1837
1838
1839
1840 public static int headerSize(boolean usesHBaseChecksum) {
1841 if (usesHBaseChecksum) {
1842 return HConstants.HFILEBLOCK_HEADER_SIZE;
1843 }
1844 return HConstants.HFILEBLOCK_HEADER_SIZE_NO_CHECKSUM;
1845 }
1846
1847
1848
1849
1850 public byte[] getDummyHeaderForVersion() {
1851 return getDummyHeaderForVersion(this.fileContext.isUseHBaseChecksum());
1852 }
1853
1854
1855
1856
1857 static private byte[] getDummyHeaderForVersion(boolean usesHBaseChecksum) {
1858 if (usesHBaseChecksum) {
1859 return HConstants.HFILEBLOCK_DUMMY_HEADER;
1860 }
1861 return DUMMY_HEADER_NO_CHECKSUM;
1862 }
1863
1864
1865
1866
1867
1868 public HFileContext getHFileContext() {
1869 return this.fileContext;
1870 }
1871
1872
1873
1874
1875
1876
1877 static String toStringHeader(ByteBuffer buf) throws IOException {
1878 byte[] magicBuf = new byte[Math.min(buf.limit() - buf.position(), BlockType.MAGIC_LENGTH)];
1879 buf.get(magicBuf);
1880 BlockType bt = BlockType.parse(magicBuf, 0, BlockType.MAGIC_LENGTH);
1881 int compressedBlockSizeNoHeader = buf.getInt();
1882 int uncompressedBlockSizeNoHeader = buf.getInt();
1883 long prevBlockOffset = buf.getLong();
1884 byte cksumtype = buf.get();
1885 long bytesPerChecksum = buf.getInt();
1886 long onDiskDataSizeWithHeader = buf.getInt();
1887 return " Header dump: magic: " + Bytes.toString(magicBuf) +
1888 " blockType " + bt +
1889 " compressedBlockSizeNoHeader " +
1890 compressedBlockSizeNoHeader +
1891 " uncompressedBlockSizeNoHeader " +
1892 uncompressedBlockSizeNoHeader +
1893 " prevBlockOffset " + prevBlockOffset +
1894 " checksumType " + ChecksumType.codeToType(cksumtype) +
1895 " bytesPerChecksum " + bytesPerChecksum +
1896 " onDiskDataSizeWithHeader " + onDiskDataSizeWithHeader;
1897 }
1898 }