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