1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.io.hfile;
20
21 import static org.apache.hadoop.hbase.io.compress.Compression.Algorithm.GZ;
22 import static org.apache.hadoop.hbase.io.compress.Compression.Algorithm.NONE;
23 import static org.junit.Assert.*;
24
25 import java.io.ByteArrayOutputStream;
26 import java.io.DataOutputStream;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.nio.ByteBuffer;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Random;
37 import java.util.concurrent.Callable;
38 import java.util.concurrent.ExecutionException;
39 import java.util.concurrent.Executor;
40 import java.util.concurrent.ExecutorCompletionService;
41 import java.util.concurrent.Executors;
42 import java.util.concurrent.Future;
43
44 import org.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46 import org.apache.hadoop.fs.FSDataInputStream;
47 import org.apache.hadoop.fs.FSDataOutputStream;
48 import org.apache.hadoop.fs.FileSystem;
49 import org.apache.hadoop.fs.Path;
50 import org.apache.hadoop.hbase.HBaseTestingUtility;
51 import org.apache.hadoop.hbase.HConstants;
52 import org.apache.hadoop.hbase.KeyValue;
53 import org.apache.hadoop.hbase.testclassification.MediumTests;
54 import org.apache.hadoop.hbase.Tag;
55 import org.apache.hadoop.hbase.fs.HFileSystem;
56 import org.apache.hadoop.hbase.io.compress.Compression;
57 import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
58 import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
59 import org.apache.hadoop.hbase.util.Bytes;
60 import org.apache.hadoop.hbase.util.ChecksumType;
61 import org.apache.hadoop.hbase.util.ClassSize;
62 import org.apache.hadoop.io.WritableUtils;
63 import org.apache.hadoop.io.compress.Compressor;
64 import org.junit.Before;
65 import org.junit.Test;
66 import org.junit.experimental.categories.Category;
67 import org.junit.runner.RunWith;
68 import org.junit.runners.Parameterized;
69 import org.junit.runners.Parameterized.Parameters;
70 import org.mockito.Mockito;
71
72 @Category(MediumTests.class)
73 @RunWith(Parameterized.class)
74 public class TestHFileBlock {
75
76 private static final boolean detailedLogging = false;
77 private static final boolean[] BOOLEAN_VALUES = new boolean[] { false, true };
78
79 private static final Log LOG = LogFactory.getLog(TestHFileBlock.class);
80
81 static final Compression.Algorithm[] COMPRESSION_ALGORITHMS = { NONE, GZ };
82
83 private static final int NUM_TEST_BLOCKS = 1000;
84 private static final int NUM_READER_THREADS = 26;
85
86
87 private static int NUM_KEYVALUES = 50;
88 private static int FIELD_LENGTH = 10;
89 private static float CHANCE_TO_REPEAT = 0.6f;
90
91 private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
92 private FileSystem fs;
93
94 private final boolean includesMemstoreTS;
95 private final boolean includesTag;
96 public TestHFileBlock(boolean includesMemstoreTS, boolean includesTag) {
97 this.includesMemstoreTS = includesMemstoreTS;
98 this.includesTag = includesTag;
99 }
100
101 @Parameters
102 public static Collection<Object[]> parameters() {
103 return HBaseTestingUtility.MEMSTORETS_TAGS_PARAMETRIZED;
104 }
105
106 @Before
107 public void setUp() throws IOException {
108 fs = HFileSystem.get(TEST_UTIL.getConfiguration());
109 }
110
111 static void writeTestBlockContents(DataOutputStream dos) throws IOException {
112
113 for (int i = 0; i < 1000; ++i)
114 dos.writeInt(i / 100);
115 }
116
117 static int writeTestKeyValues(HFileBlock.Writer hbw, int seed, boolean includesMemstoreTS,
118 boolean useTag) throws IOException {
119 List<KeyValue> keyValues = new ArrayList<KeyValue>();
120 Random randomizer = new Random(42l + seed);
121
122
123 for (int i = 0; i < NUM_KEYVALUES; ++i) {
124 byte[] row;
125 long timestamp;
126 byte[] family;
127 byte[] qualifier;
128 byte[] value;
129
130
131 if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) {
132 row = keyValues.get(randomizer.nextInt(keyValues.size())).getRow();
133 } else {
134 row = new byte[FIELD_LENGTH];
135 randomizer.nextBytes(row);
136 }
137 if (0 == i) {
138 family = new byte[FIELD_LENGTH];
139 randomizer.nextBytes(family);
140 } else {
141 family = keyValues.get(0).getFamily();
142 }
143 if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) {
144 qualifier = keyValues.get(
145 randomizer.nextInt(keyValues.size())).getQualifier();
146 } else {
147 qualifier = new byte[FIELD_LENGTH];
148 randomizer.nextBytes(qualifier);
149 }
150 if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) {
151 value = keyValues.get(randomizer.nextInt(keyValues.size())).getValue();
152 } else {
153 value = new byte[FIELD_LENGTH];
154 randomizer.nextBytes(value);
155 }
156 if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) {
157 timestamp = keyValues.get(
158 randomizer.nextInt(keyValues.size())).getTimestamp();
159 } else {
160 timestamp = randomizer.nextLong();
161 }
162 if (!useTag) {
163 keyValues.add(new KeyValue(row, family, qualifier, timestamp, value));
164 } else {
165 keyValues.add(new KeyValue(row, family, qualifier, timestamp, value, new Tag[] { new Tag(
166 (byte) 1, Bytes.toBytes("myTagVal")) }));
167 }
168 }
169
170
171 int totalSize = 0;
172 Collections.sort(keyValues, KeyValue.COMPARATOR);
173
174 for (KeyValue kv : keyValues) {
175 totalSize += kv.getLength();
176 if (includesMemstoreTS) {
177 long memstoreTS = randomizer.nextLong();
178 kv.setSequenceId(memstoreTS);
179 totalSize += WritableUtils.getVIntSize(memstoreTS);
180 }
181 hbw.write(kv);
182 }
183 return totalSize;
184 }
185
186 public byte[] createTestV1Block(Compression.Algorithm algo)
187 throws IOException {
188 Compressor compressor = algo.getCompressor();
189 ByteArrayOutputStream baos = new ByteArrayOutputStream();
190 OutputStream os = algo.createCompressionStream(baos, compressor, 0);
191 DataOutputStream dos = new DataOutputStream(os);
192 BlockType.META.write(dos);
193 writeTestBlockContents(dos);
194 dos.flush();
195 algo.returnCompressor(compressor);
196 return baos.toByteArray();
197 }
198
199 static HFileBlock.Writer createTestV2Block(Compression.Algorithm algo,
200 boolean includesMemstoreTS, boolean includesTag) throws IOException {
201 final BlockType blockType = BlockType.DATA;
202 HFileContext meta = new HFileContextBuilder()
203 .withCompression(algo)
204 .withIncludesMvcc(includesMemstoreTS)
205 .withIncludesTags(includesTag)
206 .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
207 .build();
208 HFileBlock.Writer hbw = new HFileBlock.Writer(null, meta);
209 DataOutputStream dos = hbw.startWriting(blockType);
210 writeTestBlockContents(dos);
211 dos.flush();
212 hbw.ensureBlockReady();
213 assertEquals(1000 * 4, hbw.getUncompressedSizeWithoutHeader());
214 hbw.release();
215 return hbw;
216 }
217
218 public String createTestBlockStr(Compression.Algorithm algo,
219 int correctLength, boolean useTag) throws IOException {
220 HFileBlock.Writer hbw = createTestV2Block(algo, includesMemstoreTS, useTag);
221 byte[] testV2Block = hbw.getHeaderAndDataForTest();
222 int osOffset = HConstants.HFILEBLOCK_HEADER_SIZE + 9;
223 if (testV2Block.length == correctLength) {
224
225
226
227
228
229 testV2Block[osOffset] = 3;
230 }
231 return Bytes.toStringBinary(testV2Block);
232 }
233
234 @Test
235 public void testNoCompression() throws IOException {
236 CacheConfig cacheConf = Mockito.mock(CacheConfig.class);
237 Mockito.when(cacheConf.isBlockCacheEnabled()).thenReturn(false);
238
239 HFileBlock block =
240 createTestV2Block(NONE, includesMemstoreTS, false).getBlockForCaching(cacheConf);
241 assertEquals(4000, block.getUncompressedSizeWithoutHeader());
242 assertEquals(4004, block.getOnDiskSizeWithoutHeader());
243 assertTrue(block.isUnpacked());
244 }
245
246 @Test
247 public void testGzipCompression() throws IOException {
248 final String correctTestBlockStr =
249 "DATABLK*\\x00\\x00\\x00>\\x00\\x00\\x0F\\xA0\\xFF\\xFF\\xFF\\xFF"
250 + "\\xFF\\xFF\\xFF\\xFF"
251 + "\\x01\\x00\\x00@\\x00\\x00\\x00\\x00["
252
253 + "\\x1F\\x8B"
254 + "\\x08"
255 + "\\x00"
256 + "\\x00\\x00\\x00\\x00"
257 + "\\x00"
258
259
260
261
262 + "\\x03"
263 + "\\xED\\xC3\\xC1\\x11\\x00 \\x08\\xC00DD\\xDD\\x7Fa"
264 + "\\xD6\\xE8\\xA3\\xB9K\\x84`\\x96Q\\xD3\\xA8\\xDB\\xA8e\\xD4c"
265 + "\\xD46\\xEA5\\xEA3\\xEA7\\xE7\\x00LI\\x5Cs\\xA0\\x0F\\x00\\x00"
266 + "\\x00\\x00\\x00\\x00";
267 final int correctGzipBlockLength = 95;
268 final String testBlockStr = createTestBlockStr(GZ, correctGzipBlockLength, false);
269
270
271 assertEquals(correctTestBlockStr.substring(0, correctGzipBlockLength - 4),
272 testBlockStr.substring(0, correctGzipBlockLength - 4));
273 }
274
275 @Test
276 public void testReaderV2() throws IOException {
277 testReaderV2Internals();
278 }
279
280 protected void testReaderV2Internals() throws IOException {
281 if(includesTag) {
282 TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
283 }
284 for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
285 for (boolean pread : new boolean[] { false, true }) {
286 LOG.info("testReaderV2: Compression algorithm: " + algo +
287 ", pread=" + pread);
288 Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_"
289 + algo);
290 FSDataOutputStream os = fs.create(path);
291 HFileContext meta = new HFileContextBuilder()
292 .withCompression(algo)
293 .withIncludesMvcc(includesMemstoreTS)
294 .withIncludesTags(includesTag)
295 .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
296 .build();
297 HFileBlock.Writer hbw = new HFileBlock.Writer(null,
298 meta);
299 long totalSize = 0;
300 for (int blockId = 0; blockId < 2; ++blockId) {
301 DataOutputStream dos = hbw.startWriting(BlockType.DATA);
302 for (int i = 0; i < 1234; ++i)
303 dos.writeInt(i);
304 hbw.writeHeaderAndData(os);
305 totalSize += hbw.getOnDiskSizeWithHeader();
306 }
307 os.close();
308
309 FSDataInputStream is = fs.open(path);
310 meta = new HFileContextBuilder()
311 .withHBaseCheckSum(true)
312 .withIncludesMvcc(includesMemstoreTS)
313 .withIncludesTags(includesTag)
314 .withCompression(algo).build();
315 HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta);
316 HFileBlock b = hbr.readBlockData(0, -1, -1, pread);
317 is.close();
318 assertEquals(0, HFile.getChecksumFailuresCount());
319
320 b.sanityCheck();
321 assertEquals(4936, b.getUncompressedSizeWithoutHeader());
322 assertEquals(algo == GZ ? 2173 : 4936,
323 b.getOnDiskSizeWithoutHeader() - b.totalChecksumBytes());
324 HFileBlock expected = b;
325
326 if (algo == GZ) {
327 is = fs.open(path);
328 hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta);
329 b = hbr.readBlockData(0, 2173 + HConstants.HFILEBLOCK_HEADER_SIZE +
330 b.totalChecksumBytes(), -1, pread);
331 assertEquals(expected, b);
332 int wrongCompressedSize = 2172;
333 try {
334 b = hbr.readBlockData(0, wrongCompressedSize
335 + HConstants.HFILEBLOCK_HEADER_SIZE, -1, pread);
336 fail("Exception expected");
337 } catch (IOException ex) {
338 String expectedPrefix = "On-disk size without header provided is "
339 + wrongCompressedSize + ", but block header contains "
340 + b.getOnDiskSizeWithoutHeader() + ".";
341 assertTrue("Invalid exception message: '" + ex.getMessage()
342 + "'.\nMessage is expected to start with: '" + expectedPrefix
343 + "'", ex.getMessage().startsWith(expectedPrefix));
344 }
345 is.close();
346 }
347 }
348 }
349 }
350
351
352
353
354
355 @Test
356 public void testDataBlockEncoding() throws IOException {
357 testInternals();
358 }
359
360 private void testInternals() throws IOException {
361 final int numBlocks = 5;
362 if(includesTag) {
363 TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
364 }
365 for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
366 for (boolean pread : new boolean[] { false, true }) {
367 for (DataBlockEncoding encoding : DataBlockEncoding.values()) {
368 Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_"
369 + algo + "_" + encoding.toString());
370 FSDataOutputStream os = fs.create(path);
371 HFileDataBlockEncoder dataBlockEncoder = (encoding != DataBlockEncoding.NONE) ?
372 new HFileDataBlockEncoderImpl(encoding) : NoOpDataBlockEncoder.INSTANCE;
373 HFileContext meta = new HFileContextBuilder()
374 .withCompression(algo)
375 .withIncludesMvcc(includesMemstoreTS)
376 .withIncludesTags(includesTag)
377 .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
378 .build();
379 HFileBlock.Writer hbw = new HFileBlock.Writer(dataBlockEncoder, meta);
380 long totalSize = 0;
381 final List<Integer> encodedSizes = new ArrayList<Integer>();
382 final List<ByteBuffer> encodedBlocks = new ArrayList<ByteBuffer>();
383 for (int blockId = 0; blockId < numBlocks; ++blockId) {
384 hbw.startWriting(BlockType.DATA);
385 writeTestKeyValues(hbw, blockId, includesMemstoreTS, includesTag);
386 hbw.writeHeaderAndData(os);
387 int headerLen = HConstants.HFILEBLOCK_HEADER_SIZE;
388 byte[] encodedResultWithHeader = hbw.getUncompressedBufferWithHeader().array();
389 final int encodedSize = encodedResultWithHeader.length - headerLen;
390 if (encoding != DataBlockEncoding.NONE) {
391
392
393 headerLen += DataBlockEncoding.ID_SIZE;
394 }
395 byte[] encodedDataSection =
396 new byte[encodedResultWithHeader.length - headerLen];
397 System.arraycopy(encodedResultWithHeader, headerLen,
398 encodedDataSection, 0, encodedDataSection.length);
399 final ByteBuffer encodedBuf =
400 ByteBuffer.wrap(encodedDataSection);
401 encodedSizes.add(encodedSize);
402 encodedBlocks.add(encodedBuf);
403 totalSize += hbw.getOnDiskSizeWithHeader();
404 }
405 os.close();
406
407 FSDataInputStream is = fs.open(path);
408 meta = new HFileContextBuilder()
409 .withHBaseCheckSum(true)
410 .withCompression(algo)
411 .withIncludesMvcc(includesMemstoreTS)
412 .withIncludesTags(includesTag)
413 .build();
414 HFileBlock.FSReaderImpl hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta);
415 hbr.setDataBlockEncoder(dataBlockEncoder);
416 hbr.setIncludesMemstoreTS(includesMemstoreTS);
417 HFileBlock blockFromHFile, blockUnpacked;
418 int pos = 0;
419 for (int blockId = 0; blockId < numBlocks; ++blockId) {
420 blockFromHFile = hbr.readBlockData(pos, -1, -1, pread);
421 assertEquals(0, HFile.getChecksumFailuresCount());
422 blockFromHFile.sanityCheck();
423 pos += blockFromHFile.getOnDiskSizeWithHeader();
424 assertEquals((int) encodedSizes.get(blockId),
425 blockFromHFile.getUncompressedSizeWithoutHeader());
426 assertEquals(meta.isCompressedOrEncrypted(), !blockFromHFile.isUnpacked());
427 long packedHeapsize = blockFromHFile.heapSize();
428 blockUnpacked = blockFromHFile.unpack(meta, hbr);
429 assertTrue(blockUnpacked.isUnpacked());
430 if (meta.isCompressedOrEncrypted()) {
431 LOG.info("packedHeapsize=" + packedHeapsize + ", unpackedHeadsize=" + blockUnpacked
432 .heapSize());
433 assertFalse(packedHeapsize == blockUnpacked.heapSize());
434 assertTrue("Packed heapSize should be < unpacked heapSize",
435 packedHeapsize < blockUnpacked.heapSize());
436 }
437 ByteBuffer actualBuffer = blockUnpacked.getBufferWithoutHeader();
438 if (encoding != DataBlockEncoding.NONE) {
439
440 assertEquals(
441 "Unexpected first byte with " + buildMessageDetails(algo, encoding, pread),
442 Long.toHexString(0), Long.toHexString(actualBuffer.get(0)));
443 assertEquals(
444 "Unexpected second byte with " + buildMessageDetails(algo, encoding, pread),
445 Long.toHexString(encoding.getId()), Long.toHexString(actualBuffer.get(1)));
446 actualBuffer.position(2);
447 actualBuffer = actualBuffer.slice();
448 }
449
450 ByteBuffer expectedBuffer = encodedBlocks.get(blockId);
451 expectedBuffer.rewind();
452
453
454 assertBuffersEqual(expectedBuffer, actualBuffer, algo, encoding, pread);
455
456
457 for (boolean reuseBuffer : new boolean[] { false, true }) {
458 ByteBuffer serialized = ByteBuffer.allocate(blockFromHFile.getSerializedLength());
459 blockFromHFile.serialize(serialized);
460 HFileBlock deserialized =
461 (HFileBlock) blockFromHFile.getDeserializer().deserialize(serialized, reuseBuffer);
462 assertEquals(
463 "Serialization did not preserve block state. reuseBuffer=" + reuseBuffer,
464 blockFromHFile, deserialized);
465
466 if (blockFromHFile != blockUnpacked) {
467 assertEquals("Deserializaed block cannot be unpacked correctly.",
468 blockUnpacked, deserialized.unpack(meta, hbr));
469 }
470 }
471 }
472 is.close();
473 }
474 }
475 }
476 }
477
478 static String buildMessageDetails(Algorithm compression, DataBlockEncoding encoding,
479 boolean pread) {
480 return String.format("compression %s, encoding %s, pread %s", compression, encoding, pread);
481 }
482
483 static void assertBuffersEqual(ByteBuffer expectedBuffer,
484 ByteBuffer actualBuffer, Compression.Algorithm compression,
485 DataBlockEncoding encoding, boolean pread) {
486 if (!actualBuffer.equals(expectedBuffer)) {
487 int prefix = 0;
488 int minLimit = Math.min(expectedBuffer.limit(), actualBuffer.limit());
489 while (prefix < minLimit &&
490 expectedBuffer.get(prefix) == actualBuffer.get(prefix)) {
491 prefix++;
492 }
493
494 fail(String.format(
495 "Content mismatch for %s, commonPrefix %d, expected %s, got %s",
496 buildMessageDetails(compression, encoding, pread), prefix,
497 nextBytesToStr(expectedBuffer, prefix),
498 nextBytesToStr(actualBuffer, prefix)));
499 }
500 }
501
502
503
504
505
506 private static String nextBytesToStr(ByteBuffer buf, int pos) {
507 int maxBytes = buf.limit() - pos;
508 int numBytes = Math.min(16, maxBytes);
509 return Bytes.toStringBinary(buf.array(), buf.arrayOffset() + pos,
510 numBytes) + (numBytes < maxBytes ? "..." : "");
511 }
512
513 @Test
514 public void testPreviousOffset() throws IOException {
515 testPreviousOffsetInternals();
516 }
517
518 protected void testPreviousOffsetInternals() throws IOException {
519
520 for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
521 for (boolean pread : BOOLEAN_VALUES) {
522 for (boolean cacheOnWrite : BOOLEAN_VALUES) {
523 Random rand = defaultRandom();
524 LOG.info("testPreviousOffset:Compression algorithm: " + algo +
525 ", pread=" + pread +
526 ", cacheOnWrite=" + cacheOnWrite);
527 Path path = new Path(TEST_UTIL.getDataTestDir(), "prev_offset");
528 List<Long> expectedOffsets = new ArrayList<Long>();
529 List<Long> expectedPrevOffsets = new ArrayList<Long>();
530 List<BlockType> expectedTypes = new ArrayList<BlockType>();
531 List<ByteBuffer> expectedContents = cacheOnWrite
532 ? new ArrayList<ByteBuffer>() : null;
533 long totalSize = writeBlocks(rand, algo, path, expectedOffsets,
534 expectedPrevOffsets, expectedTypes, expectedContents);
535
536 FSDataInputStream is = fs.open(path);
537 HFileContext meta = new HFileContextBuilder()
538 .withHBaseCheckSum(true)
539 .withIncludesMvcc(includesMemstoreTS)
540 .withIncludesTags(includesTag)
541 .withCompression(algo).build();
542 HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta);
543 long curOffset = 0;
544 for (int i = 0; i < NUM_TEST_BLOCKS; ++i) {
545 if (!pread) {
546 assertEquals(is.getPos(), curOffset + (i == 0 ? 0 :
547 HConstants.HFILEBLOCK_HEADER_SIZE));
548 }
549
550 assertEquals(expectedOffsets.get(i).longValue(), curOffset);
551 if (detailedLogging) {
552 LOG.info("Reading block #" + i + " at offset " + curOffset);
553 }
554 HFileBlock b = hbr.readBlockData(curOffset, -1, -1, pread);
555 if (detailedLogging) {
556 LOG.info("Block #" + i + ": " + b);
557 }
558 assertEquals("Invalid block #" + i + "'s type:",
559 expectedTypes.get(i), b.getBlockType());
560 assertEquals("Invalid previous block offset for block " + i
561 + " of " + "type " + b.getBlockType() + ":",
562 (long) expectedPrevOffsets.get(i), b.getPrevBlockOffset());
563 b.sanityCheck();
564 assertEquals(curOffset, b.getOffset());
565
566
567
568 HFileBlock b2 = hbr.readBlockData(curOffset,
569 b.getOnDiskSizeWithHeader(), -1, pread);
570 b2.sanityCheck();
571
572 assertEquals(b.getBlockType(), b2.getBlockType());
573 assertEquals(b.getOnDiskSizeWithoutHeader(),
574 b2.getOnDiskSizeWithoutHeader());
575 assertEquals(b.getOnDiskSizeWithHeader(),
576 b2.getOnDiskSizeWithHeader());
577 assertEquals(b.getUncompressedSizeWithoutHeader(),
578 b2.getUncompressedSizeWithoutHeader());
579 assertEquals(b.getPrevBlockOffset(), b2.getPrevBlockOffset());
580 assertEquals(curOffset, b2.getOffset());
581 assertEquals(b.getBytesPerChecksum(), b2.getBytesPerChecksum());
582 assertEquals(b.getOnDiskDataSizeWithHeader(),
583 b2.getOnDiskDataSizeWithHeader());
584 assertEquals(0, HFile.getChecksumFailuresCount());
585
586 curOffset += b.getOnDiskSizeWithHeader();
587
588 if (cacheOnWrite) {
589
590
591
592 b = b.unpack(meta, hbr);
593
594
595 ByteBuffer bufRead = b.getBufferWithHeader();
596 ByteBuffer bufExpected = expectedContents.get(i);
597 boolean bytesAreCorrect = Bytes.compareTo(bufRead.array(),
598 bufRead.arrayOffset(),
599 bufRead.limit() - b.totalChecksumBytes(),
600 bufExpected.array(), bufExpected.arrayOffset(),
601 bufExpected.limit()) == 0;
602 String wrongBytesMsg = "";
603
604 if (!bytesAreCorrect) {
605
606
607 wrongBytesMsg = "Expected bytes in block #" + i + " (algo="
608 + algo + ", pread=" + pread
609 + ", cacheOnWrite=" + cacheOnWrite + "):\n";
610 wrongBytesMsg += Bytes.toStringBinary(bufExpected.array(),
611 bufExpected.arrayOffset(), Math.min(32 + 10, bufExpected.limit()))
612 + ", actual:\n"
613 + Bytes.toStringBinary(bufRead.array(),
614 bufRead.arrayOffset(), Math.min(32 + 10, bufRead.limit()));
615 if (detailedLogging) {
616 LOG.warn("expected header" +
617 HFileBlock.toStringHeader(bufExpected) +
618 "\nfound header" +
619 HFileBlock.toStringHeader(bufRead));
620 LOG.warn("bufread offset " + bufRead.arrayOffset() +
621 " limit " + bufRead.limit() +
622 " expected offset " + bufExpected.arrayOffset() +
623 " limit " + bufExpected.limit());
624 LOG.warn(wrongBytesMsg);
625 }
626 }
627 assertTrue(wrongBytesMsg, bytesAreCorrect);
628 }
629 }
630
631 assertEquals(curOffset, fs.getFileStatus(path).getLen());
632 is.close();
633 }
634 }
635 }
636 }
637
638 private Random defaultRandom() {
639 return new Random(189237);
640 }
641
642 private class BlockReaderThread implements Callable<Boolean> {
643 private final String clientId;
644 private final HFileBlock.FSReader hbr;
645 private final List<Long> offsets;
646 private final List<BlockType> types;
647 private final long fileSize;
648
649 public BlockReaderThread(String clientId,
650 HFileBlock.FSReader hbr, List<Long> offsets, List<BlockType> types,
651 long fileSize) {
652 this.clientId = clientId;
653 this.offsets = offsets;
654 this.hbr = hbr;
655 this.types = types;
656 this.fileSize = fileSize;
657 }
658
659 @Override
660 public Boolean call() throws Exception {
661 Random rand = new Random(clientId.hashCode());
662 long endTime = System.currentTimeMillis() + 10000;
663 int numBlocksRead = 0;
664 int numPositionalRead = 0;
665 int numWithOnDiskSize = 0;
666 while (System.currentTimeMillis() < endTime) {
667 int blockId = rand.nextInt(NUM_TEST_BLOCKS);
668 long offset = offsets.get(blockId);
669 boolean pread = rand.nextBoolean();
670 boolean withOnDiskSize = rand.nextBoolean();
671 long expectedSize =
672 (blockId == NUM_TEST_BLOCKS - 1 ? fileSize
673 : offsets.get(blockId + 1)) - offset;
674
675 HFileBlock b;
676 try {
677 long onDiskSizeArg = withOnDiskSize ? expectedSize : -1;
678 b = hbr.readBlockData(offset, onDiskSizeArg, -1, pread);
679 } catch (IOException ex) {
680 LOG.error("Error in client " + clientId + " trying to read block at "
681 + offset + ", pread=" + pread + ", withOnDiskSize=" +
682 withOnDiskSize, ex);
683 return false;
684 }
685
686 assertEquals(types.get(blockId), b.getBlockType());
687 assertEquals(expectedSize, b.getOnDiskSizeWithHeader());
688 assertEquals(offset, b.getOffset());
689
690 ++numBlocksRead;
691 if (pread)
692 ++numPositionalRead;
693 if (withOnDiskSize)
694 ++numWithOnDiskSize;
695 }
696 LOG.info("Client " + clientId + " successfully read " + numBlocksRead +
697 " blocks (with pread: " + numPositionalRead + ", with onDiskSize " +
698 "specified: " + numWithOnDiskSize + ")");
699
700 return true;
701 }
702
703 }
704
705 @Test
706 public void testConcurrentReading() throws Exception {
707 testConcurrentReadingInternals();
708 }
709
710 protected void testConcurrentReadingInternals() throws IOException,
711 InterruptedException, ExecutionException {
712 for (Compression.Algorithm compressAlgo : COMPRESSION_ALGORITHMS) {
713 Path path =
714 new Path(TEST_UTIL.getDataTestDir(), "concurrent_reading");
715 Random rand = defaultRandom();
716 List<Long> offsets = new ArrayList<Long>();
717 List<BlockType> types = new ArrayList<BlockType>();
718 writeBlocks(rand, compressAlgo, path, offsets, null, types, null);
719 FSDataInputStream is = fs.open(path);
720 long fileSize = fs.getFileStatus(path).getLen();
721 HFileContext meta = new HFileContextBuilder()
722 .withHBaseCheckSum(true)
723 .withIncludesMvcc(includesMemstoreTS)
724 .withIncludesTags(includesTag)
725 .withCompression(compressAlgo)
726 .build();
727 HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, fileSize, meta);
728
729 Executor exec = Executors.newFixedThreadPool(NUM_READER_THREADS);
730 ExecutorCompletionService<Boolean> ecs =
731 new ExecutorCompletionService<Boolean>(exec);
732
733 for (int i = 0; i < NUM_READER_THREADS; ++i) {
734 ecs.submit(new BlockReaderThread("reader_" + (char) ('A' + i), hbr,
735 offsets, types, fileSize));
736 }
737
738 for (int i = 0; i < NUM_READER_THREADS; ++i) {
739 Future<Boolean> result = ecs.take();
740 assertTrue(result.get());
741 if (detailedLogging) {
742 LOG.info(String.valueOf(i + 1)
743 + " reader threads finished successfully (algo=" + compressAlgo
744 + ")");
745 }
746 }
747
748 is.close();
749 }
750 }
751
752 private long writeBlocks(Random rand, Compression.Algorithm compressAlgo,
753 Path path, List<Long> expectedOffsets, List<Long> expectedPrevOffsets,
754 List<BlockType> expectedTypes, List<ByteBuffer> expectedContents
755 ) throws IOException {
756 boolean cacheOnWrite = expectedContents != null;
757 FSDataOutputStream os = fs.create(path);
758 HFileContext meta = new HFileContextBuilder()
759 .withHBaseCheckSum(true)
760 .withIncludesMvcc(includesMemstoreTS)
761 .withIncludesTags(includesTag)
762 .withCompression(compressAlgo)
763 .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
764 .build();
765 HFileBlock.Writer hbw = new HFileBlock.Writer(null, meta);
766 Map<BlockType, Long> prevOffsetByType = new HashMap<BlockType, Long>();
767 long totalSize = 0;
768 for (int i = 0; i < NUM_TEST_BLOCKS; ++i) {
769 long pos = os.getPos();
770 int blockTypeOrdinal = rand.nextInt(BlockType.values().length);
771 if (blockTypeOrdinal == BlockType.ENCODED_DATA.ordinal()) {
772 blockTypeOrdinal = BlockType.DATA.ordinal();
773 }
774 BlockType bt = BlockType.values()[blockTypeOrdinal];
775 DataOutputStream dos = hbw.startWriting(bt);
776 int size = rand.nextInt(500);
777 for (int j = 0; j < size; ++j) {
778
779 dos.writeShort(i + 1);
780 dos.writeInt(j + 1);
781 }
782
783 if (expectedOffsets != null)
784 expectedOffsets.add(os.getPos());
785
786 if (expectedPrevOffsets != null) {
787 Long prevOffset = prevOffsetByType.get(bt);
788 expectedPrevOffsets.add(prevOffset != null ? prevOffset : -1);
789 prevOffsetByType.put(bt, os.getPos());
790 }
791
792 expectedTypes.add(bt);
793
794 hbw.writeHeaderAndData(os);
795 totalSize += hbw.getOnDiskSizeWithHeader();
796
797 if (cacheOnWrite)
798 expectedContents.add(hbw.getUncompressedBufferWithHeader());
799
800 if (detailedLogging) {
801 LOG.info("Written block #" + i + " of type " + bt
802 + ", uncompressed size " + hbw.getUncompressedSizeWithoutHeader()
803 + ", packed size " + hbw.getOnDiskSizeWithoutHeader()
804 + " at offset " + pos);
805 }
806 }
807 os.close();
808 LOG.info("Created a temporary file at " + path + ", "
809 + fs.getFileStatus(path).getLen() + " byte, compression=" +
810 compressAlgo);
811 return totalSize;
812 }
813
814 @Test
815 public void testBlockHeapSize() {
816 testBlockHeapSizeInternals();
817 }
818
819 protected void testBlockHeapSizeInternals() {
820 if (ClassSize.is32BitJVM()) {
821 assertTrue(HFileBlock.BYTE_BUFFER_HEAP_SIZE == 64);
822 } else {
823 assertTrue(HFileBlock.BYTE_BUFFER_HEAP_SIZE == 80);
824 }
825
826 for (int size : new int[] { 100, 256, 12345 }) {
827 byte[] byteArr = new byte[HConstants.HFILEBLOCK_HEADER_SIZE + size];
828 ByteBuffer buf = ByteBuffer.wrap(byteArr, 0, size);
829 HFileContext meta = new HFileContextBuilder()
830 .withIncludesMvcc(includesMemstoreTS)
831 .withIncludesTags(includesTag)
832 .withHBaseCheckSum(false)
833 .withCompression(Algorithm.NONE)
834 .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
835 .withChecksumType(ChecksumType.NULL).build();
836 HFileBlock block = new HFileBlock(BlockType.DATA, size, size, -1, buf,
837 HFileBlock.FILL_HEADER, -1,
838 0, meta);
839 long byteBufferExpectedSize =
840 ClassSize.align(ClassSize.estimateBase(buf.getClass(), true)
841 + HConstants.HFILEBLOCK_HEADER_SIZE + size);
842 long hfileMetaSize = ClassSize.align(ClassSize.estimateBase(HFileContext.class, true));
843 long hfileBlockExpectedSize =
844 ClassSize.align(ClassSize.estimateBase(HFileBlock.class, true));
845 long expected = hfileBlockExpectedSize + byteBufferExpectedSize + hfileMetaSize;
846 assertEquals("Block data size: " + size + ", byte buffer expected " +
847 "size: " + byteBufferExpectedSize + ", HFileBlock class expected " +
848 "size: " + hfileBlockExpectedSize + ";", expected,
849 block.heapSize());
850 }
851 }
852 }