View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.mapreduce;
19  
20  import org.apache.commons.logging.Log;
21  import org.apache.commons.logging.LogFactory;
22  import org.apache.hadoop.conf.Configuration;
23  import org.apache.hadoop.conf.Configured;
24  import org.apache.hadoop.fs.Path;
25  import org.apache.hadoop.hbase.Cell;
26  import org.apache.hadoop.hbase.CellUtil;
27  import org.apache.hadoop.hbase.HBaseConfiguration;
28  import org.apache.hadoop.hbase.KeyValue;
29  import org.apache.hadoop.hbase.KeyValueUtil;
30  import org.apache.hadoop.hbase.TableName;
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.classification.InterfaceStability;
33  import org.apache.hadoop.hbase.client.Connection;
34  import org.apache.hadoop.hbase.client.ConnectionFactory;
35  import org.apache.hadoop.hbase.client.Delete;
36  import org.apache.hadoop.hbase.client.Mutation;
37  import org.apache.hadoop.hbase.client.Put;
38  import org.apache.hadoop.hbase.client.RegionLocator;
39  import org.apache.hadoop.hbase.client.Table;
40  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
41  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
42  import org.apache.hadoop.hbase.util.Bytes;
43  import org.apache.hadoop.hbase.wal.WALKey;
44  import org.apache.hadoop.mapreduce.Job;
45  import org.apache.hadoop.mapreduce.Mapper;
46  import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
47  import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
48  import org.apache.hadoop.util.Tool;
49  import org.apache.hadoop.util.ToolRunner;
50  
51  import java.io.IOException;
52  import java.text.ParseException;
53  import java.text.SimpleDateFormat;
54  import java.util.Map;
55  import java.util.TreeMap;
56  
57  /**
58   * A tool to replay WAL files as a M/R job.
59   * The WAL can be replayed for a set of tables or all tables,
60   * and a timerange can be provided (in milliseconds).
61   * The WAL is filtered to the passed set of tables and  the output
62   * can optionally be mapped to another set of tables.
63   *
64   * WAL replay can also generate HFiles for later bulk importing,
65   * in that case the WAL is replayed for a single table only.
66   */
67  @InterfaceAudience.Public
68  @InterfaceStability.Stable
69  public class WALPlayer extends Configured implements Tool {
70    private static final Log LOG = LogFactory.getLog(WALPlayer.class);
71    final static String NAME = "WALPlayer";
72    final static String BULK_OUTPUT_CONF_KEY = "wal.bulk.output";
73    final static String TABLES_KEY = "wal.input.tables";
74    final static String TABLE_MAP_KEY = "wal.input.tablesmap";
75  
76    // This relies on Hadoop Configuration to handle warning about deprecated configs and
77    // to set the correct non-deprecated configs when an old one shows up.
78    static {
79      Configuration.addDeprecation("hlog.bulk.output", BULK_OUTPUT_CONF_KEY);
80      Configuration.addDeprecation("hlog.input.tables", TABLES_KEY);
81      Configuration.addDeprecation("hlog.input.tablesmap", TABLE_MAP_KEY);
82      Configuration.addDeprecation(HLogInputFormat.START_TIME_KEY, WALInputFormat.START_TIME_KEY);
83      Configuration.addDeprecation(HLogInputFormat.END_TIME_KEY, WALInputFormat.END_TIME_KEY);
84    }
85  
86    private final static String JOB_NAME_CONF_KEY = "mapreduce.job.name";
87  
88    /**
89     * A mapper that just writes out KeyValues.
90     * This one can be used together with {@link KeyValueSortReducer}
91     */
92    static class WALKeyValueMapper
93    extends Mapper<WALKey, WALEdit, ImmutableBytesWritable, KeyValue> {
94      private byte[] table;
95  
96      @Override
97      public void map(WALKey key, WALEdit value,
98        Context context)
99      throws IOException {
100       try {
101         // skip all other tables
102         if (Bytes.equals(table, key.getTablename().getName())) {
103           for (Cell cell : value.getCells()) {
104             KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
105             if (WALEdit.isMetaEditFamily(kv.getFamily())) continue;
106             context.write(new ImmutableBytesWritable(kv.getRow()), kv);
107           }
108         }
109       } catch (InterruptedException e) {
110         e.printStackTrace();
111       }
112     }
113 
114     @Override
115     public void setup(Context context) throws IOException {
116       // only a single table is supported when HFiles are generated with HFileOutputFormat
117       String[] tables = context.getConfiguration().getStrings(TABLES_KEY);
118       if (tables == null || tables.length != 1) {
119         // this can only happen when WALMapper is used directly by a class other than WALPlayer
120         throw new IOException("Exactly one table must be specified for bulk HFile case.");
121       }
122       table = Bytes.toBytes(tables[0]);
123     }
124   }
125 
126   /**
127    * A mapper that writes out {@link Mutation} to be directly applied to
128    * a running HBase instance.
129    */
130   protected static class WALMapper
131   extends Mapper<WALKey, WALEdit, ImmutableBytesWritable, Mutation> {
132     private Map<TableName, TableName> tables = new TreeMap<TableName, TableName>();
133 
134     @Override
135     public void map(WALKey key, WALEdit value, Context context)
136     throws IOException {
137       try {
138         if (tables.isEmpty() || tables.containsKey(key.getTablename())) {
139           TableName targetTable = tables.isEmpty() ?
140                 key.getTablename() :
141                 tables.get(key.getTablename());
142           ImmutableBytesWritable tableOut = new ImmutableBytesWritable(targetTable.getName());
143           Put put = null;
144           Delete del = null;
145           Cell lastCell = null;
146           for (Cell cell : value.getCells()) {
147             // filtering WAL meta entries
148             if (WALEdit.isMetaEditFamily(cell.getFamily())) continue;
149 
150             // Allow a subclass filter out this cell.
151             if (filter(context, cell)) {
152               // A WALEdit may contain multiple operations (HBASE-3584) and/or
153               // multiple rows (HBASE-5229).
154               // Aggregate as much as possible into a single Put/Delete
155               // operation before writing to the context.
156               if (lastCell == null || lastCell.getTypeByte() != cell.getTypeByte()
157                   || !CellUtil.matchingRow(lastCell, cell)) {
158                 // row or type changed, write out aggregate KVs.
159                 if (put != null) context.write(tableOut, put);
160                 if (del != null) context.write(tableOut, del);
161                 if (CellUtil.isDelete(cell)) {
162                   del = new Delete(cell.getRow());
163                 } else {
164                   put = new Put(cell.getRow());
165                 }
166               }
167               if (CellUtil.isDelete(cell)) {
168                 del.addDeleteMarker(cell);
169               } else {
170                 put.add(cell);
171               }
172             }
173             lastCell = cell;
174           }
175           // write residual KVs
176           if (put != null) context.write(tableOut, put);
177           if (del != null) context.write(tableOut, del);
178         }
179       } catch (InterruptedException e) {
180         e.printStackTrace();
181       }
182     }
183 
184     /**
185      * @param cell
186      * @return Return true if we are to emit this cell.
187      */
188     protected boolean filter(Context context, final Cell cell) {
189       return true;
190     }
191 
192     @Override
193     public void setup(Context context) throws IOException {
194       String[] tableMap = context.getConfiguration().getStrings(TABLE_MAP_KEY);
195       String[] tablesToUse = context.getConfiguration().getStrings(TABLES_KEY);
196       if (tablesToUse == null && tableMap == null) {
197         // Then user wants all tables.
198       } else if (tablesToUse == null || tableMap == null || tablesToUse.length != tableMap.length) {
199         // this can only happen when WALMapper is used directly by a class other than WALPlayer
200         throw new IOException("No tables or incorrect table mapping specified.");
201       }
202       int i = 0;
203       if (tablesToUse != null) {
204         for (String table : tablesToUse) {
205           tables.put(TableName.valueOf(table),
206             TableName.valueOf(tableMap[i++]));
207         }
208       }
209     }
210   }
211 
212   void setupTime(Configuration conf, String option) throws IOException {
213     String val = conf.get(option);
214     if (null == val) return;
215     long ms;
216     try {
217       // first try to parse in user friendly form
218       ms = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS").parse(val).getTime();
219     } catch (ParseException pe) {
220       try {
221         // then see if just a number of ms's was specified
222         ms = Long.parseLong(val);
223       } catch (NumberFormatException nfe) {
224         throw new IOException(option
225             + " must be specified either in the form 2001-02-20T16:35:06.99 "
226             + "or as number of milliseconds");
227       }
228     }
229     conf.setLong(option, ms);
230   }
231 
232   /**
233    * Sets up the actual job.
234    *
235    * @param args  The command line parameters.
236    * @return The newly created job.
237    * @throws IOException When setting up the job fails.
238    */
239   public Job createSubmittableJob(String[] args)
240   throws IOException {
241     Configuration conf = getConf();
242     setupTime(conf, HLogInputFormat.START_TIME_KEY);
243     setupTime(conf, HLogInputFormat.END_TIME_KEY);
244     Path inputDir = new Path(args[0]);
245     String[] tables = args[1].split(",");
246     String[] tableMap;
247     if (args.length > 2) {
248       tableMap = args[2].split(",");
249       if (tableMap.length != tables.length) {
250         throw new IOException("The same number of tables and mapping must be provided.");
251       }
252     } else {
253       // if not mapping is specified map each table to itself
254       tableMap = tables;
255     }
256     conf.setStrings(TABLES_KEY, tables);
257     conf.setStrings(TABLE_MAP_KEY, tableMap);
258     Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" + inputDir));
259     job.setJarByClass(WALPlayer.class);
260     FileInputFormat.setInputPaths(job, inputDir);
261     job.setInputFormatClass(WALInputFormat.class);
262     job.setMapOutputKeyClass(ImmutableBytesWritable.class);
263     String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);
264     if (hfileOutPath != null) {
265       // the bulk HFile case
266       if (tables.length != 1) {
267         throw new IOException("Exactly one table must be specified for the bulk export option");
268       }
269       TableName tableName = TableName.valueOf(tables[0]);
270       job.setMapperClass(WALKeyValueMapper.class);
271       job.setReducerClass(KeyValueSortReducer.class);
272       Path outputDir = new Path(hfileOutPath);
273       FileOutputFormat.setOutputPath(job, outputDir);
274       job.setMapOutputValueClass(KeyValue.class);
275       try (Connection conn = ConnectionFactory.createConnection(conf);
276           Table table = conn.getTable(tableName);
277           RegionLocator regionLocator = conn.getRegionLocator(tableName)) {
278         HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(), regionLocator);
279       }
280       TableMapReduceUtil.addDependencyJars(job.getConfiguration(),
281           com.google.common.base.Preconditions.class);
282     } else {
283       // output to live cluster
284       job.setMapperClass(WALMapper.class);
285       job.setOutputFormatClass(MultiTableOutputFormat.class);
286       TableMapReduceUtil.addDependencyJars(job);
287       TableMapReduceUtil.initCredentials(job);
288       // No reducers.
289       job.setNumReduceTasks(0);
290     }
291     return job;
292   }
293 
294   /*
295    * @param errorMsg Error message.  Can be null.
296    */
297   private void usage(final String errorMsg) {
298     if (errorMsg != null && errorMsg.length() > 0) {
299       System.err.println("ERROR: " + errorMsg);
300     }
301     System.err.println("Usage: " + NAME + " [options] <wal inputdir> <tables> [<tableMappings>]");
302     System.err.println("Read all WAL entries for <tables>.");
303     System.err.println("If no tables (\"\") are specific, all tables are imported.");
304     System.err.println("(Careful, even -ROOT- and hbase:meta entries will be imported in that case.)");
305     System.err.println("Otherwise <tables> is a comma separated list of tables.\n");
306     System.err.println("The WAL entries can be mapped to new set of tables via <tableMapping>.");
307     System.err.println("<tableMapping> is a command separated list of targettables.");
308     System.err.println("If specified, each table in <tables> must have a mapping.\n");
309     System.err.println("By default " + NAME + " will load data directly into HBase.");
310     System.err.println("To generate HFiles for a bulk data load instead, pass the option:");
311     System.err.println("  -D" + BULK_OUTPUT_CONF_KEY + "=/path/for/output");
312     System.err.println("  (Only one table can be specified, and no mapping is allowed!)");
313     System.err.println("Other options: (specify time range to WAL edit to consider)");
314     System.err.println("  -D" + WALInputFormat.START_TIME_KEY + "=[date|ms]");
315     System.err.println("  -D" + WALInputFormat.END_TIME_KEY + "=[date|ms]");
316     System.err.println("   -D " + JOB_NAME_CONF_KEY
317         + "=jobName - use the specified mapreduce job name for the wal player");
318     System.err.println("For performance also consider the following options:\n"
319         + "  -Dmapreduce.map.speculative=false\n"
320         + "  -Dmapreduce.reduce.speculative=false");
321   }
322 
323   /**
324    * Main entry point.
325    *
326    * @param args  The command line parameters.
327    * @throws Exception When running the job fails.
328    */
329   public static void main(String[] args) throws Exception {
330     int ret = ToolRunner.run(HBaseConfiguration.create(), new WALPlayer(), args);
331     System.exit(ret);
332   }
333 
334   @Override
335   public int run(String[] args) throws Exception {
336     if (args.length < 2) {
337       usage("Wrong number of arguments: " + args.length);
338       System.exit(-1);
339     }
340     Job job = createSubmittableJob(args);
341     return job.waitForCompletion(true) ? 0 : 1;
342   }
343 }