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