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