1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.mapreduce;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertFalse;
23 import static org.junit.Assert.assertNotNull;
24 import static org.junit.Assert.assertNotSame;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
28 import java.io.IOException;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Random;
34 import java.util.Set;
35 import java.util.concurrent.Callable;
36
37 import junit.framework.Assert;
38
39 import org.apache.commons.logging.Log;
40 import org.apache.commons.logging.LogFactory;
41 import org.apache.hadoop.conf.Configuration;
42 import org.apache.hadoop.fs.FileStatus;
43 import org.apache.hadoop.fs.FileSystem;
44 import org.apache.hadoop.fs.Path;
45 import org.apache.hadoop.hbase.CategoryBasedTimeout;
46 import org.apache.hadoop.hbase.Cell;
47 import org.apache.hadoop.hbase.CellUtil;
48 import org.apache.hadoop.hbase.CompatibilitySingletonFactory;
49 import org.apache.hadoop.hbase.HBaseConfiguration;
50 import org.apache.hadoop.hbase.HBaseTestingUtility;
51 import org.apache.hadoop.hbase.HColumnDescriptor;
52 import org.apache.hadoop.hbase.HConstants;
53 import org.apache.hadoop.hbase.HTableDescriptor;
54 import org.apache.hadoop.hbase.HadoopShims;
55 import org.apache.hadoop.hbase.KeyValue;
56 import org.apache.hadoop.hbase.PerformanceEvaluation;
57 import org.apache.hadoop.hbase.TableName;
58 import org.apache.hadoop.hbase.client.HBaseAdmin;
59 import org.apache.hadoop.hbase.client.HTable;
60 import org.apache.hadoop.hbase.client.Put;
61 import org.apache.hadoop.hbase.client.RegionLocator;
62 import org.apache.hadoop.hbase.client.Result;
63 import org.apache.hadoop.hbase.client.ResultScanner;
64 import org.apache.hadoop.hbase.client.Scan;
65 import org.apache.hadoop.hbase.client.Table;
66 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
67 import org.apache.hadoop.hbase.io.compress.Compression;
68 import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
69 import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
70 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
71 import org.apache.hadoop.hbase.io.hfile.HFile;
72 import org.apache.hadoop.hbase.io.hfile.HFile.Reader;
73 import org.apache.hadoop.hbase.regionserver.BloomType;
74 import org.apache.hadoop.hbase.regionserver.HStore;
75 import org.apache.hadoop.hbase.regionserver.StoreFile;
76 import org.apache.hadoop.hbase.regionserver.TimeRangeTracker;
77 import org.apache.hadoop.hbase.testclassification.LargeTests;
78 import org.apache.hadoop.hbase.util.Bytes;
79 import org.apache.hadoop.hbase.util.FSUtils;
80 import org.apache.hadoop.hbase.util.Threads;
81 import org.apache.hadoop.hbase.util.Writables;
82 import org.apache.hadoop.io.NullWritable;
83 import org.apache.hadoop.mapreduce.Job;
84 import org.apache.hadoop.mapreduce.Mapper;
85 import org.apache.hadoop.mapreduce.RecordWriter;
86 import org.apache.hadoop.mapreduce.TaskAttemptContext;
87 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
88 import org.junit.Ignore;
89 import org.junit.Rule;
90 import org.junit.Test;
91 import org.junit.experimental.categories.Category;
92 import org.junit.rules.TestRule;
93 import org.mockito.Mockito;
94
95
96
97
98
99
100
101 @Category(LargeTests.class)
102 public class TestHFileOutputFormat {
103 @Rule public final TestRule timeout = CategoryBasedTimeout.builder().
104 withTimeout(this.getClass()).withLookingForStuckThread(true).build();
105 private final static int ROWSPERSPLIT = 1024;
106
107 private static final byte[] FAMILY_NAME = Bytes.toBytes("info");
108 private static final byte[][] FAMILIES = {
109 Bytes.add(FAMILY_NAME, Bytes.toBytes("-A")),
110 Bytes.add(FAMILY_NAME, Bytes.toBytes("-B"))
111 };
112 private static final TableName TABLE_NAME =
113 TableName.valueOf("TestTable");
114
115 private HBaseTestingUtility util = new HBaseTestingUtility();
116
117 private static final Log LOG = LogFactory.getLog(TestHFileOutputFormat.class);
118
119
120
121
122 static class RandomKVGeneratingMapper extends
123 Mapper<NullWritable, NullWritable, ImmutableBytesWritable, KeyValue> {
124
125 private int keyLength;
126 private static final int KEYLEN_DEFAULT = 10;
127 private static final String KEYLEN_CONF = "randomkv.key.length";
128
129 private int valLength;
130 private static final int VALLEN_DEFAULT=10;
131 private static final String VALLEN_CONF="randomkv.val.length";
132 private static final byte [] QUALIFIER = Bytes.toBytes("data");
133
134 @Override
135 protected void setup(Context context) throws IOException,
136 InterruptedException {
137 super.setup(context);
138
139 Configuration conf = context.getConfiguration();
140 keyLength = conf.getInt(KEYLEN_CONF, KEYLEN_DEFAULT);
141 valLength = conf.getInt(VALLEN_CONF, VALLEN_DEFAULT);
142 }
143
144 protected void map(
145 NullWritable n1, NullWritable n2,
146 Mapper<NullWritable, NullWritable,
147 ImmutableBytesWritable,KeyValue>.Context context)
148 throws java.io.IOException ,InterruptedException
149 {
150
151 byte keyBytes[] = new byte[keyLength];
152 byte valBytes[] = new byte[valLength];
153
154 int taskId = context.getTaskAttemptID().getTaskID().getId();
155 assert taskId < Byte.MAX_VALUE : "Unit tests dont support > 127 tasks!";
156
157 Random random = new Random();
158 for (int i = 0; i < ROWSPERSPLIT; i++) {
159
160 random.nextBytes(keyBytes);
161
162 keyBytes[keyLength - 1] = (byte)(taskId & 0xFF);
163 random.nextBytes(valBytes);
164 ImmutableBytesWritable key = new ImmutableBytesWritable(keyBytes);
165
166 for (byte[] family : TestHFileOutputFormat.FAMILIES) {
167 KeyValue kv = new KeyValue(keyBytes, family, QUALIFIER, valBytes);
168 context.write(key, kv);
169 }
170 }
171 }
172 }
173
174 private void setupRandomGeneratorMapper(Job job) {
175 job.setInputFormatClass(NMapInputFormat.class);
176 job.setMapperClass(RandomKVGeneratingMapper.class);
177 job.setMapOutputKeyClass(ImmutableBytesWritable.class);
178 job.setMapOutputValueClass(KeyValue.class);
179 }
180
181
182
183
184
185
186 @Test
187 public void test_LATEST_TIMESTAMP_isReplaced()
188 throws Exception {
189 Configuration conf = new Configuration(this.util.getConfiguration());
190 RecordWriter<ImmutableBytesWritable, KeyValue> writer = null;
191 TaskAttemptContext context = null;
192 Path dir =
193 util.getDataTestDir("test_LATEST_TIMESTAMP_isReplaced");
194 try {
195 Job job = new Job(conf);
196 FileOutputFormat.setOutputPath(job, dir);
197 context = createTestTaskAttemptContext(job);
198 HFileOutputFormat hof = new HFileOutputFormat();
199 writer = hof.getRecordWriter(context);
200 final byte [] b = Bytes.toBytes("b");
201
202
203
204 KeyValue kv = new KeyValue(b, b, b);
205 KeyValue original = kv.clone();
206 writer.write(new ImmutableBytesWritable(), kv);
207 assertFalse(original.equals(kv));
208 assertTrue(Bytes.equals(original.getRow(), kv.getRow()));
209 assertTrue(CellUtil.matchingColumn(original, kv.getFamily(), kv.getQualifier()));
210 assertNotSame(original.getTimestamp(), kv.getTimestamp());
211 assertNotSame(HConstants.LATEST_TIMESTAMP, kv.getTimestamp());
212
213
214
215 kv = new KeyValue(b, b, b, kv.getTimestamp() - 1, b);
216 original = kv.clone();
217 writer.write(new ImmutableBytesWritable(), kv);
218 assertTrue(original.equals(kv));
219 } finally {
220 if (writer != null && context != null) writer.close(context);
221 dir.getFileSystem(conf).delete(dir, true);
222 }
223 }
224
225 private TaskAttemptContext createTestTaskAttemptContext(final Job job)
226 throws IOException, Exception {
227 HadoopShims hadoop = CompatibilitySingletonFactory.getInstance(HadoopShims.class);
228 TaskAttemptContext context = hadoop.createTestTaskAttemptContext(job, "attempt_200707121733_0001_m_000000_0");
229 return context;
230 }
231
232
233
234
235
236 @Test
237 public void test_TIMERANGE() throws Exception {
238 Configuration conf = new Configuration(this.util.getConfiguration());
239 RecordWriter<ImmutableBytesWritable, KeyValue> writer = null;
240 TaskAttemptContext context = null;
241 Path dir =
242 util.getDataTestDir("test_TIMERANGE_present");
243 LOG.info("Timerange dir writing to dir: "+ dir);
244 try {
245
246 Job job = new Job(conf);
247 FileOutputFormat.setOutputPath(job, dir);
248 context = createTestTaskAttemptContext(job);
249 HFileOutputFormat hof = new HFileOutputFormat();
250 writer = hof.getRecordWriter(context);
251
252
253 final byte [] b = Bytes.toBytes("b");
254
255
256 KeyValue kv = new KeyValue(b, b, b, 2000, b);
257 KeyValue original = kv.clone();
258 writer.write(new ImmutableBytesWritable(), kv);
259 assertEquals(original,kv);
260
261
262 kv = new KeyValue(b, b, b, 1000, b);
263 original = kv.clone();
264 writer.write(new ImmutableBytesWritable(), kv);
265 assertEquals(original, kv);
266
267
268 writer.close(context);
269
270
271
272
273 FileSystem fs = FileSystem.get(conf);
274 Path attemptDirectory = hof.getDefaultWorkFile(context, "").getParent();
275 FileStatus[] sub1 = fs.listStatus(attemptDirectory);
276 FileStatus[] file = fs.listStatus(sub1[0].getPath());
277
278
279 HFile.Reader rd = HFile.createReader(fs, file[0].getPath(),
280 new CacheConfig(conf), conf);
281 Map<byte[],byte[]> finfo = rd.loadFileInfo();
282 byte[] range = finfo.get("TIMERANGE".getBytes());
283 assertNotNull(range);
284
285
286 TimeRangeTracker timeRangeTracker = new TimeRangeTracker();
287 Writables.copyWritable(range, timeRangeTracker);
288 LOG.info(timeRangeTracker.getMinimumTimestamp() +
289 "...." + timeRangeTracker.getMaximumTimestamp());
290 assertEquals(1000, timeRangeTracker.getMinimumTimestamp());
291 assertEquals(2000, timeRangeTracker.getMaximumTimestamp());
292 rd.close();
293 } finally {
294 if (writer != null && context != null) writer.close(context);
295 dir.getFileSystem(conf).delete(dir, true);
296 }
297 }
298
299
300
301
302 @Test
303 public void testWritingPEData() throws Exception {
304 Configuration conf = util.getConfiguration();
305 Path testDir = util.getDataTestDirOnTestFS("testWritingPEData");
306 FileSystem fs = testDir.getFileSystem(conf);
307
308
309 conf.setInt("mapreduce.task.io.sort.mb", 20);
310
311 conf.setLong(HConstants.HREGION_MAX_FILESIZE, 64 * 1024);
312
313 Job job = new Job(conf, "testWritingPEData");
314 setupRandomGeneratorMapper(job);
315
316
317 byte[] startKey = new byte[RandomKVGeneratingMapper.KEYLEN_DEFAULT];
318 byte[] endKey = new byte[RandomKVGeneratingMapper.KEYLEN_DEFAULT];
319
320 Arrays.fill(startKey, (byte)0);
321 Arrays.fill(endKey, (byte)0xff);
322
323 job.setPartitionerClass(SimpleTotalOrderPartitioner.class);
324
325 SimpleTotalOrderPartitioner.setStartKey(job.getConfiguration(), startKey);
326 SimpleTotalOrderPartitioner.setEndKey(job.getConfiguration(), endKey);
327 job.setReducerClass(KeyValueSortReducer.class);
328 job.setOutputFormatClass(HFileOutputFormat.class);
329 job.setNumReduceTasks(4);
330 job.getConfiguration().setStrings("io.serializations", conf.get("io.serializations"),
331 MutationSerialization.class.getName(), ResultSerialization.class.getName(),
332 KeyValueSerialization.class.getName());
333
334 FileOutputFormat.setOutputPath(job, testDir);
335 assertTrue(job.waitForCompletion(false));
336 FileStatus [] files = fs.listStatus(testDir);
337 assertTrue(files.length > 0);
338 }
339
340 @Test
341 public void testJobConfiguration() throws Exception {
342 Configuration conf = new Configuration(this.util.getConfiguration());
343 conf.set("hbase.fs.tmp.dir", util.getDataTestDir("testJobConfiguration").toString());
344 Job job = new Job(conf);
345 job.setWorkingDirectory(util.getDataTestDir("testJobConfiguration"));
346 HTableDescriptor tableDescriptor = Mockito.mock(HTableDescriptor.class);
347 RegionLocator regionLocator = Mockito.mock(RegionLocator.class);
348 setupMockStartKeys(regionLocator);
349 HFileOutputFormat2.configureIncrementalLoad(job, tableDescriptor, regionLocator);
350 assertEquals(job.getNumReduceTasks(), 4);
351 }
352
353 private byte [][] generateRandomStartKeys(int numKeys) {
354 Random random = new Random();
355 byte[][] ret = new byte[numKeys][];
356
357 ret[0] = HConstants.EMPTY_BYTE_ARRAY;
358 for (int i = 1; i < numKeys; i++) {
359 ret[i] =
360 PerformanceEvaluation.generateData(random, PerformanceEvaluation.DEFAULT_VALUE_LENGTH);
361 }
362 return ret;
363 }
364
365 private byte[][] generateRandomSplitKeys(int numKeys) {
366 Random random = new Random();
367 byte[][] ret = new byte[numKeys][];
368 for (int i = 0; i < numKeys; i++) {
369 ret[i] =
370 PerformanceEvaluation.generateData(random, PerformanceEvaluation.DEFAULT_VALUE_LENGTH);
371 }
372 return ret;
373 }
374
375 @Test
376 public void testMRIncrementalLoad() throws Exception {
377 LOG.info("\nStarting test testMRIncrementalLoad\n");
378 doIncrementalLoadTest(false);
379 }
380
381 @Test
382 public void testMRIncrementalLoadWithSplit() throws Exception {
383 LOG.info("\nStarting test testMRIncrementalLoadWithSplit\n");
384 doIncrementalLoadTest(true);
385 }
386
387 private void doIncrementalLoadTest(
388 boolean shouldChangeRegions) throws Exception {
389 util = new HBaseTestingUtility();
390 Configuration conf = util.getConfiguration();
391 byte[][] splitKeys = generateRandomSplitKeys(4);
392 HBaseAdmin admin = null;
393 try {
394 util.setJobWithoutMRCluster();
395 util.startMiniCluster();
396 Path testDir = util.getDataTestDirOnTestFS("testLocalMRIncrementalLoad");
397 admin = util.getHBaseAdmin();
398 HTable table = util.createTable(TABLE_NAME, FAMILIES, splitKeys);
399 assertEquals("Should start with empty table",
400 0, util.countRows(table));
401 int numRegions = -1;
402 try(RegionLocator r = table.getRegionLocator()) {
403 numRegions = r.getStartKeys().length;
404 }
405 assertEquals("Should make 5 regions", numRegions, 5);
406
407
408 runIncrementalPELoad(conf, table, testDir);
409
410 assertEquals("HFOF should not touch actual table",
411 0, util.countRows(table));
412
413
414
415 int dir = 0;
416 for (FileStatus f : testDir.getFileSystem(conf).listStatus(testDir)) {
417 for (byte[] family : FAMILIES) {
418 if (Bytes.toString(family).equals(f.getPath().getName())) {
419 ++dir;
420 }
421 }
422 }
423 assertEquals("Column family not found in FS.", FAMILIES.length, dir);
424
425
426 if (shouldChangeRegions) {
427 LOG.info("Changing regions in table");
428 admin.disableTable(table.getTableName());
429 while(util.getMiniHBaseCluster().getMaster().getAssignmentManager().
430 getRegionStates().isRegionsInTransition()) {
431 Threads.sleep(200);
432 LOG.info("Waiting on table to finish disabling");
433 }
434 util.deleteTable(table.getName());
435 byte[][] newSplitKeys = generateRandomSplitKeys(14);
436 table = util.createTable(TABLE_NAME, FAMILIES, newSplitKeys);
437 while (table.getRegionLocations().size() != 15 ||
438 !admin.isTableAvailable(table.getTableName())) {
439 Thread.sleep(200);
440 LOG.info("Waiting for new region assignment to happen");
441 }
442 }
443
444
445 new LoadIncrementalHFiles(conf).doBulkLoad(testDir, table);
446
447
448 int expectedRows = NMapInputFormat.getNumMapTasks(conf) * ROWSPERSPLIT;
449 assertEquals("LoadIncrementalHFiles should put expected data in table",
450 expectedRows, util.countRows(table));
451 Scan scan = new Scan();
452 ResultScanner results = table.getScanner(scan);
453 for (Result res : results) {
454 assertEquals(FAMILIES.length, res.rawCells().length);
455 Cell first = res.rawCells()[0];
456 for (Cell kv : res.rawCells()) {
457 assertTrue(CellUtil.matchingRow(first, kv));
458 assertTrue(Bytes.equals(CellUtil.cloneValue(first), CellUtil.cloneValue(kv)));
459 }
460 }
461 results.close();
462 String tableDigestBefore = util.checksumRows(table);
463
464
465 admin.disableTable(TABLE_NAME);
466 while (!admin.isTableDisabled(TABLE_NAME)) {
467 Thread.sleep(200);
468 LOG.info("Waiting for table to disable");
469 }
470 admin.enableTable(TABLE_NAME);
471 util.waitTableAvailable(TABLE_NAME);
472 assertEquals("Data should remain after reopening of regions",
473 tableDigestBefore, util.checksumRows(table));
474 } finally {
475 if (admin != null) admin.close();
476 util.shutdownMiniCluster();
477 }
478 }
479
480 private void runIncrementalPELoad(
481 Configuration conf, HTable table, Path outDir)
482 throws Exception {
483 Job job = new Job(conf, "testLocalMRIncrementalLoad");
484 job.setWorkingDirectory(util.getDataTestDirOnTestFS("runIncrementalPELoad"));
485 job.getConfiguration().setStrings("io.serializations", conf.get("io.serializations"),
486 MutationSerialization.class.getName(), ResultSerialization.class.getName(),
487 KeyValueSerialization.class.getName());
488 setupRandomGeneratorMapper(job);
489 HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(),
490 table.getRegionLocator());
491 FileOutputFormat.setOutputPath(job, outDir);
492
493 Assert.assertFalse( util.getTestFileSystem().exists(outDir)) ;
494
495 assertEquals(table.getRegionLocator().getAllRegionLocations().size(), job.getNumReduceTasks());
496
497 assertTrue(job.waitForCompletion(true));
498 }
499
500
501
502
503
504
505
506
507
508
509 @Test
510 public void testSerializeDeserializeFamilyCompressionMap() throws IOException {
511 for (int numCfs = 0; numCfs <= 3; numCfs++) {
512 Configuration conf = new Configuration(this.util.getConfiguration());
513 Map<String, Compression.Algorithm> familyToCompression =
514 getMockColumnFamiliesForCompression(numCfs);
515 Table table = Mockito.mock(HTable.class);
516 setupMockColumnFamiliesForCompression(table, familyToCompression);
517 HFileOutputFormat.configureCompression(table, conf);
518
519
520 Map<byte[], Algorithm> retrievedFamilyToCompressionMap = HFileOutputFormat
521 .createFamilyCompressionMap(conf);
522
523
524
525 for (Entry<String, Algorithm> entry : familyToCompression.entrySet()) {
526 assertEquals("Compression configuration incorrect for column family:"
527 + entry.getKey(), entry.getValue(),
528 retrievedFamilyToCompressionMap.get(entry.getKey().getBytes()));
529 }
530 }
531 }
532
533 private void setupMockColumnFamiliesForCompression(Table table,
534 Map<String, Compression.Algorithm> familyToCompression) throws IOException {
535 HTableDescriptor mockTableDescriptor = new HTableDescriptor(TABLE_NAME);
536 for (Entry<String, Compression.Algorithm> entry : familyToCompression.entrySet()) {
537 mockTableDescriptor.addFamily(new HColumnDescriptor(entry.getKey())
538 .setMaxVersions(1)
539 .setCompressionType(entry.getValue())
540 .setBlockCacheEnabled(false)
541 .setTimeToLive(0));
542 }
543 Mockito.doReturn(mockTableDescriptor).when(table).getTableDescriptor();
544 }
545
546
547
548
549
550 private Map<String, Compression.Algorithm>
551 getMockColumnFamiliesForCompression (int numCfs) {
552 Map<String, Compression.Algorithm> familyToCompression = new HashMap<String, Compression.Algorithm>();
553
554 if (numCfs-- > 0) {
555 familyToCompression.put("Family1!@#!@#&", Compression.Algorithm.LZO);
556 }
557 if (numCfs-- > 0) {
558 familyToCompression.put("Family2=asdads&!AASD", Compression.Algorithm.SNAPPY);
559 }
560 if (numCfs-- > 0) {
561 familyToCompression.put("Family2=asdads&!AASD", Compression.Algorithm.GZ);
562 }
563 if (numCfs-- > 0) {
564 familyToCompression.put("Family3", Compression.Algorithm.NONE);
565 }
566 return familyToCompression;
567 }
568
569
570
571
572
573
574
575
576
577
578
579 @Test
580 public void testSerializeDeserializeFamilyBloomTypeMap() throws IOException {
581 for (int numCfs = 0; numCfs <= 2; numCfs++) {
582 Configuration conf = new Configuration(this.util.getConfiguration());
583 Map<String, BloomType> familyToBloomType =
584 getMockColumnFamiliesForBloomType(numCfs);
585 Table table = Mockito.mock(HTable.class);
586 setupMockColumnFamiliesForBloomType(table,
587 familyToBloomType);
588 HFileOutputFormat.configureBloomType(table, conf);
589
590
591
592 Map<byte[], BloomType> retrievedFamilyToBloomTypeMap =
593 HFileOutputFormat
594 .createFamilyBloomTypeMap(conf);
595
596
597
598 for (Entry<String, BloomType> entry : familyToBloomType.entrySet()) {
599 assertEquals("BloomType configuration incorrect for column family:"
600 + entry.getKey(), entry.getValue(),
601 retrievedFamilyToBloomTypeMap.get(entry.getKey().getBytes()));
602 }
603 }
604 }
605
606 private void setupMockColumnFamiliesForBloomType(Table table,
607 Map<String, BloomType> familyToDataBlockEncoding) throws IOException {
608 HTableDescriptor mockTableDescriptor = new HTableDescriptor(TABLE_NAME);
609 for (Entry<String, BloomType> entry : familyToDataBlockEncoding.entrySet()) {
610 mockTableDescriptor.addFamily(new HColumnDescriptor(entry.getKey())
611 .setMaxVersions(1)
612 .setBloomFilterType(entry.getValue())
613 .setBlockCacheEnabled(false)
614 .setTimeToLive(0));
615 }
616 Mockito.doReturn(mockTableDescriptor).when(table).getTableDescriptor();
617 }
618
619
620
621
622
623 private Map<String, BloomType>
624 getMockColumnFamiliesForBloomType (int numCfs) {
625 Map<String, BloomType> familyToBloomType =
626 new HashMap<String, BloomType>();
627
628 if (numCfs-- > 0) {
629 familyToBloomType.put("Family1!@#!@#&", BloomType.ROW);
630 }
631 if (numCfs-- > 0) {
632 familyToBloomType.put("Family2=asdads&!AASD",
633 BloomType.ROWCOL);
634 }
635 if (numCfs-- > 0) {
636 familyToBloomType.put("Family3", BloomType.NONE);
637 }
638 return familyToBloomType;
639 }
640
641
642
643
644
645
646
647
648
649
650 @Test
651 public void testSerializeDeserializeFamilyBlockSizeMap() throws IOException {
652 for (int numCfs = 0; numCfs <= 3; numCfs++) {
653 Configuration conf = new Configuration(this.util.getConfiguration());
654 Map<String, Integer> familyToBlockSize =
655 getMockColumnFamiliesForBlockSize(numCfs);
656 Table table = Mockito.mock(HTable.class);
657 setupMockColumnFamiliesForBlockSize(table,
658 familyToBlockSize);
659 HFileOutputFormat.configureBlockSize(table, conf);
660
661
662
663 Map<byte[], Integer> retrievedFamilyToBlockSizeMap =
664 HFileOutputFormat
665 .createFamilyBlockSizeMap(conf);
666
667
668
669 for (Entry<String, Integer> entry : familyToBlockSize.entrySet()
670 ) {
671 assertEquals("BlockSize configuration incorrect for column family:"
672 + entry.getKey(), entry.getValue(),
673 retrievedFamilyToBlockSizeMap.get(entry.getKey().getBytes()));
674 }
675 }
676 }
677
678 private void setupMockColumnFamiliesForBlockSize(Table table,
679 Map<String, Integer> familyToDataBlockEncoding) throws IOException {
680 HTableDescriptor mockTableDescriptor = new HTableDescriptor(TABLE_NAME);
681 for (Entry<String, Integer> entry : familyToDataBlockEncoding.entrySet()) {
682 mockTableDescriptor.addFamily(new HColumnDescriptor(entry.getKey())
683 .setMaxVersions(1)
684 .setBlocksize(entry.getValue())
685 .setBlockCacheEnabled(false)
686 .setTimeToLive(0));
687 }
688 Mockito.doReturn(mockTableDescriptor).when(table).getTableDescriptor();
689 }
690
691
692
693
694
695 private Map<String, Integer>
696 getMockColumnFamiliesForBlockSize (int numCfs) {
697 Map<String, Integer> familyToBlockSize =
698 new HashMap<String, Integer>();
699
700 if (numCfs-- > 0) {
701 familyToBlockSize.put("Family1!@#!@#&", 1234);
702 }
703 if (numCfs-- > 0) {
704 familyToBlockSize.put("Family2=asdads&!AASD",
705 Integer.MAX_VALUE);
706 }
707 if (numCfs-- > 0) {
708 familyToBlockSize.put("Family2=asdads&!AASD",
709 Integer.MAX_VALUE);
710 }
711 if (numCfs-- > 0) {
712 familyToBlockSize.put("Family3", 0);
713 }
714 return familyToBlockSize;
715 }
716
717
718
719
720
721
722
723
724
725
726 @Test
727 public void testSerializeDeserializeFamilyDataBlockEncodingMap() throws IOException {
728 for (int numCfs = 0; numCfs <= 3; numCfs++) {
729 Configuration conf = new Configuration(this.util.getConfiguration());
730 Map<String, DataBlockEncoding> familyToDataBlockEncoding =
731 getMockColumnFamiliesForDataBlockEncoding(numCfs);
732 Table table = Mockito.mock(HTable.class);
733 setupMockColumnFamiliesForDataBlockEncoding(table,
734 familyToDataBlockEncoding);
735 HFileOutputFormat.configureDataBlockEncoding(table, conf);
736
737
738
739 Map<byte[], DataBlockEncoding> retrievedFamilyToDataBlockEncodingMap =
740 HFileOutputFormat
741 .createFamilyDataBlockEncodingMap(conf);
742
743
744
745 for (Entry<String, DataBlockEncoding> entry : familyToDataBlockEncoding.entrySet()) {
746 assertEquals("DataBlockEncoding configuration incorrect for column family:"
747 + entry.getKey(), entry.getValue(),
748 retrievedFamilyToDataBlockEncodingMap.get(entry.getKey().getBytes()));
749 }
750 }
751 }
752
753 private void setupMockColumnFamiliesForDataBlockEncoding(Table table,
754 Map<String, DataBlockEncoding> familyToDataBlockEncoding) throws IOException {
755 HTableDescriptor mockTableDescriptor = new HTableDescriptor(TABLE_NAME);
756 for (Entry<String, DataBlockEncoding> entry : familyToDataBlockEncoding.entrySet()) {
757 mockTableDescriptor.addFamily(new HColumnDescriptor(entry.getKey())
758 .setMaxVersions(1)
759 .setDataBlockEncoding(entry.getValue())
760 .setBlockCacheEnabled(false)
761 .setTimeToLive(0));
762 }
763 Mockito.doReturn(mockTableDescriptor).when(table).getTableDescriptor();
764 }
765
766
767
768
769
770 private Map<String, DataBlockEncoding>
771 getMockColumnFamiliesForDataBlockEncoding (int numCfs) {
772 Map<String, DataBlockEncoding> familyToDataBlockEncoding =
773 new HashMap<String, DataBlockEncoding>();
774
775 if (numCfs-- > 0) {
776 familyToDataBlockEncoding.put("Family1!@#!@#&", DataBlockEncoding.DIFF);
777 }
778 if (numCfs-- > 0) {
779 familyToDataBlockEncoding.put("Family2=asdads&!AASD",
780 DataBlockEncoding.FAST_DIFF);
781 }
782 if (numCfs-- > 0) {
783 familyToDataBlockEncoding.put("Family2=asdads&!AASD",
784 DataBlockEncoding.PREFIX);
785 }
786 if (numCfs-- > 0) {
787 familyToDataBlockEncoding.put("Family3", DataBlockEncoding.NONE);
788 }
789 return familyToDataBlockEncoding;
790 }
791
792 private void setupMockStartKeys(RegionLocator regionLocator) throws IOException {
793 byte[][] mockKeys = new byte[][] {
794 HConstants.EMPTY_BYTE_ARRAY,
795 Bytes.toBytes("aaa"),
796 Bytes.toBytes("ggg"),
797 Bytes.toBytes("zzz")
798 };
799 Mockito.doReturn(mockKeys).when(regionLocator).getStartKeys();
800 }
801
802
803
804
805
806 @Test
807 public void testColumnFamilySettings() throws Exception {
808 Configuration conf = new Configuration(this.util.getConfiguration());
809 RecordWriter<ImmutableBytesWritable, KeyValue> writer = null;
810 TaskAttemptContext context = null;
811 Path dir = util.getDataTestDir("testColumnFamilySettings");
812
813
814 HTable table = Mockito.mock(HTable.class);
815 RegionLocator regionLocator = Mockito.mock(RegionLocator.class);
816 HTableDescriptor htd = new HTableDescriptor(TABLE_NAME);
817 Mockito.doReturn(htd).when(table).getTableDescriptor();
818 for (HColumnDescriptor hcd: this.util.generateColumnDescriptors()) {
819 htd.addFamily(hcd);
820 }
821
822
823 setupMockStartKeys(regionLocator);
824
825 try {
826
827
828
829 conf.set("io.seqfile.compression.type", "NONE");
830 conf.set("hbase.fs.tmp.dir", dir.toString());
831 Job job = new Job(conf, "testLocalMRIncrementalLoad");
832 job.setWorkingDirectory(util.getDataTestDirOnTestFS("testColumnFamilySettings"));
833 setupRandomGeneratorMapper(job);
834 HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(), regionLocator);
835 FileOutputFormat.setOutputPath(job, dir);
836 context = createTestTaskAttemptContext(job);
837 HFileOutputFormat hof = new HFileOutputFormat();
838 writer = hof.getRecordWriter(context);
839
840
841 writeRandomKeyValues(writer, context, htd.getFamiliesKeys(), ROWSPERSPLIT);
842 writer.close(context);
843
844
845 FileSystem fs = dir.getFileSystem(conf);
846
847
848 hof.getOutputCommitter(context).commitTask(context);
849 hof.getOutputCommitter(context).commitJob(context);
850 FileStatus[] families = FSUtils.listStatus(fs, dir, new FSUtils.FamilyDirFilter(fs));
851 assertEquals(htd.getFamilies().size(), families.length);
852 for (FileStatus f : families) {
853 String familyStr = f.getPath().getName();
854 HColumnDescriptor hcd = htd.getFamily(Bytes.toBytes(familyStr));
855
856
857 Path dataFilePath = fs.listStatus(f.getPath())[0].getPath();
858 Reader reader = HFile.createReader(fs, dataFilePath, new CacheConfig(conf), conf);
859 Map<byte[], byte[]> fileInfo = reader.loadFileInfo();
860
861 byte[] bloomFilter = fileInfo.get(StoreFile.BLOOM_FILTER_TYPE_KEY);
862 if (bloomFilter == null) bloomFilter = Bytes.toBytes("NONE");
863 assertEquals("Incorrect bloom filter used for column family " + familyStr +
864 "(reader: " + reader + ")",
865 hcd.getBloomFilterType(), BloomType.valueOf(Bytes.toString(bloomFilter)));
866 assertEquals("Incorrect compression used for column family " + familyStr +
867 "(reader: " + reader + ")", hcd.getCompression(), reader.getFileContext().getCompression());
868 }
869 } finally {
870 dir.getFileSystem(conf).delete(dir, true);
871 }
872 }
873
874
875
876
877
878 private void writeRandomKeyValues(RecordWriter<ImmutableBytesWritable, KeyValue> writer,
879 TaskAttemptContext context, Set<byte[]> families, int numRows)
880 throws IOException, InterruptedException {
881 byte keyBytes[] = new byte[Bytes.SIZEOF_INT];
882 int valLength = 10;
883 byte valBytes[] = new byte[valLength];
884
885 int taskId = context.getTaskAttemptID().getTaskID().getId();
886 assert taskId < Byte.MAX_VALUE : "Unit tests dont support > 127 tasks!";
887 final byte [] qualifier = Bytes.toBytes("data");
888 Random random = new Random();
889 for (int i = 0; i < numRows; i++) {
890
891 Bytes.putInt(keyBytes, 0, i);
892 random.nextBytes(valBytes);
893 ImmutableBytesWritable key = new ImmutableBytesWritable(keyBytes);
894
895 for (byte[] family : families) {
896 KeyValue kv = new KeyValue(keyBytes, family, qualifier, valBytes);
897 writer.write(key, kv);
898 }
899 }
900 }
901
902
903
904
905
906
907
908 @Ignore ("Flakey: See HBASE-9051") @Test
909 public void testExcludeAllFromMinorCompaction() throws Exception {
910 Configuration conf = util.getConfiguration();
911 conf.setInt("hbase.hstore.compaction.min", 2);
912 generateRandomStartKeys(5);
913
914 try {
915 util.setJobWithoutMRCluster();
916 util.startMiniCluster();
917 final FileSystem fs = util.getDFSCluster().getFileSystem();
918 HBaseAdmin admin = new HBaseAdmin(conf);
919 HTable table = util.createTable(TABLE_NAME, FAMILIES);
920 assertEquals("Should start with empty table", 0, util.countRows(table));
921
922
923 final Path storePath = HStore.getStoreHomedir(
924 FSUtils.getTableDir(FSUtils.getRootDir(conf), TABLE_NAME),
925 admin.getTableRegions(TABLE_NAME).get(0),
926 FAMILIES[0]);
927 assertEquals(0, fs.listStatus(storePath).length);
928
929
930 conf.setBoolean("hbase.mapreduce.hfileoutputformat.compaction.exclude",
931 true);
932
933 for (int i = 0; i < 2; i++) {
934 Path testDir = util.getDataTestDirOnTestFS("testExcludeAllFromMinorCompaction_" + i);
935 runIncrementalPELoad(conf, table, testDir);
936
937 new LoadIncrementalHFiles(conf).doBulkLoad(testDir, table);
938 }
939
940
941 int expectedRows = 2 * NMapInputFormat.getNumMapTasks(conf) * ROWSPERSPLIT;
942 assertEquals("LoadIncrementalHFiles should put expected data in table",
943 expectedRows, util.countRows(table));
944
945
946 assertEquals(2, fs.listStatus(storePath).length);
947
948
949 admin.compact(TABLE_NAME.getName());
950 try {
951 quickPoll(new Callable<Boolean>() {
952 public Boolean call() throws Exception {
953 return fs.listStatus(storePath).length == 1;
954 }
955 }, 5000);
956 throw new IOException("SF# = " + fs.listStatus(storePath).length);
957 } catch (AssertionError ae) {
958
959 }
960
961
962 admin.majorCompact(TABLE_NAME.getName());
963 quickPoll(new Callable<Boolean>() {
964 public Boolean call() throws Exception {
965 return fs.listStatus(storePath).length == 1;
966 }
967 }, 5000);
968
969 } finally {
970 util.shutdownMiniCluster();
971 }
972 }
973
974 @Test
975 public void testExcludeMinorCompaction() throws Exception {
976 Configuration conf = util.getConfiguration();
977 conf.setInt("hbase.hstore.compaction.min", 2);
978 generateRandomStartKeys(5);
979
980 try {
981 util.setJobWithoutMRCluster();
982 util.startMiniCluster();
983 Path testDir = util.getDataTestDirOnTestFS("testExcludeMinorCompaction");
984 final FileSystem fs = util.getTestFileSystem();
985 HBaseAdmin admin = new HBaseAdmin(conf);
986 HTable table = util.createTable(TABLE_NAME, FAMILIES);
987 assertEquals("Should start with empty table", 0, util.countRows(table));
988
989
990 final Path storePath = HStore.getStoreHomedir(
991 FSUtils.getTableDir(FSUtils.getRootDir(conf), TABLE_NAME),
992 admin.getTableRegions(TABLE_NAME).get(0),
993 FAMILIES[0]);
994 assertEquals(0, fs.listStatus(storePath).length);
995
996
997 Put p = new Put(Bytes.toBytes("test"));
998 p.add(FAMILIES[0], Bytes.toBytes("1"), Bytes.toBytes("1"));
999 table.put(p);
1000 admin.flush(TABLE_NAME.getName());
1001 assertEquals(1, util.countRows(table));
1002 quickPoll(new Callable<Boolean>() {
1003 public Boolean call() throws Exception {
1004 return fs.listStatus(storePath).length == 1;
1005 }
1006 }, 5000);
1007
1008
1009 conf.setBoolean("hbase.mapreduce.hfileoutputformat.compaction.exclude",
1010 true);
1011 runIncrementalPELoad(conf, table, testDir);
1012
1013
1014 new LoadIncrementalHFiles(conf).doBulkLoad(testDir, table);
1015
1016
1017 int expectedRows = NMapInputFormat.getNumMapTasks(conf) * ROWSPERSPLIT;
1018 assertEquals("LoadIncrementalHFiles should put expected data in table",
1019 expectedRows + 1, util.countRows(table));
1020
1021
1022 assertEquals(2, fs.listStatus(storePath).length);
1023
1024
1025 admin.compact(TABLE_NAME.getName());
1026 try {
1027 quickPoll(new Callable<Boolean>() {
1028 public Boolean call() throws Exception {
1029 return fs.listStatus(storePath).length == 1;
1030 }
1031 }, 5000);
1032 throw new IOException("SF# = " + fs.listStatus(storePath).length);
1033 } catch (AssertionError ae) {
1034
1035 }
1036
1037
1038 admin.majorCompact(TABLE_NAME.getName());
1039 quickPoll(new Callable<Boolean>() {
1040 public Boolean call() throws Exception {
1041 return fs.listStatus(storePath).length == 1;
1042 }
1043 }, 5000);
1044
1045 } finally {
1046 util.shutdownMiniCluster();
1047 }
1048 }
1049
1050 private void quickPoll(Callable<Boolean> c, int waitMs) throws Exception {
1051 int sleepMs = 10;
1052 int retries = (int) Math.ceil(((double) waitMs) / sleepMs);
1053 while (retries-- > 0) {
1054 if (c.call().booleanValue()) {
1055 return;
1056 }
1057 Thread.sleep(sleepMs);
1058 }
1059 fail();
1060 }
1061
1062 public static void main(String args[]) throws Exception {
1063 new TestHFileOutputFormat().manualTest(args);
1064 }
1065
1066 public void manualTest(String args[]) throws Exception {
1067 Configuration conf = HBaseConfiguration.create();
1068 util = new HBaseTestingUtility(conf);
1069 if ("newtable".equals(args[0])) {
1070 TableName tname = TableName.valueOf(args[1]);
1071 byte[][] splitKeys = generateRandomSplitKeys(4);
1072 HTable table = util.createTable(tname, FAMILIES, splitKeys);
1073 } else if ("incremental".equals(args[0])) {
1074 TableName tname = TableName.valueOf(args[1]);
1075 HTable table = new HTable(conf, tname);
1076 Path outDir = new Path("incremental-out");
1077 runIncrementalPELoad(conf, table, outDir);
1078 } else {
1079 throw new RuntimeException(
1080 "usage: TestHFileOutputFormat newtable | incremental");
1081 }
1082 }
1083
1084 }
1085