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.assertTrue;
23  
24  import java.io.IOException;
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.HashSet;
28  import java.util.List;
29  import java.util.Set;
30  import java.util.UUID;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.conf.Configurable;
35  import org.apache.hadoop.conf.Configuration;
36  import org.apache.hadoop.fs.FSDataOutputStream;
37  import org.apache.hadoop.fs.FileStatus;
38  import org.apache.hadoop.fs.FileSystem;
39  import org.apache.hadoop.fs.Path;
40  import org.apache.hadoop.hbase.Cell;
41  import org.apache.hadoop.hbase.CellUtil;
42  import org.apache.hadoop.hbase.HBaseTestingUtility;
43  import org.apache.hadoop.hbase.HConstants;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.TableNotFoundException;
46  import org.apache.hadoop.hbase.client.HTable;
47  import org.apache.hadoop.hbase.client.Result;
48  import org.apache.hadoop.hbase.client.ResultScanner;
49  import org.apache.hadoop.hbase.client.Scan;
50  import org.apache.hadoop.hbase.client.Table;
51  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
52  import org.apache.hadoop.hbase.io.hfile.HFile;
53  import org.apache.hadoop.hbase.io.hfile.HFileScanner;
54  import org.apache.hadoop.hbase.testclassification.LargeTests;
55  import org.apache.hadoop.hbase.util.Bytes;
56  import org.apache.hadoop.io.Text;
57  import org.apache.hadoop.mapred.Utils.OutputFileUtils.OutputFilesFilter;
58  import org.apache.hadoop.mapreduce.Job;
59  import org.apache.hadoop.util.GenericOptionsParser;
60  import org.apache.hadoop.util.Tool;
61  import org.apache.hadoop.util.ToolRunner;
62  import org.junit.AfterClass;
63  import org.junit.BeforeClass;
64  import org.junit.Test;
65  import org.junit.experimental.categories.Category;
66  
67  @Category(LargeTests.class)
68  public class TestImportTsv implements Configurable {
69  
70    private static final Log LOG = LogFactory.getLog(TestImportTsv.class);
71    protected static final String NAME = TestImportTsv.class.getSimpleName();
72    protected static HBaseTestingUtility util = new HBaseTestingUtility();
73  
74    /**
75     * Delete the tmp directory after running doMROnTableTest. Boolean. Default is
76     * false.
77     */
78    protected static final String DELETE_AFTER_LOAD_CONF = NAME + ".deleteAfterLoad";
79  
80    /**
81     * Force use of combiner in doMROnTableTest. Boolean. Default is true.
82     */
83    protected static final String FORCE_COMBINER_CONF = NAME + ".forceCombiner";
84  
85    private final String FAMILY = "FAM";
86  
87    public Configuration getConf() {
88      return util.getConfiguration();
89    }
90  
91    public void setConf(Configuration conf) {
92      throw new IllegalArgumentException("setConf not supported");
93    }
94  
95    @BeforeClass
96    public static void provisionCluster() throws Exception {
97      util.setJobWithoutMRCluster();
98      util.startMiniCluster();
99    }
100 
101   @AfterClass
102   public static void releaseCluster() throws Exception {
103     util.shutdownMiniCluster();
104   }
105 
106   @Test
107   public void testMROnTable() throws Exception {
108     String table = "test-" + UUID.randomUUID();
109 
110     // Prepare the arguments required for the test.
111     String[] args = new String[] {
112         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B",
113         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b",
114         table
115     };
116 
117     util.createTable(TableName.valueOf(table), FAMILY);
118     doMROnTableTest(util, FAMILY, null, args, 1);
119     util.deleteTable(table);
120   }
121   
122   @Test
123   public void testMROnTableWithTimestamp() throws Exception {
124     String table = "test-" + UUID.randomUUID();
125 
126     // Prepare the arguments required for the test.
127     String[] args = new String[] {
128         "-D" + ImportTsv.COLUMNS_CONF_KEY
129             + "=HBASE_ROW_KEY,HBASE_TS_KEY,FAM:A,FAM:B",
130         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=,",
131         table
132     };
133     String data = "KEY,1234,VALUE1,VALUE2\n";
134 
135     util.createTable(TableName.valueOf(table), FAMILY);
136     doMROnTableTest(util, FAMILY, data, args, 1);
137     util.deleteTable(table);
138   }
139   
140 
141   @Test
142   public void testMROnTableWithCustomMapper()
143   throws Exception {
144     String table = "test-" + UUID.randomUUID();
145 
146     // Prepare the arguments required for the test.
147     String[] args = new String[] {
148         "-D" + ImportTsv.MAPPER_CONF_KEY + "=org.apache.hadoop.hbase.mapreduce.TsvImporterCustomTestMapper",
149         table
150     };
151 
152     util.createTable(TableName.valueOf(table), FAMILY);
153     doMROnTableTest(util, FAMILY, null, args, 3);
154     util.deleteTable(table);
155   }
156   
157   @Test
158   public void testBulkOutputWithoutAnExistingTable() throws Exception {
159     String table = "test-" + UUID.randomUUID();
160 
161     // Prepare the arguments required for the test.
162     Path hfiles = new Path(util.getDataTestDirOnTestFS(table), "hfiles");
163     String[] args = new String[] {
164         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B",
165         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b",
166         "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + hfiles.toString(),
167         table
168     };
169 
170     doMROnTableTest(util, FAMILY, null, args, 3);
171     util.deleteTable(table);
172   }
173 
174   @Test
175   public void testBulkOutputWithAnExistingTable() throws Exception {
176     String table = "test-" + UUID.randomUUID();
177 
178     // Prepare the arguments required for the test.
179     Path hfiles = new Path(util.getDataTestDirOnTestFS(table), "hfiles");
180     String[] args = new String[] {
181         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B",
182         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b",
183         "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + hfiles.toString(),
184         table
185     };
186 
187     util.createTable(TableName.valueOf(table), FAMILY);
188     doMROnTableTest(util, FAMILY, null, args, 3);
189     util.deleteTable(table);
190   }
191   
192   @Test
193   public void testBulkOutputWithAnExistingTableNoStrictTrue() throws Exception {
194     String table = "test-" + UUID.randomUUID();
195     // Prepare the arguments required for the test.
196     Path hfiles = new Path(util.getDataTestDirOnTestFS(table), "hfiles");
197     String[] args = new String[] {
198         "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B",
199         "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b",
200         "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + hfiles.toString(),
201         "-D" + ImportTsv.NO_STRICT_COL_FAMILY + "=true",
202         table
203     };
204     util.createTable(TableName.valueOf(table), FAMILY);
205     doMROnTableTest(util, FAMILY, null, args, 3);
206     util.deleteTable(table);
207   }
208 
209   @Test
210   public void testJobConfigurationsWithTsvImporterTextMapper() throws Exception {
211     String table = "test-" + UUID.randomUUID();
212     Path bulkOutputPath = new Path(util.getDataTestDirOnTestFS(table),"hfiles");
213     String INPUT_FILE = "InputFile1.csv";
214     // Prepare the arguments required for the test.
215     String[] args =
216         new String[] {
217             "-D" + ImportTsv.MAPPER_CONF_KEY
218                 + "=org.apache.hadoop.hbase.mapreduce.TsvImporterTextMapper",
219             "-D" + ImportTsv.COLUMNS_CONF_KEY
220                 + "=HBASE_ROW_KEY,FAM:A,FAM:B",
221             "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=,",
222             "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + bulkOutputPath.toString(), table,
223             INPUT_FILE
224             };
225     GenericOptionsParser opts = new GenericOptionsParser(util.getConfiguration(), args);
226     args = opts.getRemainingArgs();
227     Job job = ImportTsv.createSubmittableJob(util.getConfiguration(), args);
228     assertTrue(job.getMapperClass().equals(TsvImporterTextMapper.class));
229     assertTrue(job.getReducerClass().equals(TextSortReducer.class));
230     assertTrue(job.getMapOutputValueClass().equals(Text.class));
231   }
232 
233   @Test
234   public void testBulkOutputWithTsvImporterTextMapper() throws Exception {
235     String table = "test-" + UUID.randomUUID();
236     String FAMILY = "FAM";
237     Path bulkOutputPath = new Path(util.getDataTestDirOnTestFS(table),"hfiles");
238     // Prepare the arguments required for the test.
239     String[] args =
240         new String[] {
241             "-D" + ImportTsv.MAPPER_CONF_KEY
242                 + "=org.apache.hadoop.hbase.mapreduce.TsvImporterTextMapper",
243             "-D" + ImportTsv.COLUMNS_CONF_KEY
244                 + "=HBASE_ROW_KEY,FAM:A,FAM:B",
245             "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b",
246             "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + bulkOutputPath.toString(), table 
247             };
248     String data = "KEY\u001bVALUE4\u001bVALUE8\n";
249     doMROnTableTest(util, FAMILY, data, args, 4);
250   }
251 
252   @Test(expected = TableNotFoundException.class)
253   public void testWithoutAnExistingTableAndCreateTableSetToNo() throws Exception {
254     String table = "test-" + UUID.randomUUID();
255     String[] args =
256         new String[] { table, "/inputFile" };
257 
258     Configuration conf = new Configuration(util.getConfiguration());
259     conf.set(ImportTsv.COLUMNS_CONF_KEY, "HBASE_ROW_KEY,FAM:A");
260     conf.set(ImportTsv.BULK_OUTPUT_CONF_KEY, "/output");
261     conf.set(ImportTsv.CREATE_TABLE_CONF_KEY, "no");
262     ImportTsv.createSubmittableJob(conf, args);
263   }
264 
265   @Test(expected = TableNotFoundException.class)
266   public void testMRWithoutAnExistingTable() throws Exception {
267     String table = "test-" + UUID.randomUUID();
268     String[] args =
269         new String[] { table, "/inputFile" };
270 
271     Configuration conf = new Configuration(util.getConfiguration());
272     ImportTsv.createSubmittableJob(conf, args);
273   }
274 
275   /**
276    * If there are invalid data rows as inputs, then only those rows should be ignored.
277    */
278   @Test
279   public void testTsvImporterTextMapperWithInvalidData() throws Exception {
280     String table = "test-" + UUID.randomUUID();
281     String FAMILY = "FAM";
282     Path bulkOutputPath = new Path(util.getDataTestDirOnTestFS(table), "hfiles");
283     // Prepare the arguments required for the test.
284     String[] args =
285         new String[] {
286             "-D" + ImportTsv.MAPPER_CONF_KEY
287                 + "=org.apache.hadoop.hbase.mapreduce.TsvImporterTextMapper",
288             "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,HBASE_TS_KEY,FAM:A,FAM:B",
289             "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=,",
290             "-D" + ImportTsv.BULK_OUTPUT_CONF_KEY + "=" + bulkOutputPath.toString(), table };
291     // 3 Rows of data as input. 2 Rows are valid and 1 row is invalid as it doesn't have TS
292     String data = "KEY,1234,VALUE1,VALUE2\nKEY\nKEY,1235,VALUE1,VALUE2\n";
293     doMROnTableTest(util, FAMILY, data, args, 1, 4);
294     util.deleteTable(table);
295   }
296 
297   protected static Tool doMROnTableTest(HBaseTestingUtility util, String family,
298       String data, String[] args) throws Exception {
299     return doMROnTableTest(util, family, data, args, 1);
300   }
301 
302   protected static Tool doMROnTableTest(HBaseTestingUtility util, String family, String data,
303       String[] args, int valueMultiplier) throws Exception {
304     return doMROnTableTest(util, family, data, args, valueMultiplier, -1);
305   }
306 
307   /**
308    * Run an ImportTsv job and perform basic validation on the results.
309    * Returns the ImportTsv <code>Tool</code> instance so that other tests can
310    * inspect it for further validation as necessary. This method is static to
311    * insure non-reliance on instance's util/conf facilities.
312    * @param args Any arguments to pass BEFORE inputFile path is appended.
313    * @return The Tool instance used to run the test.
314    */
315   protected static Tool doMROnTableTest(HBaseTestingUtility util, String family, String data,
316       String[] args, int valueMultiplier, int expectedKVCount)
317   throws Exception {
318     String table = args[args.length - 1];
319     Configuration conf = new Configuration(util.getConfiguration());
320 
321     // populate input file
322     FileSystem fs = FileSystem.get(conf);
323     Path inputPath = fs.makeQualified(new Path(util.getDataTestDirOnTestFS(table), "input.dat"));
324     FSDataOutputStream op = fs.create(inputPath, true);
325     if (data == null) {
326       data = "KEY\u001bVALUE1\u001bVALUE2\n";
327     }
328     op.write(Bytes.toBytes(data));
329     op.close();
330     LOG.debug(String.format("Wrote test data to file: %s", inputPath));
331 
332     if (conf.getBoolean(FORCE_COMBINER_CONF, true)) {
333       LOG.debug("Forcing combiner.");
334       conf.setInt("mapreduce.map.combine.minspills", 1);
335     }
336 
337     // run the import
338     List<String> argv = new ArrayList<String>(Arrays.asList(args));
339     argv.add(inputPath.toString());
340     Tool tool = new ImportTsv();
341     LOG.debug("Running ImportTsv with arguments: " + argv);
342     assertEquals(0, ToolRunner.run(conf, tool, argv.toArray(args)));
343 
344     // Perform basic validation. If the input args did not include
345     // ImportTsv.BULK_OUTPUT_CONF_KEY then validate data in the table.
346     // Otherwise, validate presence of hfiles.
347     boolean createdHFiles = false;
348     String outputPath = null;
349     for (String arg : argv) {
350       if (arg.contains(ImportTsv.BULK_OUTPUT_CONF_KEY)) {
351         createdHFiles = true;
352         // split '-Dfoo=bar' on '=' and keep 'bar'
353         outputPath = arg.split("=")[1];
354         break;
355       }
356     }
357 
358     if (createdHFiles)
359       validateHFiles(fs, outputPath, family, expectedKVCount);
360     else
361       validateTable(conf, TableName.valueOf(table), family, valueMultiplier);
362 
363     if (conf.getBoolean(DELETE_AFTER_LOAD_CONF, true)) {
364       LOG.debug("Deleting test subdirectory");
365       util.cleanupDataTestDirOnTestFS(table);
366     }
367     return tool;
368   }
369 
370   /**
371    * Confirm ImportTsv via data in online table.
372    */
373   private static void validateTable(Configuration conf, TableName tableName,
374       String family, int valueMultiplier) throws IOException {
375 
376     LOG.debug("Validating table.");
377     Table table = new HTable(conf, tableName);
378     boolean verified = false;
379     long pause = conf.getLong("hbase.client.pause", 5 * 1000);
380     int numRetries = conf.getInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
381     for (int i = 0; i < numRetries; i++) {
382       try {
383         Scan scan = new Scan();
384         // Scan entire family.
385         scan.addFamily(Bytes.toBytes(family));
386         ResultScanner resScanner = table.getScanner(scan);
387         for (Result res : resScanner) {
388           assertTrue(res.size() == 2);
389           List<Cell> kvs = res.listCells();
390           assertTrue(CellUtil.matchingRow(kvs.get(0), Bytes.toBytes("KEY")));
391           assertTrue(CellUtil.matchingRow(kvs.get(1), Bytes.toBytes("KEY")));
392           assertTrue(CellUtil.matchingValue(kvs.get(0), Bytes.toBytes("VALUE" + valueMultiplier)));
393           assertTrue(CellUtil.matchingValue(kvs.get(1), Bytes.toBytes("VALUE" + 2 * valueMultiplier)));
394           // Only one result set is expected, so let it loop.
395         }
396         verified = true;
397         break;
398       } catch (NullPointerException e) {
399         // If here, a cell was empty. Presume its because updates came in
400         // after the scanner had been opened. Wait a while and retry.
401       }
402       try {
403         Thread.sleep(pause);
404       } catch (InterruptedException e) {
405         // continue
406       }
407     }
408     table.close();
409     assertTrue(verified);
410   }
411 
412   /**
413    * Confirm ImportTsv via HFiles on fs.
414    */
415   private static void validateHFiles(FileSystem fs, String outputPath, String family,
416       int expectedKVCount) throws IOException {
417     // validate number and content of output columns
418     LOG.debug("Validating HFiles.");
419     Set<String> configFamilies = new HashSet<String>();
420     configFamilies.add(family);
421     Set<String> foundFamilies = new HashSet<String>();
422     int actualKVCount = 0;
423     for (FileStatus cfStatus : fs.listStatus(new Path(outputPath), new OutputFilesFilter())) {
424       String[] elements = cfStatus.getPath().toString().split(Path.SEPARATOR);
425       String cf = elements[elements.length - 1];
426       foundFamilies.add(cf);
427       assertTrue(
428         String.format(
429           "HFile output contains a column family (%s) not present in input families (%s)",
430           cf, configFamilies),
431           configFamilies.contains(cf));
432       for (FileStatus hfile : fs.listStatus(cfStatus.getPath())) {
433         assertTrue(
434           String.format("HFile %s appears to contain no data.", hfile.getPath()),
435           hfile.getLen() > 0);
436         // count the number of KVs from all the hfiles
437         if (expectedKVCount > -1) {
438           actualKVCount += getKVCountFromHfile(fs, hfile.getPath());
439         }
440       }
441     }
442     if (expectedKVCount > -1) {
443       assertTrue(String.format(
444         "KV count in output hfile=<%d> doesn't match with expected KV count=<%d>", actualKVCount,
445         expectedKVCount), actualKVCount == expectedKVCount);
446     }
447   }
448 
449   /**
450    * Method returns the total KVs in given hfile
451    * @param fs File System
452    * @param p HFile path
453    * @return KV count in the given hfile
454    * @throws IOException
455    */
456   private static int getKVCountFromHfile(FileSystem fs, Path p) throws IOException {
457     Configuration conf = util.getConfiguration();
458     HFile.Reader reader = HFile.createReader(fs, p, new CacheConfig(conf), conf);
459     reader.loadFileInfo();
460     HFileScanner scanner = reader.getScanner(false, false);
461     scanner.seekTo();
462     int count = 0;
463     do {
464       count++;
465     } while (scanner.next());
466     reader.close();
467     return count;
468   }
469 }
470