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.mapreduce;
21
22 import static org.junit.Assert.assertEquals;
23 import static org.junit.Assert.assertFalse;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertNotSame;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.io.IOException;
30 import java.lang.reflect.Constructor;
31 import java.util.Arrays;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Set;
37 import java.util.TreeSet;
38 import java.util.concurrent.Callable;
39 import java.util.Random;
40
41 import junit.framework.Assert;
42 import org.apache.commons.logging.Log;
43 import org.apache.commons.logging.LogFactory;
44 import org.apache.hadoop.conf.Configuration;
45 import org.apache.hadoop.fs.FileStatus;
46 import org.apache.hadoop.fs.FileSystem;
47 import org.apache.hadoop.fs.Path;
48 import org.apache.hadoop.hbase.*;
49 import org.apache.hadoop.hbase.client.HBaseAdmin;
50 import org.apache.hadoop.hbase.client.HTable;
51 import org.apache.hadoop.hbase.client.Put;
52 import org.apache.hadoop.hbase.client.Result;
53 import org.apache.hadoop.hbase.client.ResultScanner;
54 import org.apache.hadoop.hbase.client.Scan;
55 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
56 import org.apache.hadoop.hbase.io.hfile.CacheConfig;
57 import org.apache.hadoop.hbase.io.hfile.Compression;
58 import org.apache.hadoop.hbase.io.hfile.Compression.Algorithm;
59 import org.apache.hadoop.hbase.io.hfile.HFile;
60 import org.apache.hadoop.hbase.io.hfile.HFile.Reader;
61 import org.apache.hadoop.hbase.regionserver.Store;
62 import org.apache.hadoop.hbase.regionserver.StoreFile;
63 import org.apache.hadoop.hbase.regionserver.TimeRangeTracker;
64 import org.apache.hadoop.hbase.util.Bytes;
65 import org.apache.hadoop.hbase.util.FSUtils;
66 import org.apache.hadoop.hbase.util.Threads;
67 import org.apache.hadoop.hbase.util.Writables;
68 import org.apache.hadoop.io.NullWritable;
69 import org.apache.hadoop.mapreduce.Job;
70 import org.apache.hadoop.mapreduce.Mapper;
71 import org.apache.hadoop.mapreduce.RecordWriter;
72 import org.apache.hadoop.mapreduce.TaskAttemptContext;
73 import org.apache.hadoop.mapreduce.TaskAttemptID;
74 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
75 import org.junit.Before;
76 import org.junit.Test;
77 import org.junit.experimental.categories.Category;
78 import org.mockito.Mockito;
79
80 import com.google.common.collect.Lists;
81
82
83
84
85
86
87
88 @Category(LargeTests.class)
89 public class TestHFileOutputFormat {
90 private final static int ROWSPERSPLIT = 1024;
91
92 private static final byte[][] FAMILIES
93 = { Bytes.add(PerformanceEvaluation.FAMILY_NAME, Bytes.toBytes("-A"))
94 , Bytes.add(PerformanceEvaluation.FAMILY_NAME, Bytes.toBytes("-B"))};
95 private static final byte[] TABLE_NAME = Bytes.toBytes("TestTable");
96
97 private HBaseTestingUtility util = new HBaseTestingUtility();
98
99 private static Log LOG = LogFactory.getLog(TestHFileOutputFormat.class);
100
101
102
103
104 static class RandomKVGeneratingMapper
105 extends Mapper<NullWritable, NullWritable,
106 ImmutableBytesWritable, KeyValue> {
107
108 private int keyLength;
109 private static final int KEYLEN_DEFAULT=10;
110 private static final String KEYLEN_CONF="randomkv.key.length";
111
112 private int valLength;
113 private static final int VALLEN_DEFAULT=10;
114 private static final String VALLEN_CONF="randomkv.val.length";
115
116 @Override
117 protected void setup(Context context) throws IOException,
118 InterruptedException {
119 super.setup(context);
120
121 Configuration conf = context.getConfiguration();
122 keyLength = conf.getInt(KEYLEN_CONF, KEYLEN_DEFAULT);
123 valLength = conf.getInt(VALLEN_CONF, VALLEN_DEFAULT);
124 }
125
126 protected void map(
127 NullWritable n1, NullWritable n2,
128 Mapper<NullWritable, NullWritable,
129 ImmutableBytesWritable,KeyValue>.Context context)
130 throws java.io.IOException ,InterruptedException
131 {
132
133 byte keyBytes[] = new byte[keyLength];
134 byte valBytes[] = new byte[valLength];
135
136 int taskId = context.getTaskAttemptID().getTaskID().getId();
137 assert taskId < Byte.MAX_VALUE : "Unit tests dont support > 127 tasks!";
138
139 Random random = new Random();
140 for (int i = 0; i < ROWSPERSPLIT; i++) {
141
142 random.nextBytes(keyBytes);
143
144 keyBytes[keyLength - 1] = (byte)(taskId & 0xFF);
145 random.nextBytes(valBytes);
146 ImmutableBytesWritable key = new ImmutableBytesWritable(keyBytes);
147
148 for (byte[] family : TestHFileOutputFormat.FAMILIES) {
149 KeyValue kv = new KeyValue(keyBytes, family,
150 PerformanceEvaluation.QUALIFIER_NAME, valBytes);
151 context.write(key, kv);
152 }
153 }
154 }
155 }
156
157 @Before
158 public void cleanupDir() throws IOException {
159 util.cleanupTestDir();
160 }
161
162
163 private void setupRandomGeneratorMapper(Job job) {
164 job.setInputFormatClass(NMapInputFormat.class);
165 job.setMapperClass(RandomKVGeneratingMapper.class);
166 job.setMapOutputKeyClass(ImmutableBytesWritable.class);
167 job.setMapOutputValueClass(KeyValue.class);
168 }
169
170
171
172
173
174
175 @Test
176 public void test_LATEST_TIMESTAMP_isReplaced()
177 throws Exception {
178 Configuration conf = new Configuration(this.util.getConfiguration());
179 RecordWriter<ImmutableBytesWritable, KeyValue> writer = null;
180 TaskAttemptContext context = null;
181 Path dir =
182 util.getDataTestDir("test_LATEST_TIMESTAMP_isReplaced");
183 try {
184 Job job = new Job(conf);
185 FileOutputFormat.setOutputPath(job, dir);
186 context = getTestTaskAttemptContext(job);
187 HFileOutputFormat hof = new HFileOutputFormat();
188 writer = hof.getRecordWriter(context);
189 final byte [] b = Bytes.toBytes("b");
190
191
192
193 KeyValue kv = new KeyValue(b, b, b);
194 KeyValue original = kv.clone();
195 writer.write(new ImmutableBytesWritable(), kv);
196 assertFalse(original.equals(kv));
197 assertTrue(Bytes.equals(original.getRow(), kv.getRow()));
198 assertTrue(original.matchingColumn(kv.getFamily(), kv.getQualifier()));
199 assertNotSame(original.getTimestamp(), kv.getTimestamp());
200 assertNotSame(HConstants.LATEST_TIMESTAMP, kv.getTimestamp());
201
202
203
204 kv = new KeyValue(b, b, b, kv.getTimestamp() - 1, b);
205 original = kv.clone();
206 writer.write(new ImmutableBytesWritable(), kv);
207 assertTrue(original.equals(kv));
208 } finally {
209 if (writer != null && context != null) writer.close(context);
210 dir.getFileSystem(conf).delete(dir, true);
211 }
212 }
213
214
215
216
217 private static boolean isPost020MapReduce() {
218
219 return TaskAttemptContext.class.isInterface();
220 }
221
222 private TaskAttemptContext getTestTaskAttemptContext(final Job job)
223 throws IOException, Exception {
224 TaskAttemptContext context;
225 if (isPost020MapReduce()) {
226 TaskAttemptID id =
227 TaskAttemptID.forName("attempt_200707121733_0001_m_000000_0");
228 Class<?> clazz =
229 Class.forName("org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl");
230 Constructor<?> c = clazz.
231 getConstructor(Configuration.class, TaskAttemptID.class);
232 context = (TaskAttemptContext)c.newInstance(job.getConfiguration(), id);
233 } else {
234 context = org.apache.hadoop.hbase.mapreduce.hadoopbackport.InputSampler.
235 getTaskAttemptContext(job);
236 }
237 return context;
238 }
239
240
241
242
243
244 @Test
245 public void test_TIMERANGE() throws Exception {
246 Configuration conf = new Configuration(this.util.getConfiguration());
247 RecordWriter<ImmutableBytesWritable, KeyValue> writer = null;
248 TaskAttemptContext context = null;
249 Path dir =
250 util.getDataTestDir("test_TIMERANGE_present");
251 LOG.info("Timerange dir writing to dir: "+ dir);
252 try {
253
254 Job job = new Job(conf);
255 FileOutputFormat.setOutputPath(job, dir);
256 context = getTestTaskAttemptContext(job);
257 HFileOutputFormat hof = new HFileOutputFormat();
258 writer = hof.getRecordWriter(context);
259
260
261 final byte [] b = Bytes.toBytes("b");
262
263
264 KeyValue kv = new KeyValue(b, b, b, 2000, b);
265 KeyValue original = kv.clone();
266 writer.write(new ImmutableBytesWritable(), kv);
267 assertEquals(original,kv);
268
269
270 kv = new KeyValue(b, b, b, 1000, b);
271 original = kv.clone();
272 writer.write(new ImmutableBytesWritable(), kv);
273 assertEquals(original, kv);
274
275
276 writer.close(context);
277
278
279
280
281 FileSystem fs = FileSystem.get(conf);
282 Path attemptDirectory = hof.getDefaultWorkFile(context, "").getParent();
283 FileStatus[] sub1 = fs.listStatus(attemptDirectory);
284 FileStatus[] file = fs.listStatus(sub1[0].getPath());
285
286
287 HFile.Reader rd = HFile.createReader(fs, file[0].getPath(),
288 new CacheConfig(conf));
289 Map<byte[],byte[]> finfo = rd.loadFileInfo();
290 byte[] range = finfo.get("TIMERANGE".getBytes());
291 assertNotNull(range);
292
293
294 TimeRangeTracker timeRangeTracker = new TimeRangeTracker();
295 Writables.copyWritable(range, timeRangeTracker);
296 LOG.info(timeRangeTracker.getMinimumTimestamp() +
297 "...." + timeRangeTracker.getMaximumTimestamp());
298 assertEquals(1000, timeRangeTracker.getMinimumTimestamp());
299 assertEquals(2000, timeRangeTracker.getMaximumTimestamp());
300 rd.close();
301 } finally {
302 if (writer != null && context != null) writer.close(context);
303 dir.getFileSystem(conf).delete(dir, true);
304 }
305 }
306
307
308
309
310 @Test
311 public void testWritingPEData() throws Exception {
312 Configuration conf = util.getConfiguration();
313 Path testDir = util.getDataTestDir("testWritingPEData");
314 FileSystem fs = testDir.getFileSystem(conf);
315
316
317 conf.setInt("io.sort.mb", 20);
318
319 conf.setLong(HConstants.HREGION_MAX_FILESIZE, 64 * 1024);
320
321 Job job = new Job(conf, "testWritingPEData");
322 setupRandomGeneratorMapper(job);
323
324
325 byte[] startKey = new byte[RandomKVGeneratingMapper.KEYLEN_DEFAULT];
326 byte[] endKey = new byte[RandomKVGeneratingMapper.KEYLEN_DEFAULT];
327
328 Arrays.fill(startKey, (byte)0);
329 Arrays.fill(endKey, (byte)0xff);
330
331 job.setPartitionerClass(SimpleTotalOrderPartitioner.class);
332
333 SimpleTotalOrderPartitioner.setStartKey(job.getConfiguration(), startKey);
334 SimpleTotalOrderPartitioner.setEndKey(job.getConfiguration(), endKey);
335 job.setReducerClass(KeyValueSortReducer.class);
336 job.setOutputFormatClass(HFileOutputFormat.class);
337 job.setNumReduceTasks(4);
338
339 FileOutputFormat.setOutputPath(job, testDir);
340 assertTrue(job.waitForCompletion(false));
341 FileStatus [] files = fs.listStatus(testDir);
342 assertTrue(files.length > 0);
343 }
344
345 @Test
346 public void testJobConfiguration() throws Exception {
347 Job job = new Job();
348 HTable table = Mockito.mock(HTable.class);
349 setupMockStartKeys(table);
350 HFileOutputFormat.configureIncrementalLoad(job, table);
351 assertEquals(job.getNumReduceTasks(), 4);
352 }
353
354 private byte [][] generateRandomStartKeys(int numKeys) {
355 Random random = new Random();
356 byte[][] ret = new byte[numKeys][];
357
358 ret[0] = HConstants.EMPTY_BYTE_ARRAY;
359 for (int i = 1; i < numKeys; i++) {
360 ret[i] = PerformanceEvaluation.generateValue(random);
361 }
362 return ret;
363 }
364
365 @Test
366 public void testMRIncrementalLoad() throws Exception {
367 doIncrementalLoadTest(false);
368 }
369
370 @Test
371 public void testMRIncrementalLoadWithSplit() throws Exception {
372 doIncrementalLoadTest(true);
373 }
374
375 private void doIncrementalLoadTest(
376 boolean shouldChangeRegions) throws Exception {
377 Configuration conf = util.getConfiguration();
378 Path testDir = util.getDataTestDir("testLocalMRIncrementalLoad");
379 byte[][] startKeys = generateRandomStartKeys(5);
380
381 try {
382 util.startMiniCluster();
383 HBaseAdmin admin = new HBaseAdmin(conf);
384 HTable table = util.createTable(TABLE_NAME, FAMILIES);
385 assertEquals("Should start with empty table",
386 0, util.countRows(table));
387 int numRegions = util.createMultiRegions(
388 util.getConfiguration(), table, FAMILIES[0], startKeys);
389 assertEquals("Should make 5 regions", numRegions, 5);
390
391
392 util.startMiniMapReduceCluster();
393 runIncrementalPELoad(conf, table, testDir);
394
395 assertEquals("HFOF should not touch actual table",
396 0, util.countRows(table));
397
398
399
400 int dir = 0;
401 for (FileStatus f : testDir.getFileSystem(conf).listStatus(testDir)) {
402 for (byte[] family : FAMILIES) {
403 if (Bytes.toString(family).equals(f.getPath().getName())) {
404 ++dir;
405 }
406 }
407 }
408 assertEquals("Column family not found in FS.", FAMILIES.length, dir);
409
410
411 if (shouldChangeRegions) {
412 LOG.info("Changing regions in table");
413 admin.disableTable(table.getTableName());
414 while(util.getMiniHBaseCluster().getMaster().getAssignmentManager().
415 isRegionsInTransition()) {
416 Threads.sleep(200);
417 LOG.info("Waiting on table to finish disabling");
418 }
419 byte[][] newStartKeys = generateRandomStartKeys(15);
420 util.createMultiRegions(
421 util.getConfiguration(), table, FAMILIES[0], newStartKeys);
422 admin.enableTable(table.getTableName());
423 while (table.getRegionsInfo().size() != 15 ||
424 !admin.isTableAvailable(table.getTableName())) {
425 Thread.sleep(200);
426 LOG.info("Waiting for new region assignment to happen");
427 }
428 }
429
430
431 new LoadIncrementalHFiles(conf).doBulkLoad(testDir, table);
432
433
434 int expectedRows = NMapInputFormat.getNumMapTasks(conf) * ROWSPERSPLIT;
435 assertEquals("LoadIncrementalHFiles should put expected data in table",
436 expectedRows, util.countRows(table));
437 Scan scan = new Scan();
438 ResultScanner results = table.getScanner(scan);
439 int count = 0;
440 for (Result res : results) {
441 count++;
442 assertEquals(FAMILIES.length, res.raw().length);
443 KeyValue first = res.raw()[0];
444 for (KeyValue kv : res.raw()) {
445 assertTrue(KeyValue.COMPARATOR.matchingRows(first, kv));
446 assertTrue(Bytes.equals(first.getValue(), kv.getValue()));
447 }
448 }
449 results.close();
450 String tableDigestBefore = util.checksumRows(table);
451
452
453 admin.disableTable(TABLE_NAME);
454 while (!admin.isTableDisabled(TABLE_NAME)) {
455 Thread.sleep(200);
456 LOG.info("Waiting for table to disable");
457 }
458 admin.enableTable(TABLE_NAME);
459 util.waitTableAvailable(TABLE_NAME, 30000);
460 assertEquals("Data should remain after reopening of regions",
461 tableDigestBefore, util.checksumRows(table));
462 } finally {
463 util.shutdownMiniMapReduceCluster();
464 util.shutdownMiniCluster();
465 }
466 }
467
468 private void runIncrementalPELoad(
469 Configuration conf, HTable table, Path outDir)
470 throws Exception {
471 Job job = new Job(conf, "testLocalMRIncrementalLoad");
472 setupRandomGeneratorMapper(job);
473 HFileOutputFormat.configureIncrementalLoad(job, table);
474 FileOutputFormat.setOutputPath(job, outDir);
475
476 Assert.assertFalse( util.getTestFileSystem().exists(outDir)) ;
477
478 assertEquals(table.getRegionsInfo().size(),
479 job.getNumReduceTasks());
480
481 assertTrue(job.waitForCompletion(true));
482 }
483
484
485
486
487
488
489
490
491 @Test
492 public void testCreateFamilyCompressionMap() throws IOException {
493 for (int numCfs = 0; numCfs <= 3; numCfs++) {
494 Configuration conf = new Configuration(this.util.getConfiguration());
495 Map<String, Compression.Algorithm> familyToCompression = getMockColumnFamilies(numCfs);
496 HTable table = Mockito.mock(HTable.class);
497 setupMockColumnFamilies(table, familyToCompression);
498 HFileOutputFormat.configureCompression(table, conf);
499
500
501 Map<byte[], String> retrievedFamilyToCompressionMap = HFileOutputFormat.createFamilyCompressionMap(conf);
502
503
504
505 for (Entry<String, Algorithm> entry : familyToCompression.entrySet()) {
506 assertEquals("Compression configuration incorrect for column family:" + entry.getKey(), entry.getValue()
507 .getName(), retrievedFamilyToCompressionMap.get(entry.getKey().getBytes()));
508 }
509 }
510 }
511
512 private void setupMockColumnFamilies(HTable table,
513 Map<String, Compression.Algorithm> familyToCompression) throws IOException
514 {
515 HTableDescriptor mockTableDescriptor = new HTableDescriptor(TABLE_NAME);
516 for (Entry<String, Compression.Algorithm> entry : familyToCompression.entrySet()) {
517 mockTableDescriptor.addFamily(new HColumnDescriptor(entry.getKey())
518 .setMaxVersions(1)
519 .setCompressionType(entry.getValue())
520 .setBlockCacheEnabled(false)
521 .setTimeToLive(0));
522 }
523 Mockito.doReturn(mockTableDescriptor).when(table).getTableDescriptor();
524 }
525
526 private void setupMockStartKeys(HTable table) throws IOException {
527 byte[][] mockKeys = new byte[][] {
528 HConstants.EMPTY_BYTE_ARRAY,
529 Bytes.toBytes("aaa"),
530 Bytes.toBytes("ggg"),
531 Bytes.toBytes("zzz")
532 };
533 Mockito.doReturn(mockKeys).when(table).getStartKeys();
534 }
535
536
537
538
539
540 private Map<String, Compression.Algorithm> getMockColumnFamilies(int numCfs) {
541 Map<String, Compression.Algorithm> familyToCompression = new HashMap<String, Compression.Algorithm>();
542
543 if (numCfs-- > 0) {
544 familyToCompression.put("Family1!@#!@#&", Compression.Algorithm.LZO);
545 }
546 if (numCfs-- > 0) {
547 familyToCompression.put("Family2=asdads&!AASD", Compression.Algorithm.SNAPPY);
548 }
549 if (numCfs-- > 0) {
550 familyToCompression.put("Family2=asdads&!AASD", Compression.Algorithm.GZ);
551 }
552 if (numCfs-- > 0) {
553 familyToCompression.put("Family3", Compression.Algorithm.NONE);
554 }
555 return familyToCompression;
556 }
557
558
559
560
561
562 @Test
563 public void testColumnFamilySettings() throws Exception {
564 Configuration conf = new Configuration(this.util.getConfiguration());
565 RecordWriter<ImmutableBytesWritable, KeyValue> writer = null;
566 TaskAttemptContext context = null;
567 Path dir = util.getDataTestDir("testColumnFamilySettings");
568
569
570 HTable table = Mockito.mock(HTable.class);
571 HTableDescriptor htd = new HTableDescriptor(TABLE_NAME);
572 Mockito.doReturn(htd).when(table).getTableDescriptor();
573 for (HColumnDescriptor hcd: this.util.generateColumnDescriptors()) {
574 htd.addFamily(hcd);
575 }
576
577
578 setupMockStartKeys(table);
579
580 try {
581
582
583
584 conf.set("io.seqfile.compression.type", "NONE");
585 Job job = new Job(conf, "testLocalMRIncrementalLoad");
586 setupRandomGeneratorMapper(job);
587 HFileOutputFormat.configureIncrementalLoad(job, table);
588 FileOutputFormat.setOutputPath(job, dir);
589 context = getTestTaskAttemptContext(job);
590 HFileOutputFormat hof = new HFileOutputFormat();
591 writer = hof.getRecordWriter(context);
592
593
594 writeRandomKeyValues(writer, context, htd.getFamiliesKeys(), ROWSPERSPLIT);
595 writer.close(context);
596
597
598 FileSystem fs = dir.getFileSystem(conf);
599
600
601 hof.getOutputCommitter(context).commitTask(context);
602 hof.getOutputCommitter(context).commitJob(context);
603 FileStatus[] families = FSUtils.listStatus(fs, dir, new FSUtils.FamilyDirFilter(fs));
604 assertEquals(htd.getFamilies().size(), families.length);
605 for (FileStatus f : families) {
606 String familyStr = f.getPath().getName();
607 HColumnDescriptor hcd = htd.getFamily(Bytes.toBytes(familyStr));
608
609
610 Path dataFilePath = fs.listStatus(f.getPath())[0].getPath();
611 Reader reader = HFile.createReader(fs, dataFilePath, new CacheConfig(conf));
612 Map<byte[], byte[]> fileInfo = reader.loadFileInfo();
613
614 byte[] bloomFilter = fileInfo.get(StoreFile.BLOOM_FILTER_TYPE_KEY);
615 if (bloomFilter == null) bloomFilter = Bytes.toBytes("NONE");
616 assertEquals("Incorrect bloom filter used for column family " + familyStr +
617 "(reader: " + reader + ")",
618 hcd.getBloomFilterType(), StoreFile.BloomType.valueOf(Bytes.toString(bloomFilter)));
619 assertEquals("Incorrect compression used for column family " + familyStr +
620 "(reader: " + reader + ")", hcd.getCompression(), reader.getCompressionAlgorithm());
621 }
622 } finally {
623 dir.getFileSystem(conf).delete(dir, true);
624 }
625 }
626
627
628
629
630
631 private void writeRandomKeyValues(RecordWriter<ImmutableBytesWritable, KeyValue> writer,
632 TaskAttemptContext context, Set<byte[]> families, int numRows)
633 throws IOException, InterruptedException {
634 byte keyBytes[] = new byte[Bytes.SIZEOF_INT];
635 int valLength = 10;
636 byte valBytes[] = new byte[valLength];
637
638 int taskId = context.getTaskAttemptID().getTaskID().getId();
639 assert taskId < Byte.MAX_VALUE : "Unit tests dont support > 127 tasks!";
640
641 Random random = new Random();
642 for (int i = 0; i < numRows; i++) {
643
644 Bytes.putInt(keyBytes, 0, i);
645 random.nextBytes(valBytes);
646 ImmutableBytesWritable key = new ImmutableBytesWritable(keyBytes);
647
648 for (byte[] family : families) {
649 KeyValue kv = new KeyValue(keyBytes, family,
650 PerformanceEvaluation.QUALIFIER_NAME, valBytes);
651 writer.write(key, kv);
652 }
653 }
654 }
655
656
657
658
659
660
661
662 @Test
663 public void testExcludeAllFromMinorCompaction() throws Exception {
664 Configuration conf = util.getConfiguration();
665 conf.setInt("hbase.hstore.compaction.min", 2);
666 generateRandomStartKeys(5);
667
668 try {
669 util.startMiniCluster();
670 final FileSystem fs = util.getDFSCluster().getFileSystem();
671 HBaseAdmin admin = new HBaseAdmin(conf);
672 HTable table = util.createTable(TABLE_NAME, FAMILIES);
673 assertEquals("Should start with empty table", 0, util.countRows(table));
674
675
676 final Path storePath = Store.getStoreHomedir(
677 HTableDescriptor.getTableDir(FSUtils.getRootDir(conf), TABLE_NAME),
678 admin.getTableRegions(TABLE_NAME).get(0).getEncodedName(),
679 FAMILIES[0]);
680 assertEquals(0, fs.listStatus(storePath).length);
681
682
683 conf.setBoolean("hbase.mapreduce.hfileoutputformat.compaction.exclude",
684 true);
685 util.startMiniMapReduceCluster();
686
687 for (int i = 0; i < 2; i++) {
688 Path testDir = util.getDataTestDir("testExcludeAllFromMinorCompaction_" + i);
689 runIncrementalPELoad(conf, table, testDir);
690
691 new LoadIncrementalHFiles(conf).doBulkLoad(testDir, table);
692 }
693
694
695 int expectedRows = 2 * NMapInputFormat.getNumMapTasks(conf) * ROWSPERSPLIT;
696 assertEquals("LoadIncrementalHFiles should put expected data in table",
697 expectedRows, util.countRows(table));
698
699
700 assertEquals(2, fs.listStatus(storePath).length);
701
702
703 admin.compact(TABLE_NAME);
704 try {
705 quickPoll(new Callable<Boolean>() {
706 public Boolean call() throws Exception {
707 return fs.listStatus(storePath).length == 1;
708 }
709 }, 5000);
710 throw new IOException("SF# = " + fs.listStatus(storePath).length);
711 } catch (AssertionError ae) {
712
713 }
714
715
716 admin.majorCompact(TABLE_NAME);
717 quickPoll(new Callable<Boolean>() {
718 public Boolean call() throws Exception {
719 return fs.listStatus(storePath).length == 1;
720 }
721 }, 5000);
722
723 } finally {
724 util.shutdownMiniMapReduceCluster();
725 util.shutdownMiniCluster();
726 }
727 }
728
729 @Test
730 public void testExcludeMinorCompaction() throws Exception {
731 Configuration conf = util.getConfiguration();
732 conf.setInt("hbase.hstore.compaction.min", 2);
733 Path testDir = util.getDataTestDir("testExcludeMinorCompaction");
734 generateRandomStartKeys(5);
735
736 try {
737 util.startMiniCluster();
738 final FileSystem fs = util.getDFSCluster().getFileSystem();
739 HBaseAdmin admin = new HBaseAdmin(conf);
740 HTable table = util.createTable(TABLE_NAME, FAMILIES);
741 assertEquals("Should start with empty table", 0, util.countRows(table));
742
743
744 final Path storePath = Store.getStoreHomedir(
745 HTableDescriptor.getTableDir(FSUtils.getRootDir(conf), TABLE_NAME),
746 admin.getTableRegions(TABLE_NAME).get(0).getEncodedName(),
747 FAMILIES[0]);
748 assertEquals(0, fs.listStatus(storePath).length);
749
750
751 Put p = new Put(Bytes.toBytes("test"));
752 p.add(FAMILIES[0], Bytes.toBytes("1"), Bytes.toBytes("1"));
753 table.put(p);
754 admin.flush(TABLE_NAME);
755 assertEquals(1, util.countRows(table));
756 quickPoll(new Callable<Boolean>() {
757 public Boolean call() throws Exception {
758 return fs.listStatus(storePath).length == 1;
759 }
760 }, 5000);
761
762
763 conf.setBoolean("hbase.mapreduce.hfileoutputformat.compaction.exclude",
764 true);
765 util.startMiniMapReduceCluster();
766 runIncrementalPELoad(conf, table, testDir);
767
768
769 new LoadIncrementalHFiles(conf).doBulkLoad(testDir, table);
770
771
772 int expectedRows = NMapInputFormat.getNumMapTasks(conf) * ROWSPERSPLIT;
773 assertEquals("LoadIncrementalHFiles should put expected data in table",
774 expectedRows + 1, util.countRows(table));
775
776
777 assertEquals(2, fs.listStatus(storePath).length);
778
779
780 admin.compact(TABLE_NAME);
781 try {
782 quickPoll(new Callable<Boolean>() {
783 public Boolean call() throws Exception {
784 return fs.listStatus(storePath).length == 1;
785 }
786 }, 5000);
787 throw new IOException("SF# = " + fs.listStatus(storePath).length);
788 } catch (AssertionError ae) {
789
790 }
791
792
793 admin.majorCompact(TABLE_NAME);
794 quickPoll(new Callable<Boolean>() {
795 public Boolean call() throws Exception {
796 return fs.listStatus(storePath).length == 1;
797 }
798 }, 5000);
799
800 } finally {
801 util.shutdownMiniMapReduceCluster();
802 util.shutdownMiniCluster();
803 }
804 }
805
806 private void quickPoll(Callable<Boolean> c, int waitMs) throws Exception {
807 int sleepMs = 10;
808 int retries = (int) Math.ceil(((double) waitMs) / sleepMs);
809 while (retries-- > 0) {
810 if (c.call().booleanValue()) {
811 return;
812 }
813 Thread.sleep(sleepMs);
814 }
815 fail();
816 }
817
818 public static void main(String args[]) throws Exception {
819 new TestHFileOutputFormat().manualTest(args);
820 }
821
822 public void manualTest(String args[]) throws Exception {
823 Configuration conf = HBaseConfiguration.create();
824 util = new HBaseTestingUtility(conf);
825 if ("newtable".equals(args[0])) {
826 byte[] tname = args[1].getBytes();
827 HTable table = util.createTable(tname, FAMILIES);
828 HBaseAdmin admin = new HBaseAdmin(conf);
829 admin.disableTable(tname);
830 byte[][] startKeys = generateRandomStartKeys(5);
831 util.createMultiRegions(conf, table, FAMILIES[0], startKeys);
832 admin.enableTable(tname);
833 } else if ("incremental".equals(args[0])) {
834 byte[] tname = args[1].getBytes();
835 HTable table = new HTable(conf, tname);
836 Path outDir = new Path("incremental-out");
837 runIncrementalPELoad(conf, table, outDir);
838 } else {
839 throw new RuntimeException(
840 "usage: TestHFileOutputFormat newtable | incremental");
841 }
842 }
843
844 @org.junit.Rule
845 public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu =
846 new org.apache.hadoop.hbase.ResourceCheckerJUnitRule();
847 }
848