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  
20  package org.apache.hadoop.hbase.io.hfile;
21  
22  import static org.junit.Assert.assertEquals;
23  import static org.junit.Assert.assertFalse;
24  import static org.junit.Assert.assertNotEquals;
25  import static org.junit.Assert.assertTrue;
26  
27  import java.io.IOException;
28  import java.util.ArrayList;
29  import java.util.Collection;
30  import java.util.EnumMap;
31  import java.util.List;
32  import java.util.Random;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.fs.FileSystem;
38  import org.apache.hadoop.fs.Path;
39  import org.apache.hadoop.hbase.HBaseTestingUtility;
40  import org.apache.hadoop.hbase.HColumnDescriptor;
41  import org.apache.hadoop.hbase.HConstants;
42  import org.apache.hadoop.hbase.KeyValue;
43  import org.apache.hadoop.hbase.testclassification.MediumTests;
44  import org.apache.hadoop.hbase.Tag;
45  import org.apache.hadoop.hbase.client.Durability;
46  import org.apache.hadoop.hbase.client.Put;
47  import org.apache.hadoop.hbase.fs.HFileSystem;
48  import org.apache.hadoop.hbase.io.compress.Compression;
49  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
50  import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache;
51  import org.apache.hadoop.hbase.regionserver.BloomType;
52  import org.apache.hadoop.hbase.regionserver.HRegion;
53  import org.apache.hadoop.hbase.regionserver.StoreFile;
54  import org.apache.hadoop.hbase.util.BloomFilterFactory;
55  import org.apache.hadoop.hbase.util.Bytes;
56  import org.apache.hadoop.hbase.util.ChecksumType;
57  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
58  import org.junit.After;
59  import org.junit.AfterClass;
60  import org.junit.Before;
61  import org.junit.Test;
62  import org.junit.experimental.categories.Category;
63  import org.junit.runner.RunWith;
64  import org.junit.runners.Parameterized;
65  import org.junit.runners.Parameterized.Parameters;
66  
67  import com.google.common.collect.Lists;
68  
69  /**
70   * Tests {@link HFile} cache-on-write functionality for the following block
71   * types: data blocks, non-root index blocks, and Bloom filter blocks.
72   */
73  @RunWith(Parameterized.class)
74  @Category(MediumTests.class)
75  public class TestCacheOnWrite {
76  
77    private static final Log LOG = LogFactory.getLog(TestCacheOnWrite.class);
78  
79    private static final HBaseTestingUtility TEST_UTIL = HBaseTestingUtility.createLocalHTU();
80    private Configuration conf;
81    private CacheConfig cacheConf;
82    private FileSystem fs;
83    private Random rand = new Random(12983177L);
84    private Path storeFilePath;
85    private BlockCache blockCache;
86    private String testDescription;
87  
88    private final CacheOnWriteType cowType;
89    private final Compression.Algorithm compress;
90    private final BlockEncoderTestType encoderType;
91    private final HFileDataBlockEncoder encoder;
92    private final boolean cacheCompressedData;
93  
94    private static final int DATA_BLOCK_SIZE = 2048;
95    private static final int NUM_KV = 25000;
96    private static final int INDEX_BLOCK_SIZE = 512;
97    private static final int BLOOM_BLOCK_SIZE = 4096;
98    private static final BloomType BLOOM_TYPE = BloomType.ROWCOL;
99    private static final int CKBYTES = 512;
100 
101   /** The number of valid key types possible in a store file */
102   private static final int NUM_VALID_KEY_TYPES =
103       KeyValue.Type.values().length - 2;
104 
105   private static enum CacheOnWriteType {
106     DATA_BLOCKS(CacheConfig.CACHE_BLOCKS_ON_WRITE_KEY,
107         BlockType.DATA, BlockType.ENCODED_DATA),
108     BLOOM_BLOCKS(CacheConfig.CACHE_BLOOM_BLOCKS_ON_WRITE_KEY,
109         BlockType.BLOOM_CHUNK),
110     INDEX_BLOCKS(CacheConfig.CACHE_INDEX_BLOCKS_ON_WRITE_KEY,
111         BlockType.LEAF_INDEX, BlockType.INTERMEDIATE_INDEX);
112 
113     private final String confKey;
114     private final BlockType blockType1;
115     private final BlockType blockType2;
116 
117     private CacheOnWriteType(String confKey, BlockType blockType) {
118       this(confKey, blockType, blockType);
119     }
120 
121     private CacheOnWriteType(String confKey, BlockType blockType1,
122         BlockType blockType2) {
123       this.blockType1 = blockType1;
124       this.blockType2 = blockType2;
125       this.confKey = confKey;
126     }
127 
128     public boolean shouldBeCached(BlockType blockType) {
129       return blockType == blockType1 || blockType == blockType2;
130     }
131 
132     public void modifyConf(Configuration conf) {
133       for (CacheOnWriteType cowType : CacheOnWriteType.values()) {
134         conf.setBoolean(cowType.confKey, cowType == this);
135       }
136     }
137 
138   }
139 
140   private static final DataBlockEncoding ENCODING_ALGO =
141       DataBlockEncoding.PREFIX;
142 
143   /** Provides fancy names for three combinations of two booleans */
144   private static enum BlockEncoderTestType {
145     NO_BLOCK_ENCODING_NOOP(true, false),
146     NO_BLOCK_ENCODING(false, false),
147     BLOCK_ENCODING_EVERYWHERE(false, true);
148 
149     private final boolean noop;
150     private final boolean encode;
151 
152     BlockEncoderTestType(boolean noop, boolean encode) {
153       this.encode = encode;
154       this.noop = noop;
155     }
156 
157     public HFileDataBlockEncoder getEncoder() {
158       return noop ? NoOpDataBlockEncoder.INSTANCE : new HFileDataBlockEncoderImpl(
159         encode ? ENCODING_ALGO : DataBlockEncoding.NONE);
160     }
161   }
162 
163   public TestCacheOnWrite(CacheOnWriteType cowType, Compression.Algorithm compress,
164       BlockEncoderTestType encoderType, boolean cacheCompressedData, BlockCache blockCache) {
165     this.cowType = cowType;
166     this.compress = compress;
167     this.encoderType = encoderType;
168     this.encoder = encoderType.getEncoder();
169     this.cacheCompressedData = cacheCompressedData;
170     this.blockCache = blockCache;
171     testDescription = "[cacheOnWrite=" + cowType + ", compress=" + compress +
172         ", encoderType=" + encoderType + ", cacheCompressedData=" + cacheCompressedData + "]";
173     LOG.info(testDescription);
174   }
175 
176   private static List<BlockCache> getBlockCaches() throws IOException {
177     Configuration conf = TEST_UTIL.getConfiguration();
178     List<BlockCache> blockcaches = new ArrayList<BlockCache>();
179     // default
180     blockcaches.add(new CacheConfig(conf).getBlockCache());
181 
182     // memory
183     BlockCache lru = new LruBlockCache(128 * 1024 * 1024, 64 * 1024, TEST_UTIL.getConfiguration());
184     blockcaches.add(lru);
185 
186     // bucket cache
187     FileSystem.get(conf).mkdirs(TEST_UTIL.getDataTestDir());
188     int[] bucketSizes =
189         { INDEX_BLOCK_SIZE, DATA_BLOCK_SIZE, BLOOM_BLOCK_SIZE, 64 * 1024, 128 * 1024 };
190     BlockCache bucketcache =
191         new BucketCache("offheap", 128 * 1024 * 1024, 64 * 1024, bucketSizes, 5, 64 * 100, null);
192     blockcaches.add(bucketcache);
193     return blockcaches;
194   }
195 
196   @Parameters
197   public static Collection<Object[]> getParameters() throws IOException {
198     List<Object[]> cowTypes = new ArrayList<Object[]>();
199     for (BlockCache blockache : getBlockCaches()) {
200       for (CacheOnWriteType cowType : CacheOnWriteType.values()) {
201         for (Compression.Algorithm compress : HBaseTestingUtility.COMPRESSION_ALGORITHMS) {
202           for (BlockEncoderTestType encoderType : BlockEncoderTestType.values()) {
203             for (boolean cacheCompressedData : new boolean[] { false, true }) {
204               cowTypes.add(new Object[] { cowType, compress, encoderType, cacheCompressedData,
205                   blockache });
206             }
207           }
208         }
209       }
210     }
211     return cowTypes;
212   }
213 
214   private void clearBlockCache(BlockCache blockCache) throws InterruptedException {
215     if (blockCache instanceof LruBlockCache) {
216       ((LruBlockCache) blockCache).clearCache();
217     } else {
218       // BucketCache may not return all cached blocks(blocks in write queue), so check it here.
219       for (int clearCount = 0; blockCache.getBlockCount() > 0; clearCount++) {
220         if (clearCount > 0) {
221           LOG.warn("clear block cache " + blockCache + " " + clearCount + " times, "
222               + blockCache.getBlockCount() + " blocks remaining");
223           Thread.sleep(10);
224         }
225         for (CachedBlock block : Lists.newArrayList(blockCache)) {
226           BlockCacheKey key = new BlockCacheKey(block.getFilename(), block.getOffset());
227           // CombinedBucketCache may need evict two times.
228           for (int evictCount = 0; blockCache.evictBlock(key); evictCount++) {
229             if (evictCount > 1) {
230               LOG.warn("evict block " + block + " in " + blockCache + " " + evictCount
231                   + " times, maybe a bug here");
232             }
233           }
234         }
235       }
236     }
237   }
238 
239   @Before
240   public void setUp() throws IOException {
241     conf = TEST_UTIL.getConfiguration();
242     this.conf.set("dfs.datanode.data.dir.perm", "700");
243     conf.setInt(HFile.FORMAT_VERSION_KEY, HFile.MAX_FORMAT_VERSION);
244     conf.setInt(HFileBlockIndex.MAX_CHUNK_SIZE_KEY, INDEX_BLOCK_SIZE);
245     conf.setInt(BloomFilterFactory.IO_STOREFILE_BLOOM_BLOCK_SIZE,
246         BLOOM_BLOCK_SIZE);
247     conf.setBoolean(CacheConfig.CACHE_DATA_BLOCKS_COMPRESSED_KEY, cacheCompressedData);
248     cowType.modifyConf(conf);
249     fs = HFileSystem.get(conf);
250     CacheConfig.GLOBAL_BLOCK_CACHE_INSTANCE = blockCache;
251     cacheConf =
252         new CacheConfig(blockCache, true, true, cowType.shouldBeCached(BlockType.DATA),
253         cowType.shouldBeCached(BlockType.LEAF_INDEX),
254         cowType.shouldBeCached(BlockType.BLOOM_CHUNK), false, cacheCompressedData, false, false);
255   }
256 
257   @After
258   public void tearDown() throws IOException, InterruptedException {
259     clearBlockCache(blockCache);
260   }
261 
262   @AfterClass
263   public static void afterClass() throws IOException {
264     TEST_UTIL.cleanupTestDir();
265   }
266 
267   private void testStoreFileCacheOnWriteInternals(boolean useTags) throws IOException {
268     writeStoreFile(useTags);
269     readStoreFile(useTags);
270   }
271 
272   private void readStoreFile(boolean useTags) throws IOException {
273     AbstractHFileReader reader;
274     if (useTags) {
275         reader = (HFileReaderV3) HFile.createReader(fs, storeFilePath, cacheConf, conf);
276     } else {
277         reader = (HFileReaderV2) HFile.createReader(fs, storeFilePath, cacheConf, conf);
278     }
279     LOG.info("HFile information: " + reader);
280     HFileContext meta = new HFileContextBuilder().withCompression(compress)
281       .withBytesPerCheckSum(CKBYTES).withChecksumType(ChecksumType.NULL)
282       .withBlockSize(DATA_BLOCK_SIZE).withDataBlockEncoding(encoder.getDataBlockEncoding())
283       .withIncludesTags(useTags).build();
284     final boolean cacheBlocks = false;
285     final boolean pread = false;
286     HFileScanner scanner = reader.getScanner(cacheBlocks, pread);
287     assertTrue(testDescription, scanner.seekTo());
288 
289     long offset = 0;
290     HFileBlock prevBlock = null;
291     EnumMap<BlockType, Integer> blockCountByType =
292         new EnumMap<BlockType, Integer>(BlockType.class);
293 
294     DataBlockEncoding encodingInCache =
295         encoderType.getEncoder().getDataBlockEncoding();
296     while (offset < reader.getTrailer().getLoadOnOpenDataOffset()) {
297       long onDiskSize = -1;
298       if (prevBlock != null) {
299          onDiskSize = prevBlock.getNextBlockOnDiskSizeWithHeader();
300       }
301       // Flags: don't cache the block, use pread, this is not a compaction.
302       // Also, pass null for expected block type to avoid checking it.
303       HFileBlock block = reader.readBlock(offset, onDiskSize, false, true,
304         false, true, null, encodingInCache);
305       BlockCacheKey blockCacheKey = new BlockCacheKey(reader.getName(),
306           offset);
307       HFileBlock fromCache = (HFileBlock) blockCache.getBlock(blockCacheKey, true, false, true);
308       boolean isCached = fromCache != null;
309       boolean shouldBeCached = cowType.shouldBeCached(block.getBlockType());
310       assertTrue("shouldBeCached: " + shouldBeCached+ "\n" +
311           "isCached: " + isCached + "\n" +
312           "Test description: " + testDescription + "\n" +
313           "block: " + block + "\n" +
314           "encodingInCache: " + encodingInCache + "\n" +
315           "blockCacheKey: " + blockCacheKey,
316         shouldBeCached == isCached);
317       if (isCached) {
318         if (cacheConf.shouldCacheCompressed(fromCache.getBlockType().getCategory())) {
319           if (compress != Compression.Algorithm.NONE) {
320             assertFalse(fromCache.isUnpacked());
321           }
322           fromCache = fromCache.unpack(meta, reader.getUncachedBlockReader());
323         } else {
324           assertTrue(fromCache.isUnpacked());
325         }
326         // block we cached at write-time and block read from file should be identical
327         assertEquals(block.getChecksumType(), fromCache.getChecksumType());
328         assertEquals(block.getBlockType(), fromCache.getBlockType());
329         if (block.getBlockType() == BlockType.ENCODED_DATA) {
330           assertEquals(block.getDataBlockEncodingId(), fromCache.getDataBlockEncodingId());
331           assertEquals(block.getDataBlockEncoding(), fromCache.getDataBlockEncoding());
332         }
333         assertEquals(block.getOnDiskSizeWithHeader(), fromCache.getOnDiskSizeWithHeader());
334         assertEquals(block.getOnDiskSizeWithoutHeader(), fromCache.getOnDiskSizeWithoutHeader());
335         assertEquals(
336           block.getUncompressedSizeWithoutHeader(), fromCache.getUncompressedSizeWithoutHeader());
337       }
338       prevBlock = block;
339       offset += block.getOnDiskSizeWithHeader();
340       BlockType bt = block.getBlockType();
341       Integer count = blockCountByType.get(bt);
342       blockCountByType.put(bt, (count == null ? 0 : count) + 1);
343     }
344 
345     LOG.info("Block count by type: " + blockCountByType);
346     String countByType = blockCountByType.toString();
347     BlockType cachedDataBlockType =
348         encoderType.encode ? BlockType.ENCODED_DATA : BlockType.DATA;
349     if (useTags) {
350       assertEquals("{" + cachedDataBlockType
351           + "=2663, LEAF_INDEX=297, BLOOM_CHUNK=9, INTERMEDIATE_INDEX=34}", countByType);
352     } else {
353       assertEquals("{" + cachedDataBlockType
354           + "=2498, LEAF_INDEX=278, BLOOM_CHUNK=9, INTERMEDIATE_INDEX=31}", countByType);
355     }
356 
357     // iterate all the keyvalue from hfile
358     while (scanner.next()) {
359       scanner.getKeyValue();
360     }
361     reader.close();
362   }
363 
364   public static KeyValue.Type generateKeyType(Random rand) {
365     if (rand.nextBoolean()) {
366       // Let's make half of KVs puts.
367       return KeyValue.Type.Put;
368     } else {
369       KeyValue.Type keyType = KeyValue.Type.values()[1 + rand.nextInt(NUM_VALID_KEY_TYPES)];
370       if (keyType == KeyValue.Type.Minimum || keyType == KeyValue.Type.Maximum) {
371         throw new RuntimeException("Generated an invalid key type: " + keyType + ". "
372             + "Probably the layout of KeyValue.Type has changed.");
373       }
374       return keyType;
375     }
376   }
377 
378   private void writeStoreFile(boolean useTags) throws IOException {
379     if(useTags) {
380       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
381     } else {
382       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 2);
383     }
384     Path storeFileParentDir = new Path(TEST_UTIL.getDataTestDir(),
385         "test_cache_on_write");
386     HFileContext meta = new HFileContextBuilder().withCompression(compress)
387         .withBytesPerCheckSum(CKBYTES).withChecksumType(ChecksumType.NULL)
388         .withBlockSize(DATA_BLOCK_SIZE).withDataBlockEncoding(encoder.getDataBlockEncoding())
389         .withIncludesTags(useTags).build();
390     StoreFile.Writer sfw = new StoreFile.WriterBuilder(conf, cacheConf, fs)
391         .withOutputDir(storeFileParentDir).withComparator(KeyValue.COMPARATOR)
392         .withFileContext(meta)
393         .withBloomType(BLOOM_TYPE).withMaxKeyCount(NUM_KV).build();
394     byte[] cf = Bytes.toBytes("fam");
395     for (int i = 0; i < NUM_KV; ++i) {
396       byte[] row = TestHFileWriterV2.randomOrderedKey(rand, i);
397       byte[] qualifier = TestHFileWriterV2.randomRowOrQualifier(rand);
398       byte[] value = TestHFileWriterV2.randomValue(rand);
399       KeyValue kv;
400       if(useTags) {
401         Tag t = new Tag((byte) 1, "visibility");
402         List<Tag> tagList = new ArrayList<Tag>();
403         tagList.add(t);
404         Tag[] tags = new Tag[1];
405         tags[0] = t;
406         kv =
407             new KeyValue(row, 0, row.length, cf, 0, cf.length, qualifier, 0, qualifier.length,
408                 rand.nextLong(), generateKeyType(rand), value, 0, value.length, tagList);
409       } else {
410         kv =
411             new KeyValue(row, 0, row.length, cf, 0, cf.length, qualifier, 0, qualifier.length,
412                 rand.nextLong(), generateKeyType(rand), value, 0, value.length);
413       }
414       sfw.append(kv);
415     }
416 
417     sfw.close();
418     storeFilePath = sfw.getPath();
419   }
420 
421   private void testNotCachingDataBlocksDuringCompactionInternals(boolean useTags)
422       throws IOException, InterruptedException {
423     if (useTags) {
424       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
425     } else {
426       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 2);
427     }
428     // TODO: need to change this test if we add a cache size threshold for
429     // compactions, or if we implement some other kind of intelligent logic for
430     // deciding what blocks to cache-on-write on compaction.
431     final String table = "CompactionCacheOnWrite";
432     final String cf = "myCF";
433     final byte[] cfBytes = Bytes.toBytes(cf);
434     final int maxVersions = 3;
435     HRegion region = TEST_UTIL.createTestRegion(table, 
436         new HColumnDescriptor(cf)
437             .setCompressionType(compress)
438             .setBloomFilterType(BLOOM_TYPE)
439             .setMaxVersions(maxVersions)
440             .setDataBlockEncoding(encoder.getDataBlockEncoding())
441     );
442     int rowIdx = 0;
443     long ts = EnvironmentEdgeManager.currentTime();
444     for (int iFile = 0; iFile < 5; ++iFile) {
445       for (int iRow = 0; iRow < 500; ++iRow) {
446         String rowStr = "" + (rowIdx * rowIdx * rowIdx) + "row" + iFile + "_" + 
447             iRow;
448         Put p = new Put(Bytes.toBytes(rowStr));
449         ++rowIdx;
450         for (int iCol = 0; iCol < 10; ++iCol) {
451           String qualStr = "col" + iCol;
452           String valueStr = "value_" + rowStr + "_" + qualStr;
453           for (int iTS = 0; iTS < 5; ++iTS) {
454             if (useTags) {
455               Tag t = new Tag((byte) 1, "visibility");
456               Tag[] tags = new Tag[1];
457               tags[0] = t;
458               KeyValue kv = new KeyValue(Bytes.toBytes(rowStr), cfBytes, Bytes.toBytes(qualStr),
459                   HConstants.LATEST_TIMESTAMP, Bytes.toBytes(valueStr), tags);
460               p.add(kv);
461             } else {
462               p.addColumn(cfBytes, Bytes.toBytes(qualStr), ts++, Bytes.toBytes(valueStr));
463             }
464           }
465         }
466         p.setDurability(Durability.ASYNC_WAL);
467         region.put(p);
468       }
469       region.flushcache();
470     }
471     clearBlockCache(blockCache);
472     assertEquals(0, blockCache.getBlockCount());
473     region.compactStores();
474     LOG.debug("compactStores() returned");
475 
476     for (CachedBlock block: blockCache) {
477       assertNotEquals(BlockType.ENCODED_DATA, block.getBlockType());
478       assertNotEquals(BlockType.DATA, block.getBlockType());
479     }
480     region.close();
481   }
482 
483   @Test
484   public void testStoreFileCacheOnWrite() throws IOException {
485     testStoreFileCacheOnWriteInternals(false);
486     testStoreFileCacheOnWriteInternals(true);
487   }
488 
489   @Test
490   public void testNotCachingDataBlocksDuringCompaction() throws IOException, InterruptedException {
491     testNotCachingDataBlocksDuringCompactionInternals(false);
492     testNotCachingDataBlocksDuringCompactionInternals(true);
493   }
494 }