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 java.lang.String.format;
22  
23  import java.io.IOException;
24  import java.util.ArrayList;
25  import java.util.HashSet;
26  import java.util.Set;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.classification.InterfaceAudience;
31  import org.apache.hadoop.classification.InterfaceStability;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.conf.Configured;
34  import org.apache.hadoop.fs.Path;
35  import org.apache.hadoop.hbase.HBaseConfiguration;
36  import org.apache.hadoop.hbase.HColumnDescriptor;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.HTableDescriptor;
39  import org.apache.hadoop.hbase.TableName;
40  import org.apache.hadoop.hbase.client.HBaseAdmin;
41  import org.apache.hadoop.hbase.client.HTable;
42  import org.apache.hadoop.hbase.client.Put;
43  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
44  import org.apache.hadoop.hbase.util.Base64;
45  import org.apache.hadoop.hbase.util.Bytes;
46  import org.apache.hadoop.hbase.util.Pair;
47  import org.apache.hadoop.io.Text;
48  import org.apache.hadoop.mapreduce.Job;
49  import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
50  import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
51  import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
52  import org.apache.hadoop.util.GenericOptionsParser;
53  import org.apache.hadoop.util.Tool;
54  import org.apache.hadoop.util.ToolRunner;
55  
56  import com.google.common.base.Preconditions;
57  import com.google.common.base.Splitter;
58  import com.google.common.collect.Lists;
59  
60  /**
61   * Tool to import data from a TSV file.
62   *
63   * This tool is rather simplistic - it doesn't do any quoting or
64   * escaping, but is useful for many data loads.
65   *
66   * @see ImportTsv#usage(String)
67   */
68  @InterfaceAudience.Public
69  @InterfaceStability.Stable
70  public class ImportTsv extends Configured implements Tool {
71  
72    protected static final Log LOG = LogFactory.getLog(ImportTsv.class);
73  
74    final static String NAME = "importtsv";
75  
76    public final static String MAPPER_CONF_KEY = "importtsv.mapper.class";
77    public final static String BULK_OUTPUT_CONF_KEY = "importtsv.bulk.output";
78    public final static String TIMESTAMP_CONF_KEY = "importtsv.timestamp";
79    public final static String JOB_NAME_CONF_KEY = "mapred.job.name";
80    // TODO: the rest of these configs are used exclusively by TsvImporterMapper.
81    // Move them out of the tool and let the mapper handle its own validation.
82    public final static String SKIP_LINES_CONF_KEY = "importtsv.skip.bad.lines";
83    public final static String COLUMNS_CONF_KEY = "importtsv.columns";
84    public final static String SEPARATOR_CONF_KEY = "importtsv.separator";
85  
86    final static String DEFAULT_SEPARATOR = "\t";
87    final static Class DEFAULT_MAPPER = TsvImporterMapper.class;
88  
89    public static class TsvParser {
90      /**
91       * Column families and qualifiers mapped to the TSV columns
92       */
93      private final byte[][] families;
94      private final byte[][] qualifiers;
95  
96      private final byte separatorByte;
97  
98      private int rowKeyColumnIndex;
99  
100     private int maxColumnCount;
101 
102     // Default value must be negative
103     public static final int DEFAULT_TIMESTAMP_COLUMN_INDEX = -1;
104 
105     private int timestampKeyColumnIndex = DEFAULT_TIMESTAMP_COLUMN_INDEX;
106 
107     public static final String ROWKEY_COLUMN_SPEC = "HBASE_ROW_KEY";
108 
109     public static final String TIMESTAMPKEY_COLUMN_SPEC = "HBASE_TS_KEY";
110 
111     /**
112      * @param columnsSpecification the list of columns to parser out, comma separated.
113      * The row key should be the special token TsvParser.ROWKEY_COLUMN_SPEC
114      */
115     public TsvParser(String columnsSpecification, String separatorStr) {
116       // Configure separator
117       byte[] separator = Bytes.toBytes(separatorStr);
118       Preconditions.checkArgument(separator.length == 1,
119         "TsvParser only supports single-byte separators");
120       separatorByte = separator[0];
121 
122       // Configure columns
123       ArrayList<String> columnStrings = Lists.newArrayList(
124         Splitter.on(',').trimResults().split(columnsSpecification));
125 
126       maxColumnCount = columnStrings.size();
127       families = new byte[maxColumnCount][];
128       qualifiers = new byte[maxColumnCount][];
129 
130       for (int i = 0; i < columnStrings.size(); i++) {
131         String str = columnStrings.get(i);
132         if (ROWKEY_COLUMN_SPEC.equals(str)) {
133           rowKeyColumnIndex = i;
134           continue;
135         }
136         
137         if (TIMESTAMPKEY_COLUMN_SPEC.equals(str)) {
138           timestampKeyColumnIndex = i;
139           continue;
140         }
141         
142         String[] parts = str.split(":", 2);
143         if (parts.length == 1) {
144           families[i] = str.getBytes();
145           qualifiers[i] = HConstants.EMPTY_BYTE_ARRAY;
146         } else {
147           families[i] = parts[0].getBytes();
148           qualifiers[i] = parts[1].getBytes();
149         }
150       }
151     }
152 
153     public boolean hasTimestamp() {
154       return timestampKeyColumnIndex != DEFAULT_TIMESTAMP_COLUMN_INDEX;
155     }
156 
157     public int getTimestampKeyColumnIndex() {
158       return timestampKeyColumnIndex;
159     }
160 
161     public int getRowKeyColumnIndex() {
162       return rowKeyColumnIndex;
163     }
164     public byte[] getFamily(int idx) {
165       return families[idx];
166     }
167     public byte[] getQualifier(int idx) {
168       return qualifiers[idx];
169     }
170 
171     public ParsedLine parse(byte[] lineBytes, int length)
172     throws BadTsvLineException {
173       // Enumerate separator offsets
174       ArrayList<Integer> tabOffsets = new ArrayList<Integer>(maxColumnCount);
175       for (int i = 0; i < length; i++) {
176         if (lineBytes[i] == separatorByte) {
177           tabOffsets.add(i);
178         }
179       }
180       if (tabOffsets.isEmpty()) {
181         throw new BadTsvLineException("No delimiter");
182       }
183 
184       tabOffsets.add(length);
185 
186       if (tabOffsets.size() > maxColumnCount) {
187         throw new BadTsvLineException("Excessive columns");
188       } else if (tabOffsets.size() <= getRowKeyColumnIndex()) {
189         throw new BadTsvLineException("No row key");
190       } else if (hasTimestamp()
191           && tabOffsets.size() <= getTimestampKeyColumnIndex()) {
192         throw new BadTsvLineException("No timestamp");
193       }
194       return new ParsedLine(tabOffsets, lineBytes);
195     }
196 
197     class ParsedLine {
198       private final ArrayList<Integer> tabOffsets;
199       private byte[] lineBytes;
200 
201       ParsedLine(ArrayList<Integer> tabOffsets, byte[] lineBytes) {
202         this.tabOffsets = tabOffsets;
203         this.lineBytes = lineBytes;
204       }
205 
206       public int getRowKeyOffset() {
207         return getColumnOffset(rowKeyColumnIndex);
208       }
209       public int getRowKeyLength() {
210         return getColumnLength(rowKeyColumnIndex);
211       }
212       
213       public long getTimestamp(long ts) throws BadTsvLineException {
214         // Return ts if HBASE_TS_KEY is not configured in column spec
215         if (!hasTimestamp()) {
216           return ts;
217         }
218 
219         String timeStampStr = Bytes.toString(lineBytes,
220             getColumnOffset(timestampKeyColumnIndex),
221             getColumnLength(timestampKeyColumnIndex));
222         try {
223           return Long.parseLong(timeStampStr);
224         } catch (NumberFormatException nfe) {
225           // treat this record as bad record
226           throw new BadTsvLineException("Invalid timestamp " + timeStampStr);
227         }
228       }
229       
230       public int getColumnOffset(int idx) {
231         if (idx > 0)
232           return tabOffsets.get(idx - 1) + 1;
233         else
234           return 0;
235       }
236       public int getColumnLength(int idx) {
237         return tabOffsets.get(idx) - getColumnOffset(idx);
238       }
239       public int getColumnCount() {
240         return tabOffsets.size();
241       }
242       public byte[] getLineBytes() {
243         return lineBytes;
244       }
245     }
246 
247     public static class BadTsvLineException extends Exception {
248       public BadTsvLineException(String err) {
249         super(err);
250       }
251       private static final long serialVersionUID = 1L;
252     }
253 
254     public Pair<Integer, Integer> parseRowKey(byte[] lineBytes, int length)
255         throws BadTsvLineException {
256       int rkColumnIndex = 0;
257       int startPos = 0, endPos = 0;
258       for (int i = 0; i <= length; i++) {
259         if (i == length || lineBytes[i] == separatorByte) {
260           endPos = i - 1;
261           if (rkColumnIndex++ == getRowKeyColumnIndex()) {
262             if ((endPos + 1) == startPos) {
263               throw new BadTsvLineException("Empty value for ROW KEY.");
264             }
265             break;
266           } else {
267             startPos = endPos + 2;
268           }
269         }
270         if (i == length) {
271           throw new BadTsvLineException(
272               "Row key does not exist as number of columns in the line"
273                   + " are less than row key position.");
274         }
275       }
276       return new Pair<Integer, Integer>(startPos, endPos);
277     }
278   }
279 
280   /**
281    * Sets up the actual job.
282    *
283    * @param conf  The current configuration.
284    * @param args  The command line parameters.
285    * @return The newly created job.
286    * @throws IOException When setting up the job fails.
287    */
288   public static Job createSubmittableJob(Configuration conf, String[] args)
289       throws IOException, ClassNotFoundException {
290 
291     HBaseAdmin admin = new HBaseAdmin(conf);
292 
293     // Support non-XML supported characters
294     // by re-encoding the passed separator as a Base64 string.
295     String actualSeparator = conf.get(SEPARATOR_CONF_KEY);
296     if (actualSeparator != null) {
297       conf.set(SEPARATOR_CONF_KEY,
298                Base64.encodeBytes(actualSeparator.getBytes()));
299     }
300 
301     // See if a non-default Mapper was set
302     String mapperClassName = conf.get(MAPPER_CONF_KEY);
303     Class mapperClass = mapperClassName != null ?
304         Class.forName(mapperClassName) : DEFAULT_MAPPER;
305 
306     String tableName = args[0];
307     Path inputDir = new Path(args[1]);
308     String jobName = conf.get(JOB_NAME_CONF_KEY,NAME + "_" + tableName);
309     Job job = new Job(conf, jobName);
310     job.setJarByClass(mapperClass);
311     FileInputFormat.setInputPaths(job, inputDir);
312     job.setInputFormatClass(TextInputFormat.class);
313     job.setMapperClass(mapperClass);
314 
315     String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);
316     String columns[] = conf.getStrings(COLUMNS_CONF_KEY);
317     if (hfileOutPath != null) {
318       if (!admin.tableExists(tableName)) {
319         LOG.warn(format("Table '%s' does not exist.", tableName));
320         // TODO: this is backwards. Instead of depending on the existence of a table,
321         // create a sane splits file for HFileOutputFormat based on data sampling.
322         createTable(admin, tableName, columns);
323       }
324       HTable table = new HTable(conf, tableName);
325       job.setReducerClass(PutSortReducer.class);
326       Path outputDir = new Path(hfileOutPath);
327       FileOutputFormat.setOutputPath(job, outputDir);
328       job.setMapOutputKeyClass(ImmutableBytesWritable.class);
329       if (mapperClass.equals(TsvImporterTextMapper.class)) {
330         job.setMapOutputValueClass(Text.class);
331         job.setReducerClass(TextSortReducer.class);
332       } else {
333         job.setMapOutputValueClass(Put.class);
334         job.setCombinerClass(PutCombiner.class);
335       }
336       HFileOutputFormat.configureIncrementalLoad(job, table);
337     } else {
338       if (mapperClass.equals(TsvImporterTextMapper.class)) {
339         usage(TsvImporterTextMapper.class.toString()
340             + " should not be used for non bulkloading case. use "
341             + TsvImporterMapper.class.toString()
342             + " or custom mapper whose value type is Put.");
343         System.exit(-1);
344       }
345       // No reducers. Just write straight to table. Call initTableReducerJob
346       // to set up the TableOutputFormat.
347       TableMapReduceUtil.initTableReducerJob(tableName, null, job);
348       job.setNumReduceTasks(0);
349     }
350 
351     TableMapReduceUtil.addDependencyJars(job);
352     TableMapReduceUtil.addDependencyJars(job.getConfiguration(),
353         com.google.common.base.Function.class /* Guava used by TsvParser */);
354     return job;
355   }
356 
357   private static void createTable(HBaseAdmin admin, String tableName, String[] columns)
358       throws IOException {
359     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName));
360     Set<String> cfSet = new HashSet<String>();
361     for (String aColumn : columns) {
362       if (TsvParser.ROWKEY_COLUMN_SPEC.equals(aColumn)
363           || TsvParser.TIMESTAMPKEY_COLUMN_SPEC.equals(aColumn)) continue;
364       // we are only concerned with the first one (in case this is a cf:cq)
365       cfSet.add(aColumn.split(":", 2)[0]);
366     }
367     for (String cf : cfSet) {
368       HColumnDescriptor hcd = new HColumnDescriptor(Bytes.toBytes(cf));
369       htd.addFamily(hcd);
370     }
371     LOG.warn(format("Creating table '%s' with '%s' columns and default descriptors.",
372       tableName, cfSet));
373     admin.createTable(htd);
374   }
375 
376   /*
377    * @param errorMsg Error message.  Can be null.
378    */
379   private static void usage(final String errorMsg) {
380     if (errorMsg != null && errorMsg.length() > 0) {
381       System.err.println("ERROR: " + errorMsg);
382     }
383     String usage = 
384       "Usage: " + NAME + " -D"+ COLUMNS_CONF_KEY + "=a,b,c <tablename> <inputdir>\n" +
385       "\n" +
386       "Imports the given input directory of TSV data into the specified table.\n" +
387       "\n" +
388       "The column names of the TSV data must be specified using the -D" + COLUMNS_CONF_KEY + "\n" +
389       "option. This option takes the form of comma-separated column names, where each\n" +
390       "column name is either a simple column family, or a columnfamily:qualifier. The special\n" +
391       "column name " + TsvParser.ROWKEY_COLUMN_SPEC + " is used to designate that this column should be used\n" +
392       "as the row key for each imported record. You must specify exactly one column\n" +
393       "to be the row key, and you must specify a column name for every column that exists in the\n" +
394       "input data. Another special column" + TsvParser.TIMESTAMPKEY_COLUMN_SPEC +
395       " designates that this column should be\n" +
396       "used as timestamp for each record. Unlike " + TsvParser.ROWKEY_COLUMN_SPEC + ", " +
397       TsvParser.TIMESTAMPKEY_COLUMN_SPEC + " is optional.\n" +
398       "You must specify at most one column as timestamp key for each imported record.\n" +
399       "Record with invalid timestamps (blank, non-numeric) will be treated as bad record.\n" +
400       "Note: if you use this option, then '" + TIMESTAMP_CONF_KEY + "' option will be ignored.\n" +
401       "\n" +
402       "By default importtsv will load data directly into HBase. To instead generate\n" +
403       "HFiles of data to prepare for a bulk data load, pass the option:\n" +
404       "  -D" + BULK_OUTPUT_CONF_KEY + "=/path/for/output\n" +
405       "  Note: if you do not use this option, then the target table must already exist in HBase\n" +
406       "\n" +
407       "Other options that may be specified with -D include:\n" +
408       "  -D" + SKIP_LINES_CONF_KEY + "=false - fail if encountering an invalid line\n" +
409       "  '-D" + SEPARATOR_CONF_KEY + "=|' - eg separate on pipes instead of tabs\n" +
410       "  -D" + TIMESTAMP_CONF_KEY + "=currentTimeAsLong - use the specified timestamp for the import\n" +
411       "  -D" + MAPPER_CONF_KEY + "=my.Mapper - A user-defined Mapper to use instead of " +
412       DEFAULT_MAPPER.getName() + "\n" +
413       "  -D" + JOB_NAME_CONF_KEY + "=jobName - use the specified mapreduce job name for the import\n" +
414       "For performance consider the following options:\n" +
415       "  -Dmapred.map.tasks.speculative.execution=false\n" +
416       "  -Dmapred.reduce.tasks.speculative.execution=false";
417 
418     System.err.println(usage);
419   }
420 
421   @Override
422   public int run(String[] args) throws Exception {
423     setConf(HBaseConfiguration.create(getConf()));
424     String[] otherArgs = new GenericOptionsParser(getConf(), args).getRemainingArgs();
425     if (otherArgs.length < 2) {
426       usage("Wrong number of arguments: " + otherArgs.length);
427       return -1;
428     }
429 
430     // When MAPPER_CONF_KEY is null, the user wants to use the provided TsvImporterMapper, so
431     // perform validation on these additional args. When it's not null, user has provided their
432     // own mapper, thus these validation are not relevant.
433     // TODO: validation for TsvImporterMapper, not this tool. Move elsewhere.
434     if (null == getConf().get(MAPPER_CONF_KEY)) {
435       // Make sure columns are specified
436       String columns[] = getConf().getStrings(COLUMNS_CONF_KEY);
437       if (columns == null) {
438         usage("No columns specified. Please specify with -D" +
439             COLUMNS_CONF_KEY+"=...");
440         return -1;
441       }
442 
443       // Make sure they specify exactly one column as the row key
444       int rowkeysFound = 0;
445       for (String col : columns) {
446         if (col.equals(TsvParser.ROWKEY_COLUMN_SPEC)) rowkeysFound++;
447       }
448       if (rowkeysFound != 1) {
449         usage("Must specify exactly one column as " + TsvParser.ROWKEY_COLUMN_SPEC);
450         return -1;
451       }
452 
453       // Make sure we have at most one column as the timestamp key
454       int tskeysFound = 0;
455       for (String col : columns) {
456         if (col.equals(TsvParser.TIMESTAMPKEY_COLUMN_SPEC))
457           tskeysFound++;
458       }
459       if (tskeysFound > 1) {
460         usage("Must specify at most one column as "
461             + TsvParser.TIMESTAMPKEY_COLUMN_SPEC);
462         return -1;
463       }
464     
465       // Make sure one or more columns are specified excluding rowkey and
466       // timestamp key
467       if (columns.length - (rowkeysFound + tskeysFound) < 1) {
468         usage("One or more columns in addition to the row key and timestamp(optional) are required");
469         return -1;
470       }
471     }
472 
473     // If timestamp option is not specified, use current system time.
474     long timstamp = getConf().getLong(TIMESTAMP_CONF_KEY, System.currentTimeMillis());
475 
476     // Set it back to replace invalid timestamp (non-numeric) with current
477     // system time
478     getConf().setLong(TIMESTAMP_CONF_KEY, timstamp);
479     
480     Job job = createSubmittableJob(getConf(), otherArgs);
481     return job.waitForCompletion(true) ? 0 : 1;
482   }
483 
484   public static void main(String[] args) throws Exception {
485     int status = ToolRunner.run(new ImportTsv(), args);
486     System.exit(status);
487   }
488 }