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