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