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