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.List;
26 import java.util.Map;
27 import java.util.TreeMap;
28 import java.util.UUID;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.apache.hadoop.classification.InterfaceAudience;
33 import org.apache.hadoop.classification.InterfaceStability;
34 import org.apache.hadoop.conf.Configuration;
35 import org.apache.hadoop.fs.Path;
36 import org.apache.hadoop.hbase.HBaseConfiguration;
37 import org.apache.hadoop.hbase.KeyValue;
38 import org.apache.hadoop.hbase.client.Delete;
39 import org.apache.hadoop.hbase.client.HConnection;
40 import org.apache.hadoop.hbase.client.HConnectionManager;
41 import org.apache.hadoop.hbase.client.HTable;
42 import org.apache.hadoop.hbase.client.Mutation;
43 import org.apache.hadoop.hbase.client.Put;
44 import org.apache.hadoop.hbase.client.Result;
45 import org.apache.hadoop.hbase.exceptions.ZooKeeperConnectionException;
46 import org.apache.hadoop.hbase.filter.Filter;
47 import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
48 import org.apache.hadoop.hbase.replication.ReplicationZookeeper;
49 import org.apache.hadoop.hbase.util.Bytes;
50 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
51 import org.apache.hadoop.mapreduce.Job;
52 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
53 import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
54 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
55 import org.apache.hadoop.util.GenericOptionsParser;
56 import org.apache.zookeeper.KeeperException;
57
58
59
60
61 @InterfaceAudience.Public
62 @InterfaceStability.Stable
63 public class Import {
64 private static final Log LOG = LogFactory.getLog(Import.class);
65 final static String NAME = "import";
66 final static String CF_RENAME_PROP = "HBASE_IMPORTER_RENAME_CFS";
67 final static String BULK_OUTPUT_CONF_KEY = "import.bulk.output";
68 final static String FILTER_CLASS_CONF_KEY = "import.filter.class";
69 final static String FILTER_ARGS_CONF_KEY = "import.filter.args";
70
71
72 private static Filter filter;
73
74
75
76
77 static class KeyValueImporter
78 extends TableMapper<ImmutableBytesWritable, KeyValue> {
79 private Map<byte[], byte[]> cfRenameMap;
80
81
82
83
84
85
86
87
88
89 @Override
90 public void map(ImmutableBytesWritable row, Result value,
91 Context context)
92 throws IOException {
93 try {
94 for (KeyValue kv : value.raw()) {
95 kv = filterKv(kv);
96
97 if (kv == null) continue;
98
99 context.write(row, convertKv(kv, cfRenameMap));
100 }
101 } catch (InterruptedException e) {
102 e.printStackTrace();
103 }
104 }
105
106 @Override
107 public void setup(Context context) {
108 cfRenameMap = createCfRenameMap(context.getConfiguration());
109 filter = instantiateFilter(context.getConfiguration());
110 }
111 }
112
113
114
115
116 static class Importer
117 extends TableMapper<ImmutableBytesWritable, Mutation> {
118 private Map<byte[], byte[]> cfRenameMap;
119 private UUID clusterId;
120
121
122
123
124
125
126
127
128
129 @Override
130 public void map(ImmutableBytesWritable row, Result value,
131 Context context)
132 throws IOException {
133 try {
134 writeResult(row, value, context);
135 } catch (InterruptedException e) {
136 e.printStackTrace();
137 }
138 }
139
140 private void writeResult(ImmutableBytesWritable key, Result result, Context context)
141 throws IOException, InterruptedException {
142 Put put = null;
143 Delete delete = null;
144 for (KeyValue kv : result.raw()) {
145 kv = filterKv(kv);
146
147 if (kv == null) continue;
148
149 kv = convertKv(kv, cfRenameMap);
150
151 if (kv.isDelete()) {
152 if (delete == null) {
153 delete = new Delete(key.get());
154 }
155 delete.addDeleteMarker(kv);
156 } else {
157 if (put == null) {
158 put = new Put(key.get());
159 }
160 put.add(kv);
161 }
162 }
163 if (put != null) {
164 put.setClusterId(clusterId);
165 context.write(key, put);
166 }
167 if (delete != null) {
168 delete.setClusterId(clusterId);
169 context.write(key, delete);
170 }
171 }
172
173 @Override
174 public void setup(Context context) {
175 Configuration conf = context.getConfiguration();
176 cfRenameMap = createCfRenameMap(conf);
177 filter = instantiateFilter(conf);
178
179 ReplicationZookeeper zkHelper = null;
180 ZooKeeperWatcher zkw = null;
181 try {
182 HConnection connection = HConnectionManager.getConnection(conf);
183 zkw = new ZooKeeperWatcher(conf, context.getTaskAttemptID().toString(), null);
184 zkHelper = new ReplicationZookeeper(connection, conf, zkw);
185 try {
186 this.clusterId = zkHelper.getUUIDForCluster(zkw);
187 } finally {
188 if (zkHelper != null) zkHelper.close();
189 }
190 } catch (ZooKeeperConnectionException e) {
191 LOG.error("Problem connecting to ZooKeper during task setup", e);
192 } catch (KeeperException e) {
193 LOG.error("Problem reading ZooKeeper data during task setup", e);
194 } catch (IOException e) {
195 LOG.error("Problem setting up task", e);
196 } finally {
197 if (zkw != null) zkw.close();
198 }
199 }
200 }
201
202
203
204
205
206
207
208
209 private static Filter instantiateFilter(Configuration conf) {
210
211 Class<? extends Filter> filterClass = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
212 if (filterClass == null) {
213 LOG.debug("No configured filter class, accepting all keyvalues.");
214 return null;
215 }
216 LOG.debug("Attempting to create filter:" + filterClass);
217
218 try {
219 Method m = filterClass.getMethod("createFilterFromArguments", ArrayList.class);
220 return (Filter) m.invoke(null, getFilterArgs(conf));
221 } catch (IllegalAccessException e) {
222 LOG.error("Couldn't instantiate filter!", e);
223 throw new RuntimeException(e);
224 } catch (SecurityException e) {
225 LOG.error("Couldn't instantiate filter!", e);
226 throw new RuntimeException(e);
227 } catch (NoSuchMethodException e) {
228 LOG.error("Couldn't instantiate filter!", e);
229 throw new RuntimeException(e);
230 } catch (IllegalArgumentException e) {
231 LOG.error("Couldn't instantiate filter!", e);
232 throw new RuntimeException(e);
233 } catch (InvocationTargetException e) {
234 LOG.error("Couldn't instantiate filter!", e);
235 throw new RuntimeException(e);
236 }
237 }
238
239 private static ArrayList<byte[]> getFilterArgs(Configuration conf) {
240 ArrayList<byte[]> args = new ArrayList<byte[]>();
241 String[] sargs = conf.getStrings(FILTER_ARGS_CONF_KEY);
242 for (String arg : sargs) {
243
244
245 args.add(Bytes.toBytes("'" + arg + "'"));
246 }
247 return args;
248 }
249
250
251
252
253
254
255
256 private static KeyValue filterKv(KeyValue kv) throws IOException {
257
258 if (filter != null) {
259 Filter.ReturnCode code = filter.filterKeyValue(kv);
260 LOG.debug("Filter returned:" + code);
261
262 if (!(code.equals(Filter.ReturnCode.INCLUDE) || code
263 .equals(Filter.ReturnCode.INCLUDE_AND_NEXT_COL))) {
264 LOG.debug("Skipping key: " + kv + " from filter decision: " + code);
265 return null;
266 }
267 }
268 return kv;
269 }
270
271
272 private static KeyValue convertKv(KeyValue kv, Map<byte[], byte[]> cfRenameMap) {
273 if(cfRenameMap != null) {
274
275 byte[] newCfName = cfRenameMap.get(kv.getFamily());
276 if(newCfName != null) {
277 kv = new KeyValue(kv.getBuffer(),
278 kv.getRowOffset(),
279 kv.getRowLength(),
280 newCfName,
281 0,
282 newCfName.length,
283 kv.getBuffer(),
284 kv.getQualifierOffset(),
285 kv.getQualifierLength(),
286 kv.getTimestamp(),
287 KeyValue.Type.codeToType(kv.getType()),
288 kv.getBuffer(),
289 kv.getValueOffset(),
290 kv.getValueLength());
291 }
292 }
293 return kv;
294 }
295
296
297 private static Map<byte[], byte[]> createCfRenameMap(Configuration conf) {
298 Map<byte[], byte[]> cfRenameMap = null;
299 String allMappingsPropVal = conf.get(CF_RENAME_PROP);
300 if(allMappingsPropVal != null) {
301
302 String[] allMappings = allMappingsPropVal.split(",");
303 for (String mapping: allMappings) {
304 if(cfRenameMap == null) {
305 cfRenameMap = new TreeMap<byte[],byte[]>(Bytes.BYTES_COMPARATOR);
306 }
307 String [] srcAndDest = mapping.split(":");
308 if(srcAndDest.length != 2) {
309 continue;
310 }
311 cfRenameMap.put(srcAndDest[0].getBytes(), srcAndDest[1].getBytes());
312 }
313 }
314 return cfRenameMap;
315 }
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330 static public void configureCfRenaming(Configuration conf,
331 Map<String, String> renameMap) {
332 StringBuilder sb = new StringBuilder();
333 for(Map.Entry<String,String> entry: renameMap.entrySet()) {
334 String sourceCf = entry.getKey();
335 String destCf = entry.getValue();
336
337 if(sourceCf.contains(":") || sourceCf.contains(",") ||
338 destCf.contains(":") || destCf.contains(",")) {
339 throw new IllegalArgumentException("Illegal character in CF names: "
340 + sourceCf + ", " + destCf);
341 }
342
343 if(sb.length() != 0) {
344 sb.append(",");
345 }
346 sb.append(sourceCf + ":" + destCf);
347 }
348 conf.set(CF_RENAME_PROP, sb.toString());
349 }
350
351
352
353
354
355
356
357 public static void addFilterAndArguments(Configuration conf, Class<? extends Filter> clazz,
358 List<String> args) {
359 conf.set(Import.FILTER_CLASS_CONF_KEY, clazz.getName());
360
361
362 StringBuilder builder = new StringBuilder();
363 for (int i = 0; i < args.size(); i++) {
364 String arg = args.get(i);
365 builder.append(arg);
366 if (i != args.size() - 1) {
367 builder.append(",");
368 }
369 }
370 conf.set(Import.FILTER_ARGS_CONF_KEY, builder.toString());
371 }
372
373
374
375
376
377
378
379
380 public static Job createSubmittableJob(Configuration conf, String[] args)
381 throws IOException {
382 String tableName = args[0];
383 Path inputDir = new Path(args[1]);
384 Job job = new Job(conf, NAME + "_" + tableName);
385 job.setJarByClass(Importer.class);
386 FileInputFormat.setInputPaths(job, inputDir);
387 job.setInputFormatClass(SequenceFileInputFormat.class);
388 String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);
389
390
391 try {
392 Class<? extends Filter> filter = conf.getClass(FILTER_CLASS_CONF_KEY, null, Filter.class);
393 if (filter != null) {
394 TableMapReduceUtil.addDependencyJars(conf, filter);
395 }
396 } catch (Exception e) {
397 throw new IOException(e);
398 }
399
400 if (hfileOutPath != null) {
401 job.setMapperClass(KeyValueImporter.class);
402 HTable table = new HTable(conf, tableName);
403 job.setReducerClass(KeyValueSortReducer.class);
404 Path outputDir = new Path(hfileOutPath);
405 FileOutputFormat.setOutputPath(job, outputDir);
406 job.setMapOutputKeyClass(ImmutableBytesWritable.class);
407 job.setMapOutputValueClass(KeyValue.class);
408 HFileOutputFormat.configureIncrementalLoad(job, table);
409 TableMapReduceUtil.addDependencyJars(job.getConfiguration(),
410 com.google.common.base.Preconditions.class);
411 } else {
412
413
414 job.setMapperClass(Importer.class);
415 TableMapReduceUtil.initTableReducerJob(tableName, null, job);
416 job.setNumReduceTasks(0);
417 }
418 return job;
419 }
420
421
422
423
424 private static void usage(final String errorMsg) {
425 if (errorMsg != null && errorMsg.length() > 0) {
426 System.err.println("ERROR: " + errorMsg);
427 }
428 System.err.println("Usage: Import [options] <tablename> <inputdir>");
429 System.err.println("By default Import will load data directly into HBase. To instead generate");
430 System.err.println("HFiles of data to prepare for a bulk data load, pass the option:");
431 System.err.println(" -D" + BULK_OUTPUT_CONF_KEY + "=/path/for/output");
432 System.err
433 .println(" To apply a generic org.apache.hadoop.hbase.filter.Filter to the input, use");
434 System.err.println(" -D" + FILTER_CLASS_CONF_KEY + "=<name of filter class>");
435 System.err.println(" -D" + FILTER_ARGS_CONF_KEY + "=<comma separated list of args for filter");
436 System.err.println(" NOTE: The filter will be applied BEFORE doing key renames via the "
437 + CF_RENAME_PROP + " property. Futher, filters will only use the"
438 + "Filter#filterKeyValue(KeyValue) method to determine if the KeyValue should be added;"
439 + " Filter.ReturnCode#INCLUDE and #INCLUDE_AND_NEXT_COL will be considered as including "
440 + "the KeyValue.");
441 System.err.println("For performance consider the following options:\n"
442 + " -Dmapred.map.tasks.speculative.execution=false\n"
443 + " -Dmapred.reduce.tasks.speculative.execution=false");
444 }
445
446
447
448
449
450
451
452 public static void main(String[] args) throws Exception {
453 Configuration conf = HBaseConfiguration.create();
454 String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
455 if (otherArgs.length < 2) {
456 usage("Wrong number of arguments: " + otherArgs.length);
457 System.exit(-1);
458 }
459 Job job = createSubmittableJob(conf, otherArgs);
460 System.exit(job.waitForCompletion(true) ? 0 : 1);
461 }
462 }