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