View Javadoc

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