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         ", blockCache=" + blockCache.getClass().getSimpleName() + "]";
174     LOG.info(testDescription);
175   }
176 
177   private static List<BlockCache> getBlockCaches() throws IOException {
178     Configuration conf = TEST_UTIL.getConfiguration();
179     List<BlockCache> blockcaches = new ArrayList<BlockCache>();
180     // default
181     blockcaches.add(new CacheConfig(conf).getBlockCache());
182 
183     // memory
184     BlockCache lru = new LruBlockCache(128 * 1024 * 1024, 64 * 1024, TEST_UTIL.getConfiguration());
185     blockcaches.add(lru);
186 
187     // bucket cache
188     FileSystem.get(conf).mkdirs(TEST_UTIL.getDataTestDir());
189     int[] bucketSizes =
190         { INDEX_BLOCK_SIZE, DATA_BLOCK_SIZE, BLOOM_BLOCK_SIZE, 64 * 1024, 128 * 1024 };
191     BlockCache bucketcache =
192         new BucketCache("offheap", 128 * 1024 * 1024, 64 * 1024, bucketSizes, 5, 64 * 100, null);
193     blockcaches.add(bucketcache);
194     return blockcaches;
195   }
196 
197   @Parameters
198   public static Collection<Object[]> getParameters() throws IOException {
199     List<Object[]> cowTypes = new ArrayList<Object[]>();
200     for (BlockCache blockache : getBlockCaches()) {
201       for (CacheOnWriteType cowType : CacheOnWriteType.values()) {
202         for (Compression.Algorithm compress : HBaseTestingUtility.COMPRESSION_ALGORITHMS) {
203           for (BlockEncoderTestType encoderType : BlockEncoderTestType.values()) {
204             for (boolean cacheCompressedData : new boolean[] { false, true }) {
205               cowTypes.add(new Object[] { cowType, compress, encoderType, cacheCompressedData,
206                   blockache });
207             }
208           }
209         }
210       }
211     }
212     return cowTypes;
213   }
214 
215   private void clearBlockCache(BlockCache blockCache) throws InterruptedException {
216     if (blockCache instanceof LruBlockCache) {
217       ((LruBlockCache) blockCache).clearCache();
218     } else {
219       // BucketCache may not return all cached blocks(blocks in write queue), so check it here.
220       for (int clearCount = 0; blockCache.getBlockCount() > 0; clearCount++) {
221         if (clearCount > 0) {
222           LOG.warn("clear block cache " + blockCache + " " + clearCount + " times, "
223               + blockCache.getBlockCount() + " blocks remaining");
224           Thread.sleep(10);
225         }
226         for (CachedBlock block : Lists.newArrayList(blockCache)) {
227           blockCache.evictBlocksByHfileName(block.getFilename());
228         }
229       }
230     }
231   }
232 
233   @Before
234   public void setUp() throws IOException {
235     conf = TEST_UTIL.getConfiguration();
236     this.conf.set("dfs.datanode.data.dir.perm", "700");
237     conf.setInt(HFile.FORMAT_VERSION_KEY, HFile.MAX_FORMAT_VERSION);
238     conf.setInt(HFileBlockIndex.MAX_CHUNK_SIZE_KEY, INDEX_BLOCK_SIZE);
239     conf.setInt(BloomFilterFactory.IO_STOREFILE_BLOOM_BLOCK_SIZE,
240         BLOOM_BLOCK_SIZE);
241     conf.setBoolean(CacheConfig.CACHE_DATA_BLOCKS_COMPRESSED_KEY, cacheCompressedData);
242     cowType.modifyConf(conf);
243     fs = HFileSystem.get(conf);
244     CacheConfig.GLOBAL_BLOCK_CACHE_INSTANCE = blockCache;
245     cacheConf =
246         new CacheConfig(blockCache, true, true, cowType.shouldBeCached(BlockType.DATA),
247         cowType.shouldBeCached(BlockType.LEAF_INDEX),
248         cowType.shouldBeCached(BlockType.BLOOM_CHUNK), false, cacheCompressedData, false);
249   }
250 
251   @After
252   public void tearDown() throws IOException, InterruptedException {
253     clearBlockCache(blockCache);
254   }
255 
256   @AfterClass
257   public static void afterClass() throws IOException {
258     TEST_UTIL.cleanupTestDir();
259   }
260 
261   private void testStoreFileCacheOnWriteInternals(boolean useTags) throws IOException {
262     writeStoreFile(useTags);
263     readStoreFile(useTags);
264   }
265 
266   private void readStoreFile(boolean useTags) throws IOException {
267     AbstractHFileReader reader;
268     if (useTags) {
269         reader = (HFileReaderV3) HFile.createReader(fs, storeFilePath, cacheConf, conf);
270     } else {
271         reader = (HFileReaderV2) HFile.createReader(fs, storeFilePath, cacheConf, conf);
272     }
273     LOG.info("HFile information: " + reader);
274     HFileContext meta = new HFileContextBuilder().withCompression(compress)
275       .withBytesPerCheckSum(CKBYTES).withChecksumType(ChecksumType.NULL)
276       .withBlockSize(DATA_BLOCK_SIZE).withDataBlockEncoding(encoder.getDataBlockEncoding())
277       .withIncludesTags(useTags).build();
278     final boolean cacheBlocks = false;
279     final boolean pread = false;
280     HFileScanner scanner = reader.getScanner(cacheBlocks, pread);
281     assertTrue(testDescription, scanner.seekTo());
282 
283     long offset = 0;
284     HFileBlock prevBlock = null;
285     EnumMap<BlockType, Integer> blockCountByType =
286         new EnumMap<BlockType, Integer>(BlockType.class);
287 
288     DataBlockEncoding encodingInCache =
289         encoderType.getEncoder().getDataBlockEncoding();
290     while (offset < reader.getTrailer().getLoadOnOpenDataOffset()) {
291       long onDiskSize = -1;
292       if (prevBlock != null) {
293          onDiskSize = prevBlock.getNextBlockOnDiskSizeWithHeader();
294       }
295       // Flags: don't cache the block, use pread, this is not a compaction.
296       // Also, pass null for expected block type to avoid checking it.
297       HFileBlock block = reader.readBlock(offset, onDiskSize, false, true,
298           false, true, null);
299       BlockCacheKey blockCacheKey = new BlockCacheKey(reader.getName(),
300       offset, encodingInCache, block.getBlockType());
301       HFileBlock fromCache = (HFileBlock) blockCache.getBlock(blockCacheKey, true, false, true);
302       boolean isCached = fromCache != null;
303       boolean shouldBeCached = cowType.shouldBeCached(block.getBlockType());
304       assertTrue("shouldBeCached: " + shouldBeCached+ "\n" +
305           "isCached: " + isCached + "\n" +
306           "Test description: " + testDescription + "\n" +
307           "block: " + block + "\n" +
308           "encodingInCache: " + encodingInCache + "\n" +
309           "blockCacheKey: " + blockCacheKey,
310         shouldBeCached == isCached);
311       if (isCached) {
312         if (cacheConf.shouldCacheCompressed(fromCache.getBlockType().getCategory())) {
313           if (compress != Compression.Algorithm.NONE) {
314             assertFalse(fromCache.isUnpacked());
315           }
316           fromCache = fromCache.unpack(meta, reader.getUncachedBlockReader());
317         } else {
318           assertTrue(fromCache.isUnpacked());
319         }
320         // block we cached at write-time and block read from file should be identical
321         assertEquals(block.getChecksumType(), fromCache.getChecksumType());
322         assertEquals(block.getBlockType(), fromCache.getBlockType());
323         if (block.getBlockType() == BlockType.ENCODED_DATA) {
324           assertEquals(block.getDataBlockEncodingId(), fromCache.getDataBlockEncodingId());
325           assertEquals(block.getDataBlockEncoding(), fromCache.getDataBlockEncoding());
326         }
327         assertEquals(block.getOnDiskSizeWithHeader(), fromCache.getOnDiskSizeWithHeader());
328         assertEquals(block.getOnDiskSizeWithoutHeader(), fromCache.getOnDiskSizeWithoutHeader());
329         assertEquals(
330           block.getUncompressedSizeWithoutHeader(), fromCache.getUncompressedSizeWithoutHeader());
331       }
332       prevBlock = block;
333       offset += block.getOnDiskSizeWithHeader();
334       BlockType bt = block.getBlockType();
335       Integer count = blockCountByType.get(bt);
336       blockCountByType.put(bt, (count == null ? 0 : count) + 1);
337     }
338 
339     LOG.info("Block count by type: " + blockCountByType);
340     String countByType = blockCountByType.toString();
341     BlockType cachedDataBlockType =
342         encoderType.encode ? BlockType.ENCODED_DATA : BlockType.DATA;
343     if (useTags) {
344       assertEquals("{" + cachedDataBlockType
345           + "=2663, LEAF_INDEX=297, BLOOM_CHUNK=9, INTERMEDIATE_INDEX=34}", countByType);
346     } else {
347       assertEquals("{" + cachedDataBlockType
348           + "=2498, LEAF_INDEX=278, BLOOM_CHUNK=9, INTERMEDIATE_INDEX=31}", countByType);
349     }
350 
351     // iterate all the keyvalue from hfile
352     while (scanner.next()) {
353       scanner.getKeyValue();
354     }
355     reader.close();
356   }
357 
358   public static KeyValue.Type generateKeyType(Random rand) {
359     if (rand.nextBoolean()) {
360       // Let's make half of KVs puts.
361       return KeyValue.Type.Put;
362     } else {
363       KeyValue.Type keyType = KeyValue.Type.values()[1 + rand.nextInt(NUM_VALID_KEY_TYPES)];
364       if (keyType == KeyValue.Type.Minimum || keyType == KeyValue.Type.Maximum) {
365         throw new RuntimeException("Generated an invalid key type: " + keyType + ". "
366             + "Probably the layout of KeyValue.Type has changed.");
367       }
368       return keyType;
369     }
370   }
371 
372   private void writeStoreFile(boolean useTags) throws IOException {
373     if(useTags) {
374       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
375     } else {
376       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 2);
377     }
378     Path storeFileParentDir = new Path(TEST_UTIL.getDataTestDir(),
379         "test_cache_on_write");
380     HFileContext meta = new HFileContextBuilder().withCompression(compress)
381         .withBytesPerCheckSum(CKBYTES).withChecksumType(ChecksumType.NULL)
382         .withBlockSize(DATA_BLOCK_SIZE).withDataBlockEncoding(encoder.getDataBlockEncoding())
383         .withIncludesTags(useTags).build();
384     StoreFile.Writer sfw = new StoreFile.WriterBuilder(conf, cacheConf, fs)
385         .withOutputDir(storeFileParentDir).withComparator(KeyValue.COMPARATOR)
386         .withFileContext(meta)
387         .withBloomType(BLOOM_TYPE).withMaxKeyCount(NUM_KV).build();
388     byte[] cf = Bytes.toBytes("fam");
389     for (int i = 0; i < NUM_KV; ++i) {
390       byte[] row = TestHFileWriterV2.randomOrderedKey(rand, i);
391       byte[] qualifier = TestHFileWriterV2.randomRowOrQualifier(rand);
392       byte[] value = TestHFileWriterV2.randomValue(rand);
393       KeyValue kv;
394       if(useTags) {
395         Tag t = new Tag((byte) 1, "visibility");
396         List<Tag> tagList = new ArrayList<Tag>();
397         tagList.add(t);
398         Tag[] tags = new Tag[1];
399         tags[0] = t;
400         kv =
401             new KeyValue(row, 0, row.length, cf, 0, cf.length, qualifier, 0, qualifier.length,
402                 rand.nextLong(), generateKeyType(rand), value, 0, value.length, tagList);
403       } else {
404         kv =
405             new KeyValue(row, 0, row.length, cf, 0, cf.length, qualifier, 0, qualifier.length,
406                 rand.nextLong(), generateKeyType(rand), value, 0, value.length);
407       }
408       sfw.append(kv);
409     }
410 
411     sfw.close();
412     storeFilePath = sfw.getPath();
413   }
414 
415   private void testNotCachingDataBlocksDuringCompactionInternals(boolean useTags)
416       throws IOException, InterruptedException {
417     if (useTags) {
418       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3);
419     } else {
420       TEST_UTIL.getConfiguration().setInt("hfile.format.version", 2);
421     }
422     // TODO: need to change this test if we add a cache size threshold for
423     // compactions, or if we implement some other kind of intelligent logic for
424     // deciding what blocks to cache-on-write on compaction.
425     final String table = "CompactionCacheOnWrite";
426     final String cf = "myCF";
427     final byte[] cfBytes = Bytes.toBytes(cf);
428     final int maxVersions = 3;
429     HRegion region = TEST_UTIL.createTestRegion(table, 
430         new HColumnDescriptor(cf)
431             .setCompressionType(compress)
432             .setBloomFilterType(BLOOM_TYPE)
433             .setMaxVersions(maxVersions)
434             .setDataBlockEncoding(encoder.getDataBlockEncoding())
435     );
436     int rowIdx = 0;
437     long ts = EnvironmentEdgeManager.currentTimeMillis();
438     for (int iFile = 0; iFile < 5; ++iFile) {
439       for (int iRow = 0; iRow < 500; ++iRow) {
440         String rowStr = "" + (rowIdx * rowIdx * rowIdx) + "row" + iFile + "_" + 
441             iRow;
442         Put p = new Put(Bytes.toBytes(rowStr));
443         ++rowIdx;
444         for (int iCol = 0; iCol < 10; ++iCol) {
445           String qualStr = "col" + iCol;
446           String valueStr = "value_" + rowStr + "_" + qualStr;
447           for (int iTS = 0; iTS < 5; ++iTS) {
448             if (useTags) {
449               Tag t = new Tag((byte) 1, "visibility");
450               Tag[] tags = new Tag[1];
451               tags[0] = t;
452               KeyValue kv = new KeyValue(Bytes.toBytes(rowStr), cfBytes, Bytes.toBytes(qualStr),
453                   HConstants.LATEST_TIMESTAMP, Bytes.toBytes(valueStr), tags);
454               p.add(kv);
455             } else {
456               p.add(cfBytes, Bytes.toBytes(qualStr), ts++, Bytes.toBytes(valueStr));
457             }
458           }
459         }
460         p.setDurability(Durability.ASYNC_WAL);
461         region.put(p);
462       }
463       region.flushcache();
464     }
465     clearBlockCache(blockCache);
466     assertEquals(0, blockCache.getBlockCount());
467     region.compactStores();
468     LOG.debug("compactStores() returned");
469 
470     for (CachedBlock block: blockCache) {
471       assertNotEquals(BlockType.ENCODED_DATA, block.getBlockType());
472       assertNotEquals(BlockType.DATA, block.getBlockType());
473     }
474     region.close();
475   }
476 
477   @Test
478   public void testStoreFileCacheOnWrite() throws IOException {
479     testStoreFileCacheOnWriteInternals(false);
480     testStoreFileCacheOnWriteInternals(true);
481   }
482 
483   @Test
484   public void testNotCachingDataBlocksDuringCompaction() throws IOException, InterruptedException {
485     testNotCachingDataBlocksDuringCompactionInternals(false);
486     testNotCachingDataBlocksDuringCompactionInternals(true);
487   }
488 }