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.IOException;
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.util.ArrayList;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.TreeMap;
29 import java.util.UUID;
30
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.apache.hadoop.hbase.classification.InterfaceAudience;
34 import org.apache.hadoop.hbase.classification.InterfaceStability;
35 import org.apache.hadoop.conf.Configuration;
36 import org.apache.hadoop.fs.Path;
37 import org.apache.hadoop.hbase.Cell;
38 import org.apache.hadoop.hbase.CellUtil;
39 import org.apache.hadoop.hbase.HBaseConfiguration;
40 import org.apache.hadoop.hbase.KeyValue;
41 import org.apache.hadoop.hbase.KeyValueUtil;
42 import org.apache.hadoop.hbase.TableName;
43 import org.apache.hadoop.hbase.ZooKeeperConnectionException;
44 import org.apache.hadoop.hbase.classification.InterfaceAudience;
45 import org.apache.hadoop.hbase.classification.InterfaceStability;
46 import org.apache.hadoop.hbase.client.Connection;
47 import org.apache.hadoop.hbase.client.ConnectionFactory;
48 import org.apache.hadoop.hbase.client.Delete;
49 import org.apache.hadoop.hbase.client.Durability;
50 import org.apache.hadoop.hbase.client.HBaseAdmin;
51 import org.apache.hadoop.hbase.client.Mutation;
52 import org.apache.hadoop.hbase.client.Put;
53 import org.apache.hadoop.hbase.client.RegionLocator;
54 import org.apache.hadoop.hbase.client.Result;
55 import org.apache.hadoop.hbase.client.Table;
56 import org.apache.hadoop.hbase.filter.Filter;
57 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
58 import org.apache.hadoop.hbase.util.Bytes;
59 import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
60 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
61 import org.apache.hadoop.mapreduce.Job;
62 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
63 import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
64 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
65 import org.apache.hadoop.util.GenericOptionsParser;
66 import org.apache.zookeeper.KeeperException;
67
68
69
70
71
72 @InterfaceAudience.Public
73 @InterfaceStability.Stable
74 public class Import {
75 private static final Log LOG = LogFactory.getLog(Import.class);
76 final static String NAME = "import";
77 public final static String CF_RENAME_PROP = "HBASE_IMPORTER_RENAME_CFS";
78 public final static String BULK_OUTPUT_CONF_KEY = "import.bulk.output";
79 public final static String FILTER_CLASS_CONF_KEY = "import.filter.class";
80 public final static String FILTER_ARGS_CONF_KEY = "import.filter.args";
81 public final static String TABLE_NAME = "import.table.name";
82 public final static String WAL_DURABILITY = "import.wal.durability";
83
84
85
86
87 public static class KeyValueImporter extends TableMapper<ImmutableBytesWritable, KeyValue> {
88 private Map<byte[], byte[]> cfRenameMap;
89 private Filter filter;
90 private static final Log LOG = LogFactory.getLog(KeyValueImporter.class);
91
92
93
94
95
96
97
98 @Override
99 public void map(ImmutableBytesWritable row, Result value,
100 Context context)
101 throws IOException {
102 try {
103 if (LOG.isTraceEnabled()) {
104 LOG.trace("Considering the row."
105 + Bytes.toString(row.get(), row.getOffset(), row.getLength()));
106 }
107 if (filter == null || !filter.filterRowKey(row.get(), row.getOffset(), row.getLength())) {
108 for (Cell kv : value.rawCells()) {
109 kv = filterKv(filter, kv);
110
111 if (kv == null) continue;
112
113 context.write(row, KeyValueUtil.ensureKeyValue(convertKv(kv, cfRenameMap)));
114 }
115 }
116 } catch (InterruptedException e) {
117 e.printStackTrace();
118 }
119 }
120
121 @Override
122 public void setup(Context context) {
123 cfRenameMap = createCfRenameMap(context.getConfiguration());
124 filter = instantiateFilter(context.getConfiguration());
125 }
126 }
127
128
129
130
131 public static class Importer extends TableMapper<ImmutableBytesWritable, Mutation> {
132 private Map<byte[], byte[]> cfRenameMap;
133 private List<UUID> clusterIds;
134 private Filter filter;
135 private Durability durability;
136
137
138
139
140
141
142
143 @Override
144 public void map(ImmutableBytesWritable row, Result value,
145 Context context)
146 throws IOException {
147 try {
148 writeResult(row, value, context);
149 } catch (InterruptedException e) {
150 e.printStackTrace();
151 }
152 }
153
154 private void writeResult(ImmutableBytesWritable key, Result result, Context context)
155 throws IOException, InterruptedException {
156 Put put = null;
157 Delete delete = null;
158 if (LOG.isTraceEnabled()) {
159 LOG.trace("Considering the row."
160 + Bytes.toString(key.get(), key.getOffset(), key.getLength()));
161 }
162 if (filter == null || !filter.filterRowKey(key.get(), key.getOffset(), key.getLength())) {
163 processKV(key, result, context, put, delete);
164 }
165 }
166
167 protected void processKV(ImmutableBytesWritable key, Result result, Context context, Put put,
168 Delete delete) throws IOException, InterruptedException {
169 for (Cell kv : result.rawCells()) {
170 kv = filterKv(filter, kv);
171
172 if (kv == null) continue;
173
174 kv = convertKv(kv, cfRenameMap);
175
176
177
178
179
180
181
182
183 if (CellUtil.isDeleteFamily(kv)) {
184 Delete deleteFamily = new Delete(key.get());
185 deleteFamily.addDeleteMarker(kv);
186 if (durability != null) {
187 deleteFamily.setDurability(durability);
188 }
189 deleteFamily.setClusterIds(clusterIds);
190 context.write(key, deleteFamily);
191 } else if (CellUtil.isDelete(kv)) {
192 if (delete == null) {
193 delete = new Delete(key.get());
194 }
195 delete.addDeleteMarker(kv);
196 } else {
197 if (put == null) {
198 put = new Put(key.get());
199 }
200 addPutToKv(put, kv);
201 }
202 }
203 if (put != null) {
204 if (durability != null) {
205 put.setDurability(durability);
206 }
207 put.setClusterIds(clusterIds);
208 context.write(key, put);
209 }
210 if (delete != null) {
211 if (durability != null) {
212 delete.setDurability(durability);
213 }
214 delete.setClusterIds(clusterIds);
215 context.write(key, delete);
216 }
217 }
218
219 protected void addPutToKv(Put put, Cell kv) throws IOException {
220 put.add(kv);
221 }
222
223 @Override
224 public void setup(Context context) {
225 Configuration conf = context.getConfiguration();
226 cfRenameMap = createCfRenameMap(conf);
227 filter = instantiateFilter(conf);
228 String durabilityStr = conf.get(WAL_DURABILITY);
229 if(durabilityStr != null){
230 durability = Durability.valueOf(durabilityStr.toUpperCase());
231 }
232
233 ZooKeeperWatcher zkw = null;
234 Exception ex = null;
235 try {
236 zkw = new ZooKeeperWatcher(conf, context.getTaskAttemptID().toString(), null);
237 clusterIds = Collections.singletonList(ZKClusterId.getUUIDForCluster(zkw));
238 } catch (ZooKeeperConnectionException e) {
239 ex = e;
240 LOG.error("Problem connecting to ZooKeper during task setup", e);
241 } catch (KeeperException e) {
242 ex = e;
243 LOG.error("Problem reading ZooKeeper data during task setup", e);
244 } catch (IOException e) {
245 ex = e;
246 LOG.error("Problem setting up task", e);
247 } finally {
248 if (zkw != null) zkw.close();
249 }
250 if (clusterIds == null) {
251
252 throw new RuntimeException(ex);
253 }
254 }
255 }
256
257
258
259
260
261
262
263
264 public static Filter instantiateFilter(Configuration conf) {
265
266 Class<? extends Filter> filterClass = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
267 if (filterClass == null) {
268 LOG.debug("No configured filter class, accepting all keyvalues.");
269 return null;
270 }
271 LOG.debug("Attempting to create filter:" + filterClass);
272 String[] filterArgs = conf.getStrings(FILTER_ARGS_CONF_KEY);
273 ArrayList<byte[]> quotedArgs = toQuotedByteArrays(filterArgs);
274 try {
275 Method m = filterClass.getMethod("createFilterFromArguments", ArrayList.class);
276 return (Filter) m.invoke(null, quotedArgs);
277 } catch (IllegalAccessException e) {
278 LOG.error("Couldn't instantiate filter!", e);
279 throw new RuntimeException(e);
280 } catch (SecurityException e) {
281 LOG.error("Couldn't instantiate filter!", e);
282 throw new RuntimeException(e);
283 } catch (NoSuchMethodException e) {
284 LOG.error("Couldn't instantiate filter!", e);
285 throw new RuntimeException(e);
286 } catch (IllegalArgumentException e) {
287 LOG.error("Couldn't instantiate filter!", e);
288 throw new RuntimeException(e);
289 } catch (InvocationTargetException e) {
290 LOG.error("Couldn't instantiate filter!", e);
291 throw new RuntimeException(e);
292 }
293 }
294
295 private static ArrayList<byte[]> toQuotedByteArrays(String... stringArgs) {
296 ArrayList<byte[]> quotedArgs = new ArrayList<byte[]>();
297 for (String stringArg : stringArgs) {
298
299
300 quotedArgs.add(Bytes.toBytes("'" + stringArg + "'"));
301 }
302 return quotedArgs;
303 }
304
305
306
307
308
309
310
311 public static Cell filterKv(Filter filter, Cell kv) throws IOException {
312
313 if (filter != null) {
314 Filter.ReturnCode code = filter.filterKeyValue(kv);
315 if (LOG.isTraceEnabled()) {
316 LOG.trace("Filter returned:" + code + " for the key value:" + kv);
317 }
318
319 if (!(code.equals(Filter.ReturnCode.INCLUDE) || code
320 .equals(Filter.ReturnCode.INCLUDE_AND_NEXT_COL))) {
321 return null;
322 }
323 }
324 return kv;
325 }
326
327
328 private static Cell convertKv(Cell kv, Map<byte[], byte[]> cfRenameMap) {
329 if(cfRenameMap != null) {
330
331 byte[] newCfName = cfRenameMap.get(CellUtil.cloneFamily(kv));
332 if(newCfName != null) {
333 kv = new KeyValue(kv.getRowArray(),
334 kv.getRowOffset(),
335 kv.getRowLength(),
336 newCfName,
337 0,
338 newCfName.length,
339 kv.getQualifierArray(),
340 kv.getQualifierOffset(),
341 kv.getQualifierLength(),
342 kv.getTimestamp(),
343 KeyValue.Type.codeToType(kv.getTypeByte()),
344 kv.getValueArray(),
345 kv.getValueOffset(),
346 kv.getValueLength());
347 }
348 }
349 return kv;
350 }
351
352
353 private static Map<byte[], byte[]> createCfRenameMap(Configuration conf) {
354 Map<byte[], byte[]> cfRenameMap = null;
355 String allMappingsPropVal = conf.get(CF_RENAME_PROP);
356 if(allMappingsPropVal != null) {
357
358 String[] allMappings = allMappingsPropVal.split(",");
359 for (String mapping: allMappings) {
360 if(cfRenameMap == null) {
361 cfRenameMap = new TreeMap<byte[],byte[]>(Bytes.BYTES_COMPARATOR);
362 }
363 String [] srcAndDest = mapping.split(":");
364 if(srcAndDest.length != 2) {
365 continue;
366 }
367 cfRenameMap.put(srcAndDest[0].getBytes(), srcAndDest[1].getBytes());
368 }
369 }
370 return cfRenameMap;
371 }
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386 static public void configureCfRenaming(Configuration conf,
387 Map<String, String> renameMap) {
388 StringBuilder sb = new StringBuilder();
389 for(Map.Entry<String,String> entry: renameMap.entrySet()) {
390 String sourceCf = entry.getKey();
391 String destCf = entry.getValue();
392
393 if(sourceCf.contains(":") || sourceCf.contains(",") ||
394 destCf.contains(":") || destCf.contains(",")) {
395 throw new IllegalArgumentException("Illegal character in CF names: "
396 + sourceCf + ", " + destCf);
397 }
398
399 if(sb.length() != 0) {
400 sb.append(",");
401 }
402 sb.append(sourceCf + ":" + destCf);
403 }
404 conf.set(CF_RENAME_PROP, sb.toString());
405 }
406
407
408
409
410
411
412
413 public static void addFilterAndArguments(Configuration conf, Class<? extends Filter> clazz,
414 List<String> filterArgs) throws IOException {
415 conf.set(Import.FILTER_CLASS_CONF_KEY, clazz.getName());
416 conf.setStrings(Import.FILTER_ARGS_CONF_KEY, filterArgs.toArray(new String[filterArgs.size()]));
417 }
418
419
420
421
422
423
424
425
426 public static Job createSubmittableJob(Configuration conf, String[] args)
427 throws IOException {
428 TableName tableName = TableName.valueOf(args[0]);
429 conf.set(TABLE_NAME, tableName.getNameAsString());
430 Path inputDir = new Path(args[1]);
431 Job job = new Job(conf, NAME + "_" + tableName);
432 job.setJarByClass(Importer.class);
433 FileInputFormat.setInputPaths(job, inputDir);
434 job.setInputFormatClass(SequenceFileInputFormat.class);
435 String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);
436
437
438 try {
439 Class<? extends Filter> filter = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
440 if (filter != null) {
441 TableMapReduceUtil.addDependencyJars(conf, filter);
442 }
443 } catch (Exception e) {
444 throw new IOException(e);
445 }
446
447 if (hfileOutPath != null) {
448 job.setMapperClass(KeyValueImporter.class);
449 try (Connection conn = ConnectionFactory.createConnection(conf);
450 Table table = conn.getTable(tableName);
451 RegionLocator regionLocator = conn.getRegionLocator(tableName)){
452 job.setReducerClass(KeyValueSortReducer.class);
453 Path outputDir = new Path(hfileOutPath);
454 FileOutputFormat.setOutputPath(job, outputDir);
455 job.setMapOutputKeyClass(ImmutableBytesWritable.class);
456 job.setMapOutputValueClass(KeyValue.class);
457 HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(), regionLocator);
458 TableMapReduceUtil.addDependencyJars(job.getConfiguration(),
459 com.google.common.base.Preconditions.class);
460 }
461 } else {
462
463
464 job.setMapperClass(Importer.class);
465 TableMapReduceUtil.initTableReducerJob(tableName.getNameAsString(), null, job);
466 job.setNumReduceTasks(0);
467 }
468 return job;
469 }
470
471
472
473
474 private static void usage(final String errorMsg) {
475 if (errorMsg != null && errorMsg.length() > 0) {
476 System.err.println("ERROR: " + errorMsg);
477 }
478 System.err.println("Usage: Import [options] <tablename> <inputdir>");
479 System.err.println("By default Import will load data directly into HBase. To instead generate");
480 System.err.println("HFiles of data to prepare for a bulk data load, pass the option:");
481 System.err.println(" -D" + BULK_OUTPUT_CONF_KEY + "=/path/for/output");
482 System.err
483 .println(" To apply a generic org.apache.hadoop.hbase.filter.Filter to the input, use");
484 System.err.println(" -D" + FILTER_CLASS_CONF_KEY + "=<name of filter class>");
485 System.err.println(" -D" + FILTER_ARGS_CONF_KEY + "=<comma separated list of args for filter");
486 System.err.println(" NOTE: The filter will be applied BEFORE doing key renames via the "
487 + CF_RENAME_PROP + " property. Futher, filters will only use the"
488 + " Filter#filterRowKey(byte[] buffer, int offset, int length) method to identify "
489 + " whether the current row needs to be ignored completely for processing and "
490 + " Filter#filterKeyValue(KeyValue) method to determine if the KeyValue should be added;"
491 + " Filter.ReturnCode#INCLUDE and #INCLUDE_AND_NEXT_COL will be considered as including"
492 + " the KeyValue.");
493 System.err.println("For performance consider the following options:\n"
494 + " -Dmapreduce.map.speculative=false\n"
495 + " -Dmapreduce.reduce.speculative=false\n"
496 + " -D" + WAL_DURABILITY + "=<Used while writing data to hbase."
497 +" Allowed values are the supported durability values"
498 +" like SKIP_WAL/ASYNC_WAL/SYNC_WAL/...>");
499 }
500
501
502
503
504
505
506
507 public static void flushRegionsIfNecessary(Configuration conf) throws IOException,
508 InterruptedException {
509 String tableName = conf.get(TABLE_NAME);
510 HBaseAdmin hAdmin = null;
511 String durability = conf.get(WAL_DURABILITY);
512
513 if (conf.get(BULK_OUTPUT_CONF_KEY) == null && durability != null
514 && Durability.SKIP_WAL.name().equalsIgnoreCase(durability)) {
515 try {
516 hAdmin = new HBaseAdmin(conf);
517 hAdmin.flush(tableName);
518 } finally {
519 if (hAdmin != null) {
520 hAdmin.close();
521 }
522 }
523 }
524 }
525
526
527
528
529
530
531
532 public static void main(String[] args) throws Exception {
533 Configuration conf = HBaseConfiguration.create();
534 String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
535 if (otherArgs.length < 2) {
536 usage("Wrong number of arguments: " + otherArgs.length);
537 System.exit(-1);
538 }
539 String inputVersionString = System.getProperty(ResultSerialization.IMPORT_FORMAT_VER);
540 if (inputVersionString != null) {
541 conf.set(ResultSerialization.IMPORT_FORMAT_VER, inputVersionString);
542 }
543 Job job = createSubmittableJob(conf, otherArgs);
544 boolean isJobSuccessful = job.waitForCompletion(true);
545 if(isJobSuccessful){
546
547 flushRegionsIfNecessary(conf);
548 }
549 System.exit(job.waitForCompletion(true) ? 0 : 1);
550 }
551 }