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