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