View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
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    // change this value to activate more logs
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    // Used to generate KeyValues
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     // This compresses really well.
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); // just any fixed number
121 
122     // generate keyValues
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       // generate it or repeat, it should compress well
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     // sort it and write to stream
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); // Let's make this a meta block.
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       // Force-set the "OS" field of the gzip header to 3 (Unix) to avoid
225       // variations across operating systems.
226       // See http://www.gzip.org/zlib/rfc-gzip.html for gzip format.
227       // We only make this change when the compressed block length matches.
228       // Otherwise, there are obviously other inconsistencies.
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             + "\\x0" + ChecksumType.getDefaultChecksumType().getCode()
252             + "\\x00\\x00@\\x00\\x00\\x00\\x00["
253             // gzip-compressed block: http://www.gzip.org/zlib/rfc-gzip.html
254             + "\\x1F\\x8B"  // gzip magic signature
255             + "\\x08"  // Compression method: 8 = "deflate"
256             + "\\x00"  // Flags
257             + "\\x00\\x00\\x00\\x00"  // mtime
258             + "\\x00"  // XFL (extra flags)
259             // OS (0 = FAT filesystems, 3 = Unix). However, this field
260             // sometimes gets set to 0 on Linux and Mac, so we reset it to 3.
261             // This appears to be a difference caused by the availability
262             // (and use) of the native GZ codec.
263             + "\\x03"
264             + "\\xED\\xC3\\xC1\\x11\\x00 \\x08\\xC00DD\\xDD\\x7Fa"
265             + "\\xD6\\xE8\\xA3\\xB9K\\x84`\\x96Q\\xD3\\xA8\\xDB\\xA8e\\xD4c"
266             + "\\xD46\\xEA5\\xEA3\\xEA7\\xE7\\x00LI\\x5Cs\\xA0\\x0F\\x00\\x00"
267             + "\\x00\\x00\\x00\\x00"; //  4 byte checksum (ignored)
268     final int correctGzipBlockLength = 95;
269     final String testBlockStr = createTestBlockStr(GZ, correctGzipBlockLength, false);
270     // We ignore the block checksum because createTestBlockStr can change the
271     // gzip header after the block is produced
272     assertEquals(correctTestBlockStr.substring(0, correctGzipBlockLength - 4),
273       testBlockStr.substring(0, correctGzipBlockLength - 4));
274   }
275 
276   @Test
277   public void testReaderV2() throws IOException {
278     testReaderV2Internals();
279   }
280 
281   protected void testReaderV2Internals() throws IOException {
282     if(includesTag) {
283       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
284     }
285     for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
286       for (boolean pread : new boolean[] { false, true }) {
287           LOG.info("testReaderV2: Compression algorithm: " + algo +
288                    ", pread=" + pread);
289         Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_"
290             + algo);
291         FSDataOutputStream os = fs.create(path);
292         HFileContext meta = new HFileContextBuilder()
293                            .withCompression(algo)
294                            .withIncludesMvcc(includesMemstoreTS)
295                            .withIncludesTags(includesTag)
296                            .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
297                            .build();
298         HFileBlock.Writer hbw = new HFileBlock.Writer(null,
299            meta);
300         long totalSize = 0;
301         for (int blockId = 0; blockId < 2; ++blockId) {
302           DataOutputStream dos = hbw.startWriting(BlockType.DATA);
303           for (int i = 0; i < 1234; ++i)
304             dos.writeInt(i);
305           hbw.writeHeaderAndData(os);
306           totalSize += hbw.getOnDiskSizeWithHeader();
307         }
308         os.close();
309 
310         FSDataInputStream is = fs.open(path);
311         meta = new HFileContextBuilder()
312         .withHBaseCheckSum(true)
313         .withIncludesMvcc(includesMemstoreTS)
314         .withIncludesTags(includesTag)
315         .withCompression(algo).build();
316         HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta);
317         HFileBlock b = hbr.readBlockData(0, -1, pread);
318         is.close();
319         assertEquals(0, HFile.getChecksumFailuresCount());
320 
321         b.sanityCheck();
322         assertEquals(4936, b.getUncompressedSizeWithoutHeader());
323         assertEquals(algo == GZ ? 2173 : 4936,
324                      b.getOnDiskSizeWithoutHeader() - b.totalChecksumBytes());
325         HFileBlock expected = b;
326 
327         if (algo == GZ) {
328           is = fs.open(path);
329           hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta);
330           b = hbr.readBlockData(0, 2173 + HConstants.HFILEBLOCK_HEADER_SIZE +
331                                 b.totalChecksumBytes(), pread);
332           assertEquals(expected, b);
333           int wrongCompressedSize = 2172;
334           try {
335             b = hbr.readBlockData(0, wrongCompressedSize
336                 + HConstants.HFILEBLOCK_HEADER_SIZE, pread);
337             fail("Exception expected");
338           } catch (IOException ex) {
339             String expectedPrefix = "Passed in onDiskSizeWithHeader=";
340             assertTrue("Invalid exception message: '" + ex.getMessage()
341                 + "'.\nMessage is expected to start with: '" + expectedPrefix
342                 + "'", ex.getMessage().startsWith(expectedPrefix));
343           }
344           is.close();
345         }
346       }
347     }
348   }
349 
350   /**
351    * Test encoding/decoding data blocks.
352    * @throws IOException a bug or a problem with temporary files.
353    */
354   @Test
355   public void testDataBlockEncoding() throws IOException {
356     testInternals();
357   }
358 
359   private void testInternals() throws IOException {
360     final int numBlocks = 5;
361     if(includesTag) {
362       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
363     }
364     for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
365       for (boolean pread : new boolean[] { false, true }) {
366         for (DataBlockEncoding encoding : DataBlockEncoding.values()) {
367           Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_"
368               + algo + "_" + encoding.toString());
369           FSDataOutputStream os = fs.create(path);
370           HFileDataBlockEncoder dataBlockEncoder = (encoding != DataBlockEncoding.NONE) ?
371               new HFileDataBlockEncoderImpl(encoding) : NoOpDataBlockEncoder.INSTANCE;
372           HFileContext meta = new HFileContextBuilder()
373                               .withCompression(algo)
374                               .withIncludesMvcc(includesMemstoreTS)
375                               .withIncludesTags(includesTag)
376                               .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
377                               .build();
378           HFileBlock.Writer hbw = new HFileBlock.Writer(dataBlockEncoder, meta);
379           long totalSize = 0;
380           final List<Integer> encodedSizes = new ArrayList<Integer>();
381           final List<ByteBuffer> encodedBlocks = new ArrayList<ByteBuffer>();
382           for (int blockId = 0; blockId < numBlocks; ++blockId) {
383             hbw.startWriting(BlockType.DATA);
384             writeTestKeyValues(hbw, blockId, includesMemstoreTS, includesTag);
385             hbw.writeHeaderAndData(os);
386             int headerLen = HConstants.HFILEBLOCK_HEADER_SIZE;
387             byte[] encodedResultWithHeader = hbw.getUncompressedBufferWithHeader().array();
388             final int encodedSize = encodedResultWithHeader.length - headerLen;
389             if (encoding != DataBlockEncoding.NONE) {
390               // We need to account for the two-byte encoding algorithm ID that
391               // comes after the 24-byte block header but before encoded KVs.
392               headerLen += DataBlockEncoding.ID_SIZE;
393             }
394             byte[] encodedDataSection =
395                 new byte[encodedResultWithHeader.length - headerLen];
396             System.arraycopy(encodedResultWithHeader, headerLen,
397                 encodedDataSection, 0, encodedDataSection.length);
398             final ByteBuffer encodedBuf =
399                 ByteBuffer.wrap(encodedDataSection);
400             encodedSizes.add(encodedSize);
401             encodedBlocks.add(encodedBuf);
402             totalSize += hbw.getOnDiskSizeWithHeader();
403           }
404           os.close();
405 
406           FSDataInputStream is = fs.open(path);
407           meta = new HFileContextBuilder()
408                 .withHBaseCheckSum(true)
409                 .withCompression(algo)
410                 .withIncludesMvcc(includesMemstoreTS)
411                 .withIncludesTags(includesTag)
412                 .build();
413           HFileBlock.FSReaderImpl hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta);
414           hbr.setDataBlockEncoder(dataBlockEncoder);
415           hbr.setIncludesMemstoreTS(includesMemstoreTS);
416           HFileBlock blockFromHFile, blockUnpacked;
417           int pos = 0;
418           for (int blockId = 0; blockId < numBlocks; ++blockId) {
419             blockFromHFile = hbr.readBlockData(pos, -1, pread);
420             assertEquals(0, HFile.getChecksumFailuresCount());
421             blockFromHFile.sanityCheck();
422             pos += blockFromHFile.getOnDiskSizeWithHeader();
423             assertEquals((int) encodedSizes.get(blockId),
424               blockFromHFile.getUncompressedSizeWithoutHeader());
425             assertEquals(meta.isCompressedOrEncrypted(), !blockFromHFile.isUnpacked());
426             long packedHeapsize = blockFromHFile.heapSize();
427             blockUnpacked = blockFromHFile.unpack(meta, hbr);
428             assertTrue(blockUnpacked.isUnpacked());
429             if (meta.isCompressedOrEncrypted()) {
430               LOG.info("packedHeapsize=" + packedHeapsize + ", unpackedHeadsize=" + blockUnpacked
431                 .heapSize());
432               assertFalse(packedHeapsize == blockUnpacked.heapSize());
433               assertTrue("Packed heapSize should be < unpacked heapSize",
434                 packedHeapsize < blockUnpacked.heapSize());
435             }
436             ByteBuffer actualBuffer = blockUnpacked.getBufferWithoutHeader();
437             if (encoding != DataBlockEncoding.NONE) {
438               // We expect a two-byte big-endian encoding id.
439               assertEquals(
440                 "Unexpected first byte with " + buildMessageDetails(algo, encoding, pread),
441                 Long.toHexString(0), Long.toHexString(actualBuffer.get(0)));
442               assertEquals(
443                 "Unexpected second byte with " + buildMessageDetails(algo, encoding, pread),
444                 Long.toHexString(encoding.getId()), Long.toHexString(actualBuffer.get(1)));
445               actualBuffer.position(2);
446               actualBuffer = actualBuffer.slice();
447             }
448 
449             ByteBuffer expectedBuffer = encodedBlocks.get(blockId);
450             expectedBuffer.rewind();
451 
452             // test if content matches, produce nice message
453             assertBuffersEqual(expectedBuffer, actualBuffer, algo, encoding, pread);
454 
455             // test serialized blocks
456             for (boolean reuseBuffer : new boolean[] { false, true }) {
457               ByteBuffer serialized = ByteBuffer.allocate(blockFromHFile.getSerializedLength());
458               blockFromHFile.serialize(serialized);
459               HFileBlock deserialized =
460                 (HFileBlock) blockFromHFile.getDeserializer().deserialize(serialized, reuseBuffer);
461               assertEquals(
462                 "Serialization did not preserve block state. reuseBuffer=" + reuseBuffer,
463                 blockFromHFile, deserialized);
464               // intentional reference comparison
465               if (blockFromHFile != blockUnpacked) {
466                 assertEquals("Deserializaed block cannot be unpacked correctly.",
467                   blockUnpacked, deserialized.unpack(meta, hbr));
468               }
469             }
470           }
471           is.close();
472         }
473       }
474     }
475   }
476 
477   static String buildMessageDetails(Algorithm compression, DataBlockEncoding encoding,
478       boolean pread) {
479     return String.format("compression %s, encoding %s, pread %s", compression, encoding, pread);
480   }
481 
482   static void assertBuffersEqual(ByteBuffer expectedBuffer,
483       ByteBuffer actualBuffer, Compression.Algorithm compression,
484       DataBlockEncoding encoding, boolean pread) {
485     if (!actualBuffer.equals(expectedBuffer)) {
486       int prefix = 0;
487       int minLimit = Math.min(expectedBuffer.limit(), actualBuffer.limit());
488       while (prefix < minLimit &&
489           expectedBuffer.get(prefix) == actualBuffer.get(prefix)) {
490         prefix++;
491       }
492 
493       fail(String.format(
494           "Content mismatch for %s, commonPrefix %d, expected %s, got %s",
495           buildMessageDetails(compression, encoding, pread), prefix,
496           nextBytesToStr(expectedBuffer, prefix),
497           nextBytesToStr(actualBuffer, prefix)));
498     }
499   }
500 
501   /**
502    * Convert a few next bytes in the given buffer at the given position to
503    * string. Used for error messages.
504    */
505   private static String nextBytesToStr(ByteBuffer buf, int pos) {
506     int maxBytes = buf.limit() - pos;
507     int numBytes = Math.min(16, maxBytes);
508     return Bytes.toStringBinary(buf.array(), buf.arrayOffset() + pos,
509         numBytes) + (numBytes < maxBytes ? "..." : "");
510   }
511 
512   @Test
513   public void testPreviousOffset() throws IOException {
514     testPreviousOffsetInternals();
515   }
516 
517   protected void testPreviousOffsetInternals() throws IOException {
518     // TODO: parameterize these nested loops.
519     for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) {
520       for (boolean pread : BOOLEAN_VALUES) {
521         for (boolean cacheOnWrite : BOOLEAN_VALUES) {
522           Random rand = defaultRandom();
523           LOG.info("testPreviousOffset:Compression algorithm: " + algo +
524                    ", pread=" + pread +
525                    ", cacheOnWrite=" + cacheOnWrite);
526           Path path = new Path(TEST_UTIL.getDataTestDir(), "prev_offset");
527           List<Long> expectedOffsets = new ArrayList<Long>();
528           List<Long> expectedPrevOffsets = new ArrayList<Long>();
529           List<BlockType> expectedTypes = new ArrayList<BlockType>();
530           List<ByteBuffer> expectedContents = cacheOnWrite
531               ? new ArrayList<ByteBuffer>() : null;
532           long totalSize = writeBlocks(rand, algo, path, expectedOffsets,
533               expectedPrevOffsets, expectedTypes, expectedContents);
534 
535           FSDataInputStream is = fs.open(path);
536           HFileContext meta = new HFileContextBuilder()
537                               .withHBaseCheckSum(true)
538                               .withIncludesMvcc(includesMemstoreTS)
539                               .withIncludesTags(includesTag)
540                               .withCompression(algo).build();
541           HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta);
542           long curOffset = 0;
543           for (int i = 0; i < NUM_TEST_BLOCKS; ++i) {
544             if (!pread) {
545               assertEquals(is.getPos(), curOffset + (i == 0 ? 0 :
546                 HConstants.HFILEBLOCK_HEADER_SIZE));
547             }
548 
549             assertEquals(expectedOffsets.get(i).longValue(), curOffset);
550             if (detailedLogging) {
551               LOG.info("Reading block #" + i + " at offset " + curOffset);
552             }
553             HFileBlock b = hbr.readBlockData(curOffset, -1, pread);
554             if (detailedLogging) {
555               LOG.info("Block #" + i + ": " + b);
556             }
557             assertEquals("Invalid block #" + i + "'s type:",
558                 expectedTypes.get(i), b.getBlockType());
559             assertEquals("Invalid previous block offset for block " + i
560                 + " of " + "type " + b.getBlockType() + ":",
561                 (long) expectedPrevOffsets.get(i), b.getPrevBlockOffset());
562             b.sanityCheck();
563             assertEquals(curOffset, b.getOffset());
564 
565             // Now re-load this block knowing the on-disk size. This tests a
566             // different branch in the loader.
567             HFileBlock b2 = hbr.readBlockData(curOffset, b.getOnDiskSizeWithHeader(), pread);
568             b2.sanityCheck();
569 
570             assertEquals(b.getBlockType(), b2.getBlockType());
571             assertEquals(b.getOnDiskSizeWithoutHeader(),
572                 b2.getOnDiskSizeWithoutHeader());
573             assertEquals(b.getOnDiskSizeWithHeader(),
574                 b2.getOnDiskSizeWithHeader());
575             assertEquals(b.getUncompressedSizeWithoutHeader(),
576                 b2.getUncompressedSizeWithoutHeader());
577             assertEquals(b.getPrevBlockOffset(), b2.getPrevBlockOffset());
578             assertEquals(curOffset, b2.getOffset());
579             assertEquals(b.getBytesPerChecksum(), b2.getBytesPerChecksum());
580             assertEquals(b.getOnDiskDataSizeWithHeader(),
581                          b2.getOnDiskDataSizeWithHeader());
582             assertEquals(0, HFile.getChecksumFailuresCount());
583 
584             curOffset += b.getOnDiskSizeWithHeader();
585 
586             if (cacheOnWrite) {
587               // NOTE: cache-on-write testing doesn't actually involve a BlockCache. It simply
588               // verifies that the unpacked value read back off disk matches the unpacked value
589               // generated before writing to disk.
590               b = b.unpack(meta, hbr);
591               // b's buffer has header + data + checksum while
592               // expectedContents have header + data only
593               ByteBuffer bufRead = b.getBufferReadOnly();
594               ByteBuffer bufExpected = expectedContents.get(i);
595               boolean bytesAreCorrect = Bytes.compareTo(bufRead.array(),
596                   bufRead.arrayOffset(),
597                   bufRead.limit() - b.totalChecksumBytes(),
598                   bufExpected.array(), bufExpected.arrayOffset(),
599                   bufExpected.limit()) == 0;
600               String wrongBytesMsg = "";
601 
602               if (!bytesAreCorrect) {
603                 // Optimization: only construct an error message in case we
604                 // will need it.
605                 wrongBytesMsg = "Expected bytes in block #" + i + " (algo="
606                     + algo + ", pread=" + pread
607                     + ", cacheOnWrite=" + cacheOnWrite + "):\n";
608                 wrongBytesMsg += Bytes.toStringBinary(bufExpected.array(),
609                   bufExpected.arrayOffset(), Math.min(32 + 10, bufExpected.limit()))
610                     + ", actual:\n"
611                     + Bytes.toStringBinary(bufRead.array(),
612                   bufRead.arrayOffset(), Math.min(32 + 10, bufRead.limit()));
613                 if (detailedLogging) {
614                   LOG.warn("expected header" +
615                            HFileBlock.toStringHeader(bufExpected) +
616                            "\nfound    header" +
617                            HFileBlock.toStringHeader(bufRead));
618                   LOG.warn("bufread offset " + bufRead.arrayOffset() +
619                            " limit " + bufRead.limit() +
620                            " expected offset " + bufExpected.arrayOffset() +
621                            " limit " + bufExpected.limit());
622                   LOG.warn(wrongBytesMsg);
623                 }
624               }
625               assertTrue(wrongBytesMsg, bytesAreCorrect);
626             }
627           }
628 
629           assertEquals(curOffset, fs.getFileStatus(path).getLen());
630           is.close();
631         }
632       }
633     }
634   }
635 
636   private Random defaultRandom() {
637     return new Random(189237);
638   }
639 
640   private class BlockReaderThread implements Callable<Boolean> {
641     private final String clientId;
642     private final HFileBlock.FSReader hbr;
643     private final List<Long> offsets;
644     private final List<BlockType> types;
645     private final long fileSize;
646 
647     public BlockReaderThread(String clientId,
648         HFileBlock.FSReader hbr, List<Long> offsets, List<BlockType> types,
649         long fileSize) {
650       this.clientId = clientId;
651       this.offsets = offsets;
652       this.hbr = hbr;
653       this.types = types;
654       this.fileSize = fileSize;
655     }
656 
657     @Override
658     public Boolean call() throws Exception {
659       Random rand = new Random(clientId.hashCode());
660       long endTime = System.currentTimeMillis() + 10000;
661       int numBlocksRead = 0;
662       int numPositionalRead = 0;
663       int numWithOnDiskSize = 0;
664       while (System.currentTimeMillis() < endTime) {
665         int blockId = rand.nextInt(NUM_TEST_BLOCKS);
666         long offset = offsets.get(blockId);
667         boolean pread = rand.nextBoolean();
668         boolean withOnDiskSize = rand.nextBoolean();
669         long expectedSize =
670           (blockId == NUM_TEST_BLOCKS - 1 ? fileSize
671               : offsets.get(blockId + 1)) - offset;
672 
673         HFileBlock b;
674         try {
675           long onDiskSizeArg = withOnDiskSize ? expectedSize : -1;
676           b = hbr.readBlockData(offset, onDiskSizeArg, pread);
677         } catch (IOException ex) {
678           LOG.error("Error in client " + clientId + " trying to read block at "
679               + offset + ", pread=" + pread + ", withOnDiskSize=" +
680               withOnDiskSize, ex);
681           return false;
682         }
683 
684         assertEquals(types.get(blockId), b.getBlockType());
685         assertEquals(expectedSize, b.getOnDiskSizeWithHeader());
686         assertEquals(offset, b.getOffset());
687 
688         ++numBlocksRead;
689         if (pread)
690           ++numPositionalRead;
691         if (withOnDiskSize)
692           ++numWithOnDiskSize;
693       }
694       LOG.info("Client " + clientId + " successfully read " + numBlocksRead +
695         " blocks (with pread: " + numPositionalRead + ", with onDiskSize " +
696         "specified: " + numWithOnDiskSize + ")");
697 
698       return true;
699     }
700 
701   }
702 
703   @Test
704   public void testConcurrentReading() throws Exception {
705     testConcurrentReadingInternals();
706   }
707 
708   protected void testConcurrentReadingInternals() throws IOException,
709       InterruptedException, ExecutionException {
710     for (Compression.Algorithm compressAlgo : COMPRESSION_ALGORITHMS) {
711       Path path = new Path(TEST_UTIL.getDataTestDir(), "concurrent_reading");
712       Random rand = defaultRandom();
713       List<Long> offsets = new ArrayList<Long>();
714       List<BlockType> types = new ArrayList<BlockType>();
715       writeBlocks(rand, compressAlgo, path, offsets, null, types, null);
716       FSDataInputStream is = fs.open(path);
717       long fileSize = fs.getFileStatus(path).getLen();
718       HFileContext meta = new HFileContextBuilder()
719                           .withHBaseCheckSum(true)
720                           .withIncludesMvcc(includesMemstoreTS)
721                           .withIncludesTags(includesTag)
722                           .withCompression(compressAlgo)
723                           .build();
724       HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, fileSize, meta);
725 
726       Executor exec = Executors.newFixedThreadPool(NUM_READER_THREADS);
727       ExecutorCompletionService<Boolean> ecs =
728           new ExecutorCompletionService<Boolean>(exec);
729 
730       for (int i = 0; i < NUM_READER_THREADS; ++i) {
731         ecs.submit(new BlockReaderThread("reader_" + (char) ('A' + i), hbr,
732             offsets, types, fileSize));
733       }
734 
735       for (int i = 0; i < NUM_READER_THREADS; ++i) {
736         Future<Boolean> result = ecs.take();
737         assertTrue(result.get());
738         if (detailedLogging) {
739           LOG.info(String.valueOf(i + 1)
740             + " reader threads finished successfully (algo=" + compressAlgo
741             + ")");
742         }
743       }
744 
745       is.close();
746     }
747   }
748 
749   private long writeBlocks(Random rand, Compression.Algorithm compressAlgo,
750       Path path, List<Long> expectedOffsets, List<Long> expectedPrevOffsets,
751       List<BlockType> expectedTypes, List<ByteBuffer> expectedContents
752   ) throws IOException {
753     boolean cacheOnWrite = expectedContents != null;
754     FSDataOutputStream os = fs.create(path);
755     HFileContext meta = new HFileContextBuilder()
756                         .withHBaseCheckSum(true)
757                         .withIncludesMvcc(includesMemstoreTS)
758                         .withIncludesTags(includesTag)
759                         .withCompression(compressAlgo)
760                         .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
761                         .build();
762     HFileBlock.Writer hbw = new HFileBlock.Writer(null, meta);
763     Map<BlockType, Long> prevOffsetByType = new HashMap<BlockType, Long>();
764     long totalSize = 0;
765     for (int i = 0; i < NUM_TEST_BLOCKS; ++i) {
766       long pos = os.getPos();
767       int blockTypeOrdinal = rand.nextInt(BlockType.values().length);
768       if (blockTypeOrdinal == BlockType.ENCODED_DATA.ordinal()) {
769         blockTypeOrdinal = BlockType.DATA.ordinal();
770       }
771       BlockType bt = BlockType.values()[blockTypeOrdinal];
772       DataOutputStream dos = hbw.startWriting(bt);
773       int size = rand.nextInt(500);
774       for (int j = 0; j < size; ++j) {
775         // This might compress well.
776         dos.writeShort(i + 1);
777         dos.writeInt(j + 1);
778       }
779 
780       if (expectedOffsets != null)
781         expectedOffsets.add(os.getPos());
782 
783       if (expectedPrevOffsets != null) {
784         Long prevOffset = prevOffsetByType.get(bt);
785         expectedPrevOffsets.add(prevOffset != null ? prevOffset : -1);
786         prevOffsetByType.put(bt, os.getPos());
787       }
788 
789       expectedTypes.add(bt);
790 
791       hbw.writeHeaderAndData(os);
792       totalSize += hbw.getOnDiskSizeWithHeader();
793 
794       if (cacheOnWrite)
795         expectedContents.add(hbw.getUncompressedBufferWithHeader());
796 
797       if (detailedLogging) {
798         LOG.info("Written block #" + i + " of type " + bt
799             + ", uncompressed size " + hbw.getUncompressedSizeWithoutHeader()
800             + ", packed size " + hbw.getOnDiskSizeWithoutHeader()
801             + " at offset " + pos);
802       }
803     }
804     os.close();
805     LOG.info("Created a temporary file at " + path + ", "
806         + fs.getFileStatus(path).getLen() + " byte, compression=" +
807         compressAlgo);
808     return totalSize;
809   }
810 
811   @Test
812   public void testBlockHeapSize() {
813     testBlockHeapSizeInternals();
814   }
815 
816   protected void testBlockHeapSizeInternals() {
817     if (ClassSize.is32BitJVM()) {
818       assertTrue(HFileBlock.BYTE_BUFFER_HEAP_SIZE == 64);
819     } else {
820       assertTrue(HFileBlock.BYTE_BUFFER_HEAP_SIZE == 80);
821     }
822 
823     for (int size : new int[] { 100, 256, 12345 }) {
824       byte[] byteArr = new byte[HConstants.HFILEBLOCK_HEADER_SIZE + size];
825       ByteBuffer buf = ByteBuffer.wrap(byteArr, 0, size);
826       HFileContext meta = new HFileContextBuilder()
827                           .withIncludesMvcc(includesMemstoreTS)
828                           .withIncludesTags(includesTag)
829                           .withHBaseCheckSum(false)
830                           .withCompression(Algorithm.NONE)
831                           .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM)
832                           .withChecksumType(ChecksumType.NULL).build();
833       HFileBlock block = new HFileBlock(BlockType.DATA, size, size, -1, buf,
834           HFileBlock.FILL_HEADER, -1, 0, -1, meta);
835       long byteBufferExpectedSize =
836           ClassSize.align(ClassSize.estimateBase(buf.getClass(), true)
837               + HConstants.HFILEBLOCK_HEADER_SIZE + size);
838       long hfileMetaSize =  ClassSize.align(ClassSize.estimateBase(HFileContext.class, true));
839       long hfileBlockExpectedSize =
840           ClassSize.align(ClassSize.estimateBase(HFileBlock.class, true));
841       long expected = hfileBlockExpectedSize + byteBufferExpectedSize + hfileMetaSize;
842       assertEquals("Block data size: " + size + ", byte buffer expected " +
843           "size: " + byteBufferExpectedSize + ", HFileBlock class expected " +
844           "size: " + hfileBlockExpectedSize + ";", expected,
845           block.heapSize());
846     }
847   }
848 }