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