1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
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
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
195
196
197
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
211 if (kv == null) continue;
212
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
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
259
260
261
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
276 if (kv == null) continue;
277
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
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
304
305
306
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
337 if (kv == null) continue;
338
339 kv = convertKv(kv, cfRenameMap);
340
341
342
343
344
345
346
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
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
417 throw new RuntimeException(ex);
418 }
419 }
420 }
421
422
423
424
425
426
427
428
429 public static Filter instantiateFilter(Configuration conf) {
430
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
464
465 quotedArgs.add(Bytes.toBytes("'" + stringArg + "'"));
466 }
467 return quotedArgs;
468 }
469
470
471
472
473
474
475
476 public static Cell filterKv(Filter filter, Cell kv) throws IOException {
477
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
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
493 private static Cell convertKv(Cell kv, Map<byte[], byte[]> cfRenameMap) {
494 if(cfRenameMap != null) {
495
496 byte[] newCfName = cfRenameMap.get(CellUtil.cloneFamily(kv));
497 if(newCfName != null) {
498 kv = new KeyValue(kv.getRowArray(),
499 kv.getRowOffset(),
500 kv.getRowLength(),
501 newCfName,
502 0,
503 newCfName.length,
504 kv.getQualifierArray(),
505 kv.getQualifierOffset(),
506 kv.getQualifierLength(),
507 kv.getTimestamp(),
508 KeyValue.Type.codeToType(kv.getTypeByte()),
509 kv.getValueArray(),
510 kv.getValueOffset(),
511 kv.getValueLength());
512 }
513 }
514 return kv;
515 }
516
517
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
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
540
541
542
543
544
545
546
547
548
549
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
574
575
576
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
586
587
588
589
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
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
652
653 job.setMapperClass(Importer.class);
654 TableMapReduceUtil.initTableReducerJob(tableName.getNameAsString(), null, job);
655 job.setNumReduceTasks(0);
656 }
657 return job;
658 }
659
660
661
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
697
698
699
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
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
722
723
724
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
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 }