001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.mapreduce;
019
020import java.io.IOException;
021import java.text.ParseException;
022import java.text.SimpleDateFormat;
023import java.util.ArrayList;
024import java.util.HashSet;
025import java.util.List;
026import java.util.Map;
027import java.util.Set;
028import java.util.TreeMap;
029import org.apache.hadoop.conf.Configuration;
030import org.apache.hadoop.conf.Configured;
031import org.apache.hadoop.fs.Path;
032import org.apache.hadoop.hbase.Cell;
033import org.apache.hadoop.hbase.CellUtil;
034import org.apache.hadoop.hbase.HBaseConfiguration;
035import org.apache.hadoop.hbase.TableName;
036import org.apache.hadoop.hbase.client.Connection;
037import org.apache.hadoop.hbase.client.ConnectionFactory;
038import org.apache.hadoop.hbase.client.Delete;
039import org.apache.hadoop.hbase.client.Mutation;
040import org.apache.hadoop.hbase.client.Put;
041import org.apache.hadoop.hbase.client.RegionLocator;
042import org.apache.hadoop.hbase.client.Table;
043import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
044import org.apache.hadoop.hbase.mapreduce.HFileOutputFormat2.TableInfo;
045import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
046import org.apache.hadoop.hbase.util.Bytes;
047import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
048import org.apache.hadoop.hbase.util.MapReduceExtendedCell;
049import org.apache.hadoop.hbase.wal.WALEdit;
050import org.apache.hadoop.hbase.wal.WALKey;
051import org.apache.hadoop.mapreduce.Job;
052import org.apache.hadoop.mapreduce.Mapper;
053import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
054import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
055import org.apache.hadoop.util.Tool;
056import org.apache.hadoop.util.ToolRunner;
057import org.apache.yetus.audience.InterfaceAudience;
058import org.slf4j.Logger;
059import org.slf4j.LoggerFactory;
060
061
062
063/**
064 * A tool to replay WAL files as a M/R job.
065 * The WAL can be replayed for a set of tables or all tables,
066 * and a time range can be provided (in milliseconds).
067 * The WAL is filtered to the passed set of tables and  the output
068 * can optionally be mapped to another set of tables.
069 *
070 * WAL replay can also generate HFiles for later bulk importing,
071 * in that case the WAL is replayed for a single table only.
072 */
073@InterfaceAudience.Public
074public class WALPlayer extends Configured implements Tool {
075  private static final Logger LOG = LoggerFactory.getLogger(WALPlayer.class);
076  final static String NAME = "WALPlayer";
077  public final static String BULK_OUTPUT_CONF_KEY = "wal.bulk.output";
078  public final static String TABLES_KEY = "wal.input.tables";
079  public final static String TABLE_MAP_KEY = "wal.input.tablesmap";
080  public final static String INPUT_FILES_SEPARATOR_KEY = "wal.input.separator";
081  public final static String IGNORE_MISSING_FILES = "wal.input.ignore.missing.files";
082  public final static String MULTI_TABLES_SUPPORT = "wal.multi.tables.support";
083
084  protected static final String tableSeparator = ";";
085
086  private final static String JOB_NAME_CONF_KEY = "mapreduce.job.name";
087
088  public WALPlayer() {
089  }
090
091  protected WALPlayer(final Configuration c) {
092    super(c);
093  }
094
095  /**
096   * A mapper that just writes out KeyValues. This one can be used together with
097   * {@link CellSortReducer}
098   */
099  static class WALKeyValueMapper extends Mapper<WALKey, WALEdit, ImmutableBytesWritable, Cell> {
100    private Set<String> tableSet = new HashSet<String>();
101    private boolean multiTableSupport = false;
102
103    @Override
104    public void map(WALKey key, WALEdit value, Context context) throws IOException {
105      try {
106        // skip all other tables
107        TableName table = key.getTableName();
108        if (tableSet.contains(table.getNameAsString())) {
109          for (Cell cell : value.getCells()) {
110            if (WALEdit.isMetaEditFamily(cell)) {
111              continue;
112            }
113            byte[] outKey = multiTableSupport
114                ? Bytes.add(table.getName(), Bytes.toBytes(tableSeparator), CellUtil.cloneRow(cell))
115                : CellUtil.cloneRow(cell);
116            context.write(new ImmutableBytesWritable(outKey), new MapReduceExtendedCell(cell));
117          }
118        }
119      } catch (InterruptedException e) {
120        LOG.error("Interrupted while emitting Cell", e);
121        Thread.currentThread().interrupt();
122      }
123    }
124
125    @Override
126    public void setup(Context context) throws IOException {
127      Configuration conf = context.getConfiguration();
128      String[] tables = conf.getStrings(TABLES_KEY);
129      this.multiTableSupport = conf.getBoolean(MULTI_TABLES_SUPPORT, false);
130      for (String table : tables) {
131        tableSet.add(table);
132      }
133    }
134  }
135
136  /**
137   * Enum for map metrics.  Keep it out here rather than inside in the Map
138   * inner-class so we can find associated properties.
139   */
140  protected static enum Counter {
141    /** Number of aggregated writes */
142    PUTS,
143    /** Number of aggregated deletes */
144    DELETES,
145    CELLS_READ,
146    CELLS_WRITTEN,
147    WALEDITS
148  }
149
150  /**
151   * A mapper that writes out {@link Mutation} to be directly applied to
152   * a running HBase instance.
153   */
154  protected static class WALMapper
155      extends Mapper<WALKey, WALEdit, ImmutableBytesWritable, Mutation> {
156    private Map<TableName, TableName> tables = new TreeMap<>();
157
158    @Override
159    public void map(WALKey key, WALEdit value, Context context) throws IOException {
160      context.getCounter(Counter.WALEDITS).increment(1);
161      try {
162        if (tables.isEmpty() || tables.containsKey(key.getTableName())) {
163          TableName targetTable =
164              tables.isEmpty() ? key.getTableName() : tables.get(key.getTableName());
165          ImmutableBytesWritable tableOut = new ImmutableBytesWritable(targetTable.getName());
166          Put put = null;
167          Delete del = null;
168          Cell lastCell = null;
169          for (Cell cell : value.getCells()) {
170            context.getCounter(Counter.CELLS_READ).increment(1);
171            // Filtering WAL meta marker entries.
172            if (WALEdit.isMetaEditFamily(cell)) {
173              continue;
174            }
175            // Allow a subclass filter out this cell.
176            if (filter(context, cell)) {
177              // A WALEdit may contain multiple operations (HBASE-3584) and/or
178              // multiple rows (HBASE-5229).
179              // Aggregate as much as possible into a single Put/Delete
180              // operation before writing to the context.
181              if (lastCell == null || lastCell.getTypeByte() != cell.getTypeByte()
182                  || !CellUtil.matchingRows(lastCell, cell)) {
183                // row or type changed, write out aggregate KVs.
184                if (put != null) {
185                  context.write(tableOut, put);
186                  context.getCounter(Counter.PUTS).increment(1);
187                }
188                if (del != null) {
189                  context.write(tableOut, del);
190                  context.getCounter(Counter.DELETES).increment(1);
191                }
192                if (CellUtil.isDelete(cell)) {
193                  del = new Delete(CellUtil.cloneRow(cell));
194                } else {
195                  put = new Put(CellUtil.cloneRow(cell));
196                }
197              }
198              if (CellUtil.isDelete(cell)) {
199                del.add(cell);
200              } else {
201                put.add(cell);
202              }
203              context.getCounter(Counter.CELLS_WRITTEN).increment(1);
204            }
205            lastCell = cell;
206          }
207          // write residual KVs
208          if (put != null) {
209            context.write(tableOut, put);
210            context.getCounter(Counter.PUTS).increment(1);
211          }
212          if (del != null) {
213            context.getCounter(Counter.DELETES).increment(1);
214            context.write(tableOut, del);
215          }
216        }
217      } catch (InterruptedException e) {
218        LOG.error("Interrupted while writing results", e);
219        Thread.currentThread().interrupt();
220      }
221    }
222
223    protected boolean filter(Context context, final Cell cell) {
224      return true;
225    }
226
227    @Override
228    protected void
229        cleanup(Mapper<WALKey, WALEdit, ImmutableBytesWritable, Mutation>.Context context)
230            throws IOException, InterruptedException {
231      super.cleanup(context);
232    }
233
234    @SuppressWarnings("checkstyle:EmptyBlock")
235    @Override
236    public void setup(Context context) throws IOException {
237      String[] tableMap = context.getConfiguration().getStrings(TABLE_MAP_KEY);
238      String[] tablesToUse = context.getConfiguration().getStrings(TABLES_KEY);
239      if (tableMap == null) {
240        tableMap = tablesToUse;
241      }
242      if (tablesToUse == null) {
243        // Then user wants all tables.
244      } else if (tablesToUse.length != tableMap.length) {
245        // this can only happen when WALMapper is used directly by a class other than WALPlayer
246        throw new IOException("Incorrect table mapping specified .");
247      }
248      int i = 0;
249      if (tablesToUse != null) {
250        for (String table : tablesToUse) {
251          tables.put(TableName.valueOf(table), TableName.valueOf(tableMap[i++]));
252        }
253      }
254    }
255  }
256
257  void setupTime(Configuration conf, String option) throws IOException {
258    String val = conf.get(option);
259    if (null == val) {
260      return;
261    }
262    long ms;
263    try {
264      // first try to parse in user friendly form
265      ms = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS").parse(val).getTime();
266    } catch (ParseException pe) {
267      try {
268        // then see if just a number of ms's was specified
269        ms = Long.parseLong(val);
270      } catch (NumberFormatException nfe) {
271        throw new IOException(
272            option + " must be specified either in the form 2001-02-20T16:35:06.99 "
273                + "or as number of milliseconds");
274      }
275    }
276    conf.setLong(option, ms);
277  }
278
279  /**
280   * Sets up the actual job.
281   * @param args The command line parameters.
282   * @return The newly created job.
283   * @throws IOException When setting up the job fails.
284   */
285  public Job createSubmittableJob(String[] args) throws IOException {
286    Configuration conf = getConf();
287    setupTime(conf, WALInputFormat.START_TIME_KEY);
288    setupTime(conf, WALInputFormat.END_TIME_KEY);
289    String inputDirs = args[0];
290    String[] tables = args.length == 1? new String [] {}: args[1].split(",");
291    String[] tableMap;
292    if (args.length > 2) {
293      tableMap = args[2].split(",");
294      if (tableMap.length != tables.length) {
295        throw new IOException("The same number of tables and mapping must be provided.");
296      }
297    } else {
298      // if no mapping is specified, map each table to itself
299      tableMap = tables;
300    }
301    conf.setStrings(TABLES_KEY, tables);
302    conf.setStrings(TABLE_MAP_KEY, tableMap);
303    conf.set(FileInputFormat.INPUT_DIR, inputDirs);
304    Job job = Job.getInstance(conf, conf.get(JOB_NAME_CONF_KEY, NAME + "_" +
305      EnvironmentEdgeManager.currentTime()));
306    job.setJarByClass(WALPlayer.class);
307
308    job.setInputFormatClass(WALInputFormat.class);
309    job.setMapOutputKeyClass(ImmutableBytesWritable.class);
310
311    String hfileOutPath = conf.get(BULK_OUTPUT_CONF_KEY);
312    if (hfileOutPath != null) {
313      LOG.debug("add incremental job :" + hfileOutPath + " from " + inputDirs);
314
315      // the bulk HFile case
316      List<TableName> tableNames = getTableNameList(tables);
317
318      job.setMapperClass(WALKeyValueMapper.class);
319      job.setReducerClass(CellSortReducer.class);
320      Path outputDir = new Path(hfileOutPath);
321      FileOutputFormat.setOutputPath(job, outputDir);
322      job.setMapOutputValueClass(MapReduceExtendedCell.class);
323      try (Connection conn = ConnectionFactory.createConnection(conf);) {
324        List<TableInfo> tableInfoList = new ArrayList<TableInfo>();
325        for (TableName tableName : tableNames) {
326          Table table = conn.getTable(tableName);
327          RegionLocator regionLocator = conn.getRegionLocator(tableName);
328          tableInfoList.add(new TableInfo(table.getDescriptor(), regionLocator));
329        }
330        MultiTableHFileOutputFormat.configureIncrementalLoad(job, tableInfoList);
331      }
332      TableMapReduceUtil.addDependencyJarsForClasses(job.getConfiguration(),
333        org.apache.hbase.thirdparty.com.google.common.base.Preconditions.class);
334    } else {
335      // output to live cluster
336      job.setMapperClass(WALMapper.class);
337      job.setOutputFormatClass(MultiTableOutputFormat.class);
338      TableMapReduceUtil.addDependencyJars(job);
339      TableMapReduceUtil.initCredentials(job);
340      // No reducers.
341      job.setNumReduceTasks(0);
342    }
343    String codecCls = WALCellCodec.getWALCellCodecClass(conf).getName();
344    try {
345      TableMapReduceUtil.addDependencyJarsForClasses(job.getConfiguration(),
346        Class.forName(codecCls));
347    } catch (Exception e) {
348      throw new IOException("Cannot determine wal codec class " + codecCls, e);
349    }
350    return job;
351  }
352
353  private List<TableName> getTableNameList(String[] tables) {
354    List<TableName> list = new ArrayList<TableName>();
355    for (String name : tables) {
356      list.add(TableName.valueOf(name));
357    }
358    return list;
359  }
360
361  /**
362   * Print usage
363   * @param errorMsg Error message. Can be null.
364   */
365  private void usage(final String errorMsg) {
366    if (errorMsg != null && errorMsg.length() > 0) {
367      System.err.println("ERROR: " + errorMsg);
368    }
369    System.err.println("Usage: " + NAME + " [options] <WAL inputdir> [<tables> <tableMappings>]");
370    System.err.println(" <WAL inputdir>   directory of WALs to replay.");
371    System.err.println(" <tables>         comma separated list of tables. If no tables specified,");
372    System.err.println("                  all are imported (even hbase:meta if present).");
373    System.err.println(" <tableMappings>  WAL entries can be mapped to a new set of tables by " +
374      "passing");
375    System.err.println("                  <tableMappings>, a comma separated list of target " +
376      "tables.");
377    System.err.println("                  If specified, each table in <tables> must have a " +
378      "mapping.");
379    System.err.println("To generate HFiles to bulk load instead of loading HBase directly, pass:");
380    System.err.println(" -D" + BULK_OUTPUT_CONF_KEY + "=/path/for/output");
381    System.err.println(" Only one table can be specified, and no mapping allowed!");
382    System.err.println("To specify a time range, pass:");
383    System.err.println(" -D" + WALInputFormat.START_TIME_KEY + "=[date|ms]");
384    System.err.println(" -D" + WALInputFormat.END_TIME_KEY + "=[date|ms]");
385    System.err.println(" The start and the end date of timerange (inclusive). The dates can be");
386    System.err.println(" expressed in milliseconds-since-epoch or yyyy-MM-dd'T'HH:mm:ss.SS " +
387      "format.");
388    System.err.println(" E.g. 1234567890120 or 2009-02-13T23:32:30.12");
389    System.err.println("Other options:");
390    System.err.println(" -D" + JOB_NAME_CONF_KEY + "=jobName");
391    System.err.println(" Use the specified mapreduce job name for the wal player");
392    System.err.println(" -Dwal.input.separator=' '");
393    System.err.println(" Change WAL filename separator (WAL dir names use default ','.)");
394    System.err.println("For performance also consider the following options:\n"
395        + "  -Dmapreduce.map.speculative=false\n"
396        + "  -Dmapreduce.reduce.speculative=false");
397  }
398
399  /**
400   * Main entry point.
401   * @param args The command line parameters.
402   * @throws Exception When running the job fails.
403   */
404  public static void main(String[] args) throws Exception {
405    int ret = ToolRunner.run(new WALPlayer(HBaseConfiguration.create()), args);
406    System.exit(ret);
407  }
408
409  @Override
410  public int run(String[] args) throws Exception {
411    if (args.length < 1) {
412      usage("Wrong number of arguments: " + args.length);
413      System.exit(-1);
414    }
415    Job job = createSubmittableJob(args);
416    return job.waitForCompletion(true) ? 0 : 1;
417  }
418}