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 java.io.ByteArrayInputStream;
22  import java.io.DataInput;
23  import java.io.DataInputStream;
24  import java.io.DataOutput;
25  import java.io.IOException;
26  import java.lang.reflect.InvocationTargetException;
27  import java.lang.reflect.Method;
28  import java.util.ArrayList;
29  import java.util.Collections;
30  import java.util.List;
31  import java.util.Map;
32  import java.util.TreeMap;
33  import java.util.UUID;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.conf.Configuration;
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.CellComparator;
42  import org.apache.hadoop.hbase.CellUtil;
43  import org.apache.hadoop.hbase.HBaseConfiguration;
44  import org.apache.hadoop.hbase.KeyValue;
45  import org.apache.hadoop.hbase.KeyValueUtil;
46  import org.apache.hadoop.hbase.TableName;
47  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
48  import org.apache.hadoop.hbase.classification.InterfaceAudience;
49  import org.apache.hadoop.hbase.classification.InterfaceStability;
50  import org.apache.hadoop.hbase.client.Connection;
51  import org.apache.hadoop.hbase.client.ConnectionFactory;
52  import org.apache.hadoop.hbase.client.Delete;
53  import org.apache.hadoop.hbase.client.Durability;
54  import org.apache.hadoop.hbase.client.HBaseAdmin;
55  import org.apache.hadoop.hbase.client.Mutation;
56  import org.apache.hadoop.hbase.client.Put;
57  import org.apache.hadoop.hbase.client.RegionLocator;
58  import org.apache.hadoop.hbase.client.Result;
59  import org.apache.hadoop.hbase.client.Table;
60  import org.apache.hadoop.hbase.filter.Filter;
61  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
62  import org.apache.hadoop.hbase.util.Bytes;
63  import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
64  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
65  import org.apache.hadoop.io.RawComparator;
66  import org.apache.hadoop.io.WritableComparable;
67  import org.apache.hadoop.io.WritableComparator;
68  import org.apache.hadoop.mapreduce.Job;
69  import org.apache.hadoop.mapreduce.Partitioner;
70  import org.apache.hadoop.mapreduce.Reducer;
71  import org.apache.hadoop.mapreduce.TaskCounter;
72  import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
73  import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
74  import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
75  import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
76  import org.apache.hadoop.util.GenericOptionsParser;
77  import org.apache.zookeeper.KeeperException;
78  
79  
80  /**
81   * Import data written by {@link Export}.
82   */
83  @InterfaceAudience.Public
84  @InterfaceStability.Stable
85  public class Import {
86    private static final Log LOG = LogFactory.getLog(Import.class);
87    final static String NAME = "import";
88    public final static String CF_RENAME_PROP = "HBASE_IMPORTER_RENAME_CFS";
89    public final static String BULK_OUTPUT_CONF_KEY = "import.bulk.output";
90    public final static String FILTER_CLASS_CONF_KEY = "import.filter.class";
91    public final static String FILTER_ARGS_CONF_KEY = "import.filter.args";
92    public final static String TABLE_NAME = "import.table.name";
93    public final static String WAL_DURABILITY = "import.wal.durability";
94    public final static String HAS_LARGE_RESULT= "import.bulk.hasLargeResult";
95  
96    public static class KeyValueWritableComparablePartitioner 
97        extends Partitioner<KeyValueWritableComparable, KeyValue> {
98      private static KeyValueWritableComparable[] START_KEYS = null;
99      @Override
100     public int getPartition(KeyValueWritableComparable key, KeyValue value,
101         int numPartitions) {
102       for (int i = 0; i < START_KEYS.length; ++i) {
103         if (key.compareTo(START_KEYS[i]) <= 0) {
104           return i;
105         }
106       }
107       return START_KEYS.length;
108     }
109   
110   }
111   
112   public static class KeyValueWritableComparable 
113       implements WritableComparable<KeyValueWritableComparable> {
114     
115     private KeyValue kv = null;
116     private CellComparator cellComparator = new CellComparator();
117     
118     static {                                       
119       // register this comparator
120       WritableComparator.define(KeyValueWritableComparable.class, 
121           new KeyValueWritableComparator());
122     }
123     
124     public KeyValueWritableComparable() {
125     }
126     
127     public KeyValueWritableComparable(KeyValue kv) {
128       this.kv = kv;
129     }
130     
131     @Override
132     public void write(DataOutput out) throws IOException {
133       KeyValue.write(kv, out);
134     }
135     
136     @Override
137     public void readFields(DataInput in) throws IOException {
138       kv = KeyValue.create(in);
139     }
140     
141     @Override
142     @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="EQ_COMPARETO_USE_OBJECT_EQUALS",
143       justification="This is wrong, yes, but we should be purging Writables, not fixing them")
144     public int compareTo(KeyValueWritableComparable o) {
145       return cellComparator.compare(this.kv, ((KeyValueWritableComparable)o).kv);
146     }
147     
148     public static class KeyValueWritableComparator extends WritableComparator {
149     
150       @Override
151       public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
152         try {
153           KeyValueWritableComparable kv1 = new KeyValueWritableComparable();
154           kv1.readFields(new DataInputStream(new ByteArrayInputStream(b1, s1, l1)));
155           KeyValueWritableComparable kv2 = new KeyValueWritableComparable();
156           kv2.readFields(new DataInputStream(new ByteArrayInputStream(b2, s2, l2)));
157           return compare(kv1, kv2);
158         } catch (IOException e) {
159           throw new RuntimeException(e);
160         } 
161       }
162       
163     }
164   
165   }
166   
167   public static class KeyValueReducer
168       extends
169       Reducer<KeyValueWritableComparable, KeyValue, ImmutableBytesWritable, KeyValue> {
170     protected void reduce(
171         KeyValueWritableComparable row,
172         Iterable<KeyValue> kvs,
173         Reducer<KeyValueWritableComparable,
174           KeyValue, ImmutableBytesWritable, KeyValue>.Context context)
175         throws java.io.IOException, InterruptedException {
176       int index = 0;
177       for (KeyValue kv : kvs) {
178         context.write(new ImmutableBytesWritable(kv.getRowArray()), kv);
179         if (++index % 100 == 0)
180           context.setStatus("Wrote " + index + " KeyValues, "
181               + "and the rowkey whose is being wrote is " + Bytes.toString(kv.getRowArray())); 
182       }
183     }
184   }
185   
186   public static class KeyValueSortImporter 
187       extends TableMapper<KeyValueWritableComparable, KeyValue> {
188     private Map<byte[], byte[]> cfRenameMap;
189     private Filter filter;
190     private static final Log LOG = LogFactory.getLog(KeyValueImporter.class);
191     
192     /**
193      * @param row  The current table row key.
194      * @param value  The columns.
195      * @param context  The current context.
196      * @throws IOException When something is broken with the data.
197      */
198     @Override
199     public void map(ImmutableBytesWritable row, Result value, Context context) 
200         throws IOException {
201       try {
202         if (LOG.isTraceEnabled()) {
203           LOG.trace("Considering the row."
204               + Bytes.toString(row.get(), row.getOffset(), row.getLength()));
205         }
206         if (filter == null || !filter.filterRowKey(row.get(), row.getOffset(), row.getLength())) {
207           for (Cell kv : value.rawCells()) {
208             kv = filterKv(filter, kv);
209             // skip if we filtered it out
210             if (kv == null) continue;
211             // TODO get rid of ensureKeyValue
212             KeyValue ret = KeyValueUtil.ensureKeyValueTypeForMR(convertKv(kv, cfRenameMap));
213             context.write(new KeyValueWritableComparable(ret.createKeyOnly(false)), ret); 
214           }
215         }
216       } catch (InterruptedException e) {
217         e.printStackTrace();
218       }
219     }
220     
221     @Override
222     public void setup(Context context) throws IOException { 
223       cfRenameMap = createCfRenameMap(context.getConfiguration());
224       filter = instantiateFilter(context.getConfiguration());
225       int reduceNum = context.getNumReduceTasks();
226       Configuration conf = context.getConfiguration();
227       TableName tableName = TableName.valueOf(context.getConfiguration().get(TABLE_NAME));
228       try (Connection conn = ConnectionFactory.createConnection(conf); 
229           RegionLocator regionLocator = conn.getRegionLocator(tableName)) {
230         byte[][] startKeys = regionLocator.getStartKeys();
231         if (startKeys.length != reduceNum) {
232           throw new IOException("Region split after job initialization");
233         }
234         KeyValueWritableComparable[] startKeyWraps = 
235             new KeyValueWritableComparable[startKeys.length - 1];
236         for (int i = 1; i < startKeys.length; ++i) {
237           startKeyWraps[i - 1] = 
238               new KeyValueWritableComparable(KeyValueUtil.createFirstOnRow(startKeys[i]));
239         }
240         KeyValueWritableComparablePartitioner.START_KEYS = startKeyWraps;
241       }
242     }
243   }
244 
245   
246   /**
247    * A mapper that just writes out KeyValues.
248    */
249   @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="EQ_COMPARETO_USE_OBJECT_EQUALS",
250       justification="Writables are going away and this has been this way forever")
251   public static class KeyValueImporter extends TableMapper<ImmutableBytesWritable, KeyValue> {
252     private Map<byte[], byte[]> cfRenameMap;
253     private Filter filter;
254     private static final Log LOG = LogFactory.getLog(KeyValueImporter.class);
255 
256     /**
257      * @param row  The current table row key.
258      * @param value  The columns.
259      * @param context  The current context.
260      * @throws IOException When something is broken with the data.
261      */
262     @Override
263     public void map(ImmutableBytesWritable row, Result value,
264       Context context)
265     throws IOException {
266       try {
267         if (LOG.isTraceEnabled()) {
268           LOG.trace("Considering the row."
269               + Bytes.toString(row.get(), row.getOffset(), row.getLength()));
270         }
271         if (filter == null || !filter.filterRowKey(row.get(), row.getOffset(), row.getLength())) {
272           for (Cell kv : value.rawCells()) {
273             kv = filterKv(filter, kv);
274             // skip if we filtered it out
275             if (kv == null) continue;
276             // TODO get rid of ensureKeyValue
277             context.write(row, KeyValueUtil.ensureKeyValueTypeForMR(convertKv(kv, cfRenameMap)));
278           }
279         }
280       } catch (InterruptedException e) {
281         e.printStackTrace();
282       }
283     }
284 
285     @Override
286     public void setup(Context context) {
287       cfRenameMap = createCfRenameMap(context.getConfiguration());
288       filter = instantiateFilter(context.getConfiguration());
289     }
290   }
291 
292   /**
293    * Write table content out to files in hdfs.
294    */
295   public static class Importer extends TableMapper<ImmutableBytesWritable, Mutation> {
296     private Map<byte[], byte[]> cfRenameMap;
297     private List<UUID> clusterIds;
298     private Filter filter;
299     private Durability durability;
300 
301     /**
302      * @param row  The current table row key.
303      * @param value  The columns.
304      * @param context  The current context.
305      * @throws IOException When something is broken with the data.
306      */
307     @Override
308     public void map(ImmutableBytesWritable row, Result value,
309       Context context)
310     throws IOException {
311       try {
312         writeResult(row, value, context);
313       } catch (InterruptedException e) {
314         e.printStackTrace();
315       }
316     }
317 
318     private void writeResult(ImmutableBytesWritable key, Result result, Context context)
319     throws IOException, InterruptedException {
320       Put put = null;
321       Delete delete = null;
322       if (LOG.isTraceEnabled()) {
323         LOG.trace("Considering the row."
324             + Bytes.toString(key.get(), key.getOffset(), key.getLength()));
325       }
326       if (filter == null || !filter.filterRowKey(key.get(), key.getOffset(), key.getLength())) {
327         processKV(key, result, context, put, delete);
328       }
329     }
330 
331     protected void processKV(ImmutableBytesWritable key, Result result, Context context, Put put,
332         Delete delete) throws IOException, InterruptedException {
333       for (Cell kv : result.rawCells()) {
334         kv = filterKv(filter, kv);
335         // skip if we filter it out
336         if (kv == null) continue;
337 
338         kv = convertKv(kv, cfRenameMap);
339         // Deletes and Puts are gathered and written when finished
340         /*
341          * If there are sequence of mutations and tombstones in an Export, and after Import the same
342          * sequence should be restored as it is. If we combine all Delete tombstones into single
343          * request then there is chance of ignoring few DeleteFamily tombstones, because if we
344          * submit multiple DeleteFamily tombstones in single Delete request then we are maintaining
345          * only newest in hbase table and ignoring other. Check - HBASE-12065
346          */
347         if (CellUtil.isDeleteFamily(kv)) {
348           Delete deleteFamily = new Delete(key.get());
349           deleteFamily.addDeleteMarker(kv);
350           if (durability != null) {
351             deleteFamily.setDurability(durability);
352           }
353           deleteFamily.setClusterIds(clusterIds);
354           context.write(key, deleteFamily);
355         } else if (CellUtil.isDelete(kv)) {
356           if (delete == null) {
357             delete = new Delete(key.get());
358           }
359           delete.addDeleteMarker(kv);
360         } else {
361           if (put == null) {
362             put = new Put(key.get());
363           }
364           addPutToKv(put, kv);
365         }
366       }
367       if (put != null) {
368         if (durability != null) {
369           put.setDurability(durability);
370         }
371         put.setClusterIds(clusterIds);
372         context.write(key, put);
373       }
374       if (delete != null) {
375         if (durability != null) {
376           delete.setDurability(durability);
377         }
378         delete.setClusterIds(clusterIds);
379         context.write(key, delete);
380       }
381     }
382 
383     protected void addPutToKv(Put put, Cell kv) throws IOException {
384       put.add(kv);
385     }
386 
387     @Override
388     public void setup(Context context) {
389       Configuration conf = context.getConfiguration();
390       cfRenameMap = createCfRenameMap(conf);
391       filter = instantiateFilter(conf);
392       String durabilityStr = conf.get(WAL_DURABILITY);
393       if(durabilityStr != null){
394         durability = Durability.valueOf(durabilityStr.toUpperCase());
395       }
396       // TODO: This is kind of ugly doing setup of ZKW just to read the clusterid.
397       ZooKeeperWatcher zkw = null;
398       Exception ex = null;
399       try {
400         zkw = new ZooKeeperWatcher(conf, context.getTaskAttemptID().toString(), null);
401         clusterIds = Collections.singletonList(ZKClusterId.getUUIDForCluster(zkw));
402       } catch (ZooKeeperConnectionException e) {
403         ex = e;
404         LOG.error("Problem connecting to ZooKeper during task setup", e);
405       } catch (KeeperException e) {
406         ex = e;
407         LOG.error("Problem reading ZooKeeper data during task setup", e);
408       } catch (IOException e) {
409         ex = e;
410         LOG.error("Problem setting up task", e);
411       } finally {
412         if (zkw != null) zkw.close();
413       }
414       if (clusterIds == null) {
415         // exit early if setup fails
416         throw new RuntimeException(ex);
417       }
418     }
419   }
420 
421   /**
422    * Create a {@link Filter} to apply to all incoming keys ({@link KeyValue KeyValues}) to
423    * optionally not include in the job output
424    * @param conf {@link Configuration} from which to load the filter
425    * @return the filter to use for the task, or <tt>null</tt> if no filter to should be used
426    * @throws IllegalArgumentException if the filter is misconfigured
427    */
428   public static Filter instantiateFilter(Configuration conf) {
429     // get the filter, if it was configured    
430     Class<? extends Filter> filterClass = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
431     if (filterClass == null) {
432       LOG.debug("No configured filter class, accepting all keyvalues.");
433       return null;
434     }
435     LOG.debug("Attempting to create filter:" + filterClass);
436     String[] filterArgs = conf.getStrings(FILTER_ARGS_CONF_KEY);
437     ArrayList<byte[]> quotedArgs = toQuotedByteArrays(filterArgs);
438     try {
439       Method m = filterClass.getMethod("createFilterFromArguments", ArrayList.class);
440       return (Filter) m.invoke(null, quotedArgs);
441     } catch (IllegalAccessException e) {
442       LOG.error("Couldn't instantiate filter!", e);
443       throw new RuntimeException(e);
444     } catch (SecurityException e) {
445       LOG.error("Couldn't instantiate filter!", e);
446       throw new RuntimeException(e);
447     } catch (NoSuchMethodException e) {
448       LOG.error("Couldn't instantiate filter!", e);
449       throw new RuntimeException(e);
450     } catch (IllegalArgumentException e) {
451       LOG.error("Couldn't instantiate filter!", e);
452       throw new RuntimeException(e);
453     } catch (InvocationTargetException e) {
454       LOG.error("Couldn't instantiate filter!", e);
455       throw new RuntimeException(e);
456     }
457   }
458 
459   private static ArrayList<byte[]> toQuotedByteArrays(String... stringArgs) {
460     ArrayList<byte[]> quotedArgs = new ArrayList<byte[]>();
461     for (String stringArg : stringArgs) {
462       // all the filters' instantiation methods expected quoted args since they are coming from
463       // the shell, so add them here, though it shouldn't really be needed :-/
464       quotedArgs.add(Bytes.toBytes("'" + stringArg + "'"));
465     }
466     return quotedArgs;
467   }
468 
469   /**
470    * Attempt to filter out the keyvalue
471    * @param kv {@link KeyValue} on which to apply the filter
472    * @return <tt>null</tt> if the key should not be written, otherwise returns the original
473    *         {@link KeyValue}
474    */
475   public static Cell filterKv(Filter filter, Cell kv) throws IOException {
476     // apply the filter and skip this kv if the filter doesn't apply
477     if (filter != null) {
478       Filter.ReturnCode code = filter.filterKeyValue(kv);
479       if (LOG.isTraceEnabled()) {
480         LOG.trace("Filter returned:" + code + " for the key value:" + kv);
481       }
482       // if its not an accept type, then skip this kv
483       if (!(code.equals(Filter.ReturnCode.INCLUDE) || code
484           .equals(Filter.ReturnCode.INCLUDE_AND_NEXT_COL))) {
485         return null;
486       }
487     }
488     return kv;
489   }
490 
491   // helper: create a new KeyValue based on CF rename map
492   private static Cell convertKv(Cell kv, Map<byte[], byte[]> cfRenameMap) {
493     if(cfRenameMap != null) {
494       // If there's a rename mapping for this CF, create a new KeyValue
495       byte[] newCfName = cfRenameMap.get(CellUtil.cloneFamily(kv));
496       if(newCfName != null) {
497           kv = new KeyValue(kv.getRowArray(), // row buffer 
498                   kv.getRowOffset(),        // row offset
499                   kv.getRowLength(),        // row length
500                   newCfName,                // CF buffer
501                   0,                        // CF offset 
502                   newCfName.length,         // CF length 
503                   kv.getQualifierArray(),   // qualifier buffer
504                   kv.getQualifierOffset(),  // qualifier offset
505                   kv.getQualifierLength(),  // qualifier length
506                   kv.getTimestamp(),        // timestamp
507                   KeyValue.Type.codeToType(kv.getTypeByte()), // KV Type
508                   kv.getValueArray(),       // value buffer 
509                   kv.getValueOffset(),      // value offset
510                   kv.getValueLength());     // value length
511       }
512     }
513     return kv;
514   }
515 
516   // helper: make a map from sourceCfName to destCfName by parsing a config key
517   private static Map<byte[], byte[]> createCfRenameMap(Configuration conf) {
518     Map<byte[], byte[]> cfRenameMap = null;
519     String allMappingsPropVal = conf.get(CF_RENAME_PROP);
520     if(allMappingsPropVal != null) {
521       // The conf value format should be sourceCf1:destCf1,sourceCf2:destCf2,...
522       String[] allMappings = allMappingsPropVal.split(",");
523       for (String mapping: allMappings) {
524         if(cfRenameMap == null) {
525             cfRenameMap = new TreeMap<byte[],byte[]>(Bytes.BYTES_COMPARATOR);
526         }
527         String [] srcAndDest = mapping.split(":");
528         if(srcAndDest.length != 2) {
529             continue;
530         }
531         cfRenameMap.put(srcAndDest[0].getBytes(), srcAndDest[1].getBytes());
532       }
533     }
534     return cfRenameMap;
535   }
536 
537   /**
538    * <p>Sets a configuration property with key {@link #CF_RENAME_PROP} in conf that tells
539    * the mapper how to rename column families.
540    * 
541    * <p>Alternately, instead of calling this function, you could set the configuration key 
542    * {@link #CF_RENAME_PROP} yourself. The value should look like 
543    * <pre>srcCf1:destCf1,srcCf2:destCf2,....</pre>. This would have the same effect on
544    * the mapper behavior.
545    * 
546    * @param conf the Configuration in which the {@link #CF_RENAME_PROP} key will be
547    *  set
548    * @param renameMap a mapping from source CF names to destination CF names
549    */
550   static public void configureCfRenaming(Configuration conf, 
551           Map<String, String> renameMap) {
552     StringBuilder sb = new StringBuilder();
553     for(Map.Entry<String,String> entry: renameMap.entrySet()) {
554       String sourceCf = entry.getKey();
555       String destCf = entry.getValue();
556 
557       if(sourceCf.contains(":") || sourceCf.contains(",") || 
558               destCf.contains(":") || destCf.contains(",")) {
559         throw new IllegalArgumentException("Illegal character in CF names: " 
560               + sourceCf + ", " + destCf);
561       }
562 
563       if(sb.length() != 0) {
564         sb.append(",");
565       }
566       sb.append(sourceCf + ":" + destCf);
567     }
568     conf.set(CF_RENAME_PROP, sb.toString());
569   }
570 
571   /**
572    * Add a Filter to be instantiated on import
573    * @param conf Configuration to update (will be passed to the job)
574    * @param clazz {@link Filter} subclass to instantiate on the server.
575    * @param filterArgs List of arguments to pass to the filter on instantiation
576    */
577   public static void addFilterAndArguments(Configuration conf, Class<? extends Filter> clazz,
578       List<String> filterArgs) throws IOException {
579     conf.set(Import.FILTER_CLASS_CONF_KEY, clazz.getName());
580     conf.setStrings(Import.FILTER_ARGS_CONF_KEY, filterArgs.toArray(new String[filterArgs.size()]));
581   }
582 
583   /**
584    * Sets up the actual job.
585    * @param conf The current configuration.
586    * @param args The command line parameters.
587    * @return The newly created job.
588    * @throws IOException When setting up the job fails.
589    */
590   public static Job createSubmittableJob(Configuration conf, String[] args)
591   throws IOException {
592     TableName tableName = TableName.valueOf(args[0]);
593     conf.set(TABLE_NAME, tableName.getNameAsString());
594     Path inputDir = new Path(args[1]);
595     Job job = new Job(conf, NAME + "_" + tableName);
596     job.setJarByClass(Importer.class);
597     FileInputFormat.setInputPaths(job, inputDir);
598     job.setInputFormatClass(SequenceFileInputFormat.class);
599     String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);
600 
601     // make sure we get the filter in the jars
602     try {
603       Class<? extends Filter> filter = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
604       if (filter != null) {
605         TableMapReduceUtil.addDependencyJarsForClasses(conf, filter);
606       }
607     } catch (Exception e) {
608       throw new IOException(e);
609     }
610 
611     if (hfileOutPath != null && conf.getBoolean(HAS_LARGE_RESULT, false)) {
612       LOG.info("Use Large Result!!");
613       try (Connection conn = ConnectionFactory.createConnection(conf); 
614           Table table = conn.getTable(tableName);
615           RegionLocator regionLocator = conn.getRegionLocator(tableName)) {
616         HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(), regionLocator);
617         job.setMapperClass(KeyValueSortImporter.class);
618         job.setReducerClass(KeyValueReducer.class);
619         Path outputDir = new Path(hfileOutPath);
620         FileOutputFormat.setOutputPath(job, outputDir);
621         job.setMapOutputKeyClass(KeyValueWritableComparable.class);
622         job.setMapOutputValueClass(KeyValue.class);
623         job.getConfiguration().setClass("mapreduce.job.output.key.comparator.class", 
624             KeyValueWritableComparable.KeyValueWritableComparator.class,
625             RawComparator.class);
626         Path partitionsPath = 
627             new Path(TotalOrderPartitioner.getPartitionFile(job.getConfiguration()));
628         FileSystem fs = FileSystem.get(job.getConfiguration());
629         fs.deleteOnExit(partitionsPath);
630         job.setPartitionerClass(KeyValueWritableComparablePartitioner.class);
631         job.setNumReduceTasks(regionLocator.getStartKeys().length);
632         TableMapReduceUtil.addDependencyJarsForClasses(job.getConfiguration(),
633             com.google.common.base.Preconditions.class);
634       }
635     } else if (hfileOutPath != null) {
636       job.setMapperClass(KeyValueImporter.class);
637       try (Connection conn = ConnectionFactory.createConnection(conf); 
638           Table table = conn.getTable(tableName);
639           RegionLocator regionLocator = conn.getRegionLocator(tableName)){
640         job.setReducerClass(KeyValueSortReducer.class);
641         Path outputDir = new Path(hfileOutPath);
642         FileOutputFormat.setOutputPath(job, outputDir);
643         job.setMapOutputKeyClass(ImmutableBytesWritable.class);
644         job.setMapOutputValueClass(KeyValue.class);
645         HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(), regionLocator);
646         TableMapReduceUtil.addDependencyJarsForClasses(job.getConfiguration(),
647             com.google.common.base.Preconditions.class);
648       }
649     } else {
650       // No reducers.  Just write straight to table.  Call initTableReducerJob
651       // because it sets up the TableOutputFormat.
652       job.setMapperClass(Importer.class);
653       TableMapReduceUtil.initTableReducerJob(tableName.getNameAsString(), null, job);
654       job.setNumReduceTasks(0);
655     }
656     return job;
657   }
658 
659   /*
660    * @param errorMsg Error message.  Can be null.
661    */
662   private static void usage(final String errorMsg) {
663     if (errorMsg != null && errorMsg.length() > 0) {
664       System.err.println("ERROR: " + errorMsg);
665     }
666     System.err.println("Usage: Import [options] <tablename> <inputdir>");
667     System.err.println("By default Import will load data directly into HBase. To instead generate");
668     System.err.println("HFiles of data to prepare for a bulk data load, pass the option:");
669     System.err.println("  -D" + BULK_OUTPUT_CONF_KEY + "=/path/for/output");
670     System.err.println("If there is a large result that includes too much KeyValue "
671         + "whitch can occur OOME caused by the memery sort in reducer, pass the option:");
672     System.err.println("  -D" + HAS_LARGE_RESULT + "=true");
673     System.err
674         .println(" To apply a generic org.apache.hadoop.hbase.filter.Filter to the input, use");
675     System.err.println("  -D" + FILTER_CLASS_CONF_KEY + "=<name of filter class>");
676     System.err.println("  -D" + FILTER_ARGS_CONF_KEY + "=<comma separated list of args for filter");
677     System.err.println(" NOTE: The filter will be applied BEFORE doing key renames via the "
678         + CF_RENAME_PROP + " property. Futher, filters will only use the"
679         + " Filter#filterRowKey(byte[] buffer, int offset, int length) method to identify "
680         + " whether the current row needs to be ignored completely for processing and "
681         + " Filter#filterKeyValue(KeyValue) method to determine if the KeyValue should be added;"
682         + " Filter.ReturnCode#INCLUDE and #INCLUDE_AND_NEXT_COL will be considered as including"
683         + " the KeyValue.");
684     System.err.println("To import data exported from HBase 0.94, use");
685     System.err.println("  -Dhbase.import.version=0.94");
686     System.err.println("For performance consider the following options:\n"
687         + "  -Dmapreduce.map.speculative=false\n"
688         + "  -Dmapreduce.reduce.speculative=false\n"
689         + "  -D" + WAL_DURABILITY + "=<Used while writing data to hbase."
690             +" Allowed values are the supported durability values"
691             +" like SKIP_WAL/ASYNC_WAL/SYNC_WAL/...>");
692   }
693 
694   /**
695    * If the durability is set to {@link Durability#SKIP_WAL} and the data is imported to hbase, we
696    * need to flush all the regions of the table as the data is held in memory and is also not
697    * present in the Write Ahead Log to replay in scenarios of a crash. This method flushes all the
698    * regions of the table in the scenarios of import data to hbase with {@link Durability#SKIP_WAL}
699    */
700   public static void flushRegionsIfNecessary(Configuration conf) throws IOException,
701       InterruptedException {
702     String tableName = conf.get(TABLE_NAME);
703     HBaseAdmin hAdmin = null;
704     String durability = conf.get(WAL_DURABILITY);
705     // Need to flush if the data is written to hbase and skip wal is enabled.
706     if (conf.get(BULK_OUTPUT_CONF_KEY) == null && durability != null
707         && Durability.SKIP_WAL.name().equalsIgnoreCase(durability)) {
708       try {
709         hAdmin = new HBaseAdmin(conf);
710         hAdmin.flush(tableName);
711       } finally {
712         if (hAdmin != null) {
713           hAdmin.close();
714         }
715       }
716     }
717   }
718 
719   /**
720    * Main entry point.
721    *
722    * @param args  The command line parameters.
723    * @throws Exception When running the job fails.
724    */
725   public static void main(String[] args) throws Exception {
726     Configuration conf = HBaseConfiguration.create();
727     String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
728     if (otherArgs.length < 2) {
729       usage("Wrong number of arguments: " + otherArgs.length);
730       System.exit(-1);
731     }
732     String inputVersionString = System.getProperty(ResultSerialization.IMPORT_FORMAT_VER);
733     if (inputVersionString != null) {
734       conf.set(ResultSerialization.IMPORT_FORMAT_VER, inputVersionString);
735     }
736     Job job = createSubmittableJob(conf, otherArgs);
737     boolean isJobSuccessful = job.waitForCompletion(true);
738     if(isJobSuccessful){
739       // Flush all the regions of the table
740       flushRegionsIfNecessary(conf);
741     }
742     long inputRecords = job.getCounters().findCounter(TaskCounter.MAP_INPUT_RECORDS).getValue();
743     long outputRecords = job.getCounters().findCounter(TaskCounter.MAP_OUTPUT_RECORDS).getValue();
744     if (outputRecords < inputRecords) {
745       System.err.println("Warning, not all records were imported (maybe filtered out).");
746       if (outputRecords == 0) {
747         System.err.println("If the data was exported from HBase 0.94 "+
748             "consider using -Dhbase.import.version=0.94.");
749       }
750     }
751 
752     System.exit(isJobSuccessful ? 0 : 1);
753   }
754 }