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     EnumMap<BlockType, Integer> blockCountByType =
265         new EnumMap<BlockType, Integer>(BlockType.class);
266 
267     DataBlockEncoding encodingInCache = NoOpDataBlockEncoder.INSTANCE.getDataBlockEncoding();
268     while (offset < reader.getTrailer().getLoadOnOpenDataOffset()) {
269       // Flags: don't cache the block, use pread, this is not a compaction.
270       // Also, pass null for expected block type to avoid checking it.
271       HFileBlock block = reader.readBlock(offset, -1, false, true, false, true, null,
272           encodingInCache);
273       BlockCacheKey blockCacheKey = new BlockCacheKey(reader.getName(),
274           offset);
275       HFileBlock fromCache = (HFileBlock) blockCache.getBlock(blockCacheKey, true, false, true);
276       boolean isCached = fromCache != null;
277       boolean shouldBeCached = cowType.shouldBeCached(block.getBlockType());
278       assertTrue("shouldBeCached: " + shouldBeCached+ "\n" +
279           "isCached: " + isCached + "\n" +
280           "Test description: " + testDescription + "\n" +
281           "block: " + block + "\n" +
282           "encodingInCache: " + encodingInCache + "\n" +
283           "blockCacheKey: " + blockCacheKey,
284         shouldBeCached == isCached);
285       if (isCached) {
286         if (cacheConf.shouldCacheCompressed(fromCache.getBlockType().getCategory())) {
287           if (compress != Compression.Algorithm.NONE) {
288             assertFalse(fromCache.isUnpacked());
289           }
290           fromCache = fromCache.unpack(meta, reader.getUncachedBlockReader());
291         } else {
292           assertTrue(fromCache.isUnpacked());
293         }
294         // block we cached at write-time and block read from file should be identical
295         assertEquals(block.getChecksumType(), fromCache.getChecksumType());
296         assertEquals(block.getBlockType(), fromCache.getBlockType());
297         assertNotEquals(block.getBlockType(), BlockType.ENCODED_DATA);
298         assertEquals(block.getOnDiskSizeWithHeader(), fromCache.getOnDiskSizeWithHeader());
299         assertEquals(block.getOnDiskSizeWithoutHeader(), fromCache.getOnDiskSizeWithoutHeader());
300         assertEquals(
301           block.getUncompressedSizeWithoutHeader(), fromCache.getUncompressedSizeWithoutHeader());
302       }
303       offset += block.getOnDiskSizeWithHeader();
304       BlockType bt = block.getBlockType();
305       Integer count = blockCountByType.get(bt);
306       blockCountByType.put(bt, (count == null ? 0 : count) + 1);
307     }
308 
309     LOG.info("Block count by type: " + blockCountByType);
310     String countByType = blockCountByType.toString();
311     if (useTags) {
312       assertEquals("{" + BlockType.DATA
313           + "=2663, LEAF_INDEX=297, BLOOM_CHUNK=9, INTERMEDIATE_INDEX=32}", countByType);
314     } else {
315       assertEquals("{" + BlockType.DATA
316           + "=2498, LEAF_INDEX=278, BLOOM_CHUNK=9, INTERMEDIATE_INDEX=31}", countByType);
317     }
318 
319     // iterate all the keyvalue from hfile
320     while (scanner.next()) {
321       scanner.getKeyValue();
322     }
323     reader.close();
324   }
325 
326   public static KeyValue.Type generateKeyType(Random rand) {
327     if (rand.nextBoolean()) {
328       // Let's make half of KVs puts.
329       return KeyValue.Type.Put;
330     } else {
331       KeyValue.Type keyType = KeyValue.Type.values()[1 + rand.nextInt(NUM_VALID_KEY_TYPES)];
332       if (keyType == KeyValue.Type.Minimum || keyType == KeyValue.Type.Maximum) {
333         throw new RuntimeException("Generated an invalid key type: " + keyType + ". "
334             + "Probably the layout of KeyValue.Type has changed.");
335       }
336       return keyType;
337     }
338   }
339 
340   private void writeStoreFile(boolean useTags) throws IOException {
341     if(useTags) {
342       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
343     } else {
344       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 2);
345     }
346     Path storeFileParentDir = new Path(TEST_UTIL.getDataTestDir(),
347         "test_cache_on_write");
348     HFileContext meta = new HFileContextBuilder().withCompression(compress)
349         .withBytesPerCheckSum(CKBYTES).withChecksumType(ChecksumType.NULL)
350         .withBlockSize(DATA_BLOCK_SIZE)
351         .withDataBlockEncoding(NoOpDataBlockEncoder.INSTANCE.getDataBlockEncoding())
352         .withIncludesTags(useTags).build();
353     StoreFile.Writer sfw = new StoreFile.WriterBuilder(conf, cacheConf, fs)
354         .withOutputDir(storeFileParentDir).withComparator(KeyValue.COMPARATOR)
355         .withFileContext(meta)
356         .withBloomType(BLOOM_TYPE).withMaxKeyCount(NUM_KV).build();
357     byte[] cf = Bytes.toBytes("fam");
358     for (int i = 0; i < NUM_KV; ++i) {
359       byte[] row = TestHFileWriterV2.randomOrderedKey(rand, i);
360       byte[] qualifier = TestHFileWriterV2.randomRowOrQualifier(rand);
361       byte[] value = TestHFileWriterV2.randomValue(rand);
362       KeyValue kv;
363       if(useTags) {
364         Tag t = new Tag((byte) 1, "visibility");
365         List<Tag> tagList = new ArrayList<Tag>();
366         tagList.add(t);
367         Tag[] tags = new Tag[1];
368         tags[0] = t;
369         kv =
370             new KeyValue(row, 0, row.length, cf, 0, cf.length, qualifier, 0, qualifier.length,
371                 rand.nextLong(), generateKeyType(rand), value, 0, value.length, tagList);
372       } else {
373         kv =
374             new KeyValue(row, 0, row.length, cf, 0, cf.length, qualifier, 0, qualifier.length,
375                 rand.nextLong(), generateKeyType(rand), value, 0, value.length);
376       }
377       sfw.append(kv);
378     }
379 
380     sfw.close();
381     storeFilePath = sfw.getPath();
382   }
383 
384   private void testNotCachingDataBlocksDuringCompactionInternals(boolean useTags)
385       throws IOException, InterruptedException {
386     if (useTags) {
387       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
388     } else {
389       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 2);
390     }
391     // TODO: need to change this test if we add a cache size threshold for
392     // compactions, or if we implement some other kind of intelligent logic for
393     // deciding what blocks to cache-on-write on compaction.
394     final String table = "CompactionCacheOnWrite";
395     final String cf = "myCF";
396     final byte[] cfBytes = Bytes.toBytes(cf);
397     final int maxVersions = 3;
398     Region region = TEST_UTIL.createTestRegion(table,
399         new HColumnDescriptor(cf)
400             .setCompressionType(compress)
401             .setBloomFilterType(BLOOM_TYPE)
402             .setMaxVersions(maxVersions)
403             .setDataBlockEncoding(NoOpDataBlockEncoder.INSTANCE.getDataBlockEncoding())
404     );
405     int rowIdx = 0;
406     long ts = EnvironmentEdgeManager.currentTime();
407     for (int iFile = 0; iFile < 5; ++iFile) {
408       for (int iRow = 0; iRow < 500; ++iRow) {
409         String rowStr = "" + (rowIdx * rowIdx * rowIdx) + "row" + iFile + "_" +
410             iRow;
411         Put p = new Put(Bytes.toBytes(rowStr));
412         ++rowIdx;
413         for (int iCol = 0; iCol < 10; ++iCol) {
414           String qualStr = "col" + iCol;
415           String valueStr = "value_" + rowStr + "_" + qualStr;
416           for (int iTS = 0; iTS < 5; ++iTS) {
417             if (useTags) {
418               Tag t = new Tag((byte) 1, "visibility");
419               Tag[] tags = new Tag[1];
420               tags[0] = t;
421               KeyValue kv = new KeyValue(Bytes.toBytes(rowStr), cfBytes, Bytes.toBytes(qualStr),
422                   HConstants.LATEST_TIMESTAMP, Bytes.toBytes(valueStr), tags);
423               p.add(kv);
424             } else {
425               p.addColumn(cfBytes, Bytes.toBytes(qualStr), ts++, Bytes.toBytes(valueStr));
426             }
427           }
428         }
429         p.setDurability(Durability.ASYNC_WAL);
430         region.put(p);
431       }
432       region.flush(true);
433     }
434     clearBlockCache(blockCache);
435     assertEquals(0, blockCache.getBlockCount());
436     region.compact(false);
437     LOG.debug("compactStores() returned");
438 
439     for (CachedBlock block: blockCache) {
440       assertNotEquals(BlockType.ENCODED_DATA, block.getBlockType());
441       assertNotEquals(BlockType.DATA, block.getBlockType());
442     }
443     ((HRegion)region).close();
444   }
445 
446   @Test
447   public void testStoreFileCacheOnWrite() throws IOException {
448     testStoreFileCacheOnWriteInternals(false);
449     testStoreFileCacheOnWriteInternals(true);
450   }
451 
452   @Test
453   public void testNotCachingDataBlocksDuringCompaction() throws IOException, InterruptedException {
454     testNotCachingDataBlocksDuringCompactionInternals(false);
455     testNotCachingDataBlocksDuringCompactionInternals(true);
456   }
457 }