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.backup.impl; 019 020import static org.apache.hadoop.hbase.backup.BackupInfo.withState; 021import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.CONF_CONTINUOUS_BACKUP_PITR_WINDOW_DAYS; 022import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.CONF_CONTINUOUS_BACKUP_WAL_DIR; 023import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.CONTINUOUS_BACKUP_REPLICATION_PEER; 024import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.DEFAULT_CONTINUOUS_BACKUP_PITR_WINDOW_DAYS; 025import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_BACKUP_LIST_DESC; 026import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_BANDWIDTH; 027import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_BANDWIDTH_DESC; 028import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_DEBUG; 029import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_DEBUG_DESC; 030import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_ENABLE_CONTINUOUS_BACKUP; 031import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_ENABLE_CONTINUOUS_BACKUP_DESC; 032import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_FORCE_DELETE; 033import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_FORCE_DELETE_DESC; 034import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_IGNORECHECKSUM; 035import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_IGNORECHECKSUM_DESC; 036import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_KEEP; 037import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_KEEP_DESC; 038import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_LIST; 039import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_PATH; 040import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_PATH_DESC; 041import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_RECORD_NUMBER; 042import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_RECORD_NUMBER_DESC; 043import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_SET; 044import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_SET_BACKUP_DESC; 045import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_SET_DESC; 046import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_TABLE; 047import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_TABLE_DESC; 048import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_TABLE_LIST_DESC; 049import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_WORKERS; 050import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_WORKERS_DESC; 051import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_YARN_QUEUE_NAME; 052import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.OPTION_YARN_QUEUE_NAME_DESC; 053import static org.apache.hadoop.hbase.backup.HBackupFileSystem.writeBackupCompleteMarker; 054import static org.apache.hadoop.hbase.backup.impl.BackupSystemTable.Order.NEW_TO_OLD; 055import static org.apache.hadoop.hbase.backup.replication.ContinuousBackupReplicationEndpoint.ONE_DAY_IN_MILLISECONDS; 056import static org.apache.hadoop.hbase.backup.util.BackupUtils.DATE_FORMAT; 057 058import java.io.IOException; 059import java.net.URI; 060import java.text.ParseException; 061import java.text.SimpleDateFormat; 062import java.util.ArrayList; 063import java.util.Collections; 064import java.util.HashSet; 065import java.util.List; 066import java.util.Map; 067import java.util.Optional; 068import java.util.Set; 069import java.util.TimeZone; 070import java.util.concurrent.TimeUnit; 071import org.apache.commons.lang3.StringUtils; 072import org.apache.hadoop.conf.Configuration; 073import org.apache.hadoop.conf.Configured; 074import org.apache.hadoop.fs.FileStatus; 075import org.apache.hadoop.fs.FileSystem; 076import org.apache.hadoop.fs.Path; 077import org.apache.hadoop.hbase.HBaseConfiguration; 078import org.apache.hadoop.hbase.TableName; 079import org.apache.hadoop.hbase.backup.BackupAdmin; 080import org.apache.hadoop.hbase.backup.BackupInfo; 081import org.apache.hadoop.hbase.backup.BackupInfo.BackupState; 082import org.apache.hadoop.hbase.backup.BackupRequest; 083import org.apache.hadoop.hbase.backup.BackupRestoreConstants; 084import org.apache.hadoop.hbase.backup.BackupRestoreConstants.BackupCommand; 085import org.apache.hadoop.hbase.backup.BackupType; 086import org.apache.hadoop.hbase.backup.HBackupFileSystem; 087import org.apache.hadoop.hbase.backup.util.BackupFileSystemManager; 088import org.apache.hadoop.hbase.backup.util.BackupSet; 089import org.apache.hadoop.hbase.backup.util.BackupUtils; 090import org.apache.hadoop.hbase.client.Admin; 091import org.apache.hadoop.hbase.client.Connection; 092import org.apache.hadoop.hbase.client.ConnectionFactory; 093import org.apache.hadoop.hbase.replication.ReplicationPeerDescription; 094import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 095import org.apache.hadoop.hbase.util.Pair; 096import org.apache.yetus.audience.InterfaceAudience; 097 098import org.apache.hbase.thirdparty.com.google.common.base.Splitter; 099import org.apache.hbase.thirdparty.com.google.common.base.Strings; 100import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 101import org.apache.hbase.thirdparty.org.apache.commons.cli.CommandLine; 102import org.apache.hbase.thirdparty.org.apache.commons.cli.HelpFormatter; 103import org.apache.hbase.thirdparty.org.apache.commons.cli.Options; 104 105/** 106 * General backup commands, options and usage messages 107 */ 108@InterfaceAudience.Private 109public final class BackupCommands { 110 public final static String INCORRECT_USAGE = "Incorrect usage"; 111 112 public final static String TOP_LEVEL_NOT_ALLOWED = 113 "Top level (root) folder is not allowed to be a backup destination"; 114 115 public static final String USAGE = "Usage: hbase backup COMMAND [command-specific arguments]\n" 116 + "where COMMAND is one of:\n" + " create create a new backup image\n" 117 + " delete delete an existing backup image\n" 118 + " describe show the detailed information of a backup image\n" 119 + " history show history of all successful backups\n" 120 + " progress show the progress of the latest backup request\n" 121 + " set backup set management\n" + " repair repair backup system table\n" 122 + " merge merge backup images\n" 123 + "Run \'hbase backup COMMAND -h\' to see help message for each command\n"; 124 125 public static final String CREATE_CMD_USAGE = 126 "Usage: hbase backup create <type> <backup_path> [options]\n" 127 + " type \"full\" to create a full backup image\n" 128 + " \"incremental\" to create an incremental backup image\n" 129 + " backup_path Full path to store the backup image\n"; 130 131 public static final String PROGRESS_CMD_USAGE = "Usage: hbase backup progress <backup_id>\n" 132 + " backup_id Backup image id (optional). If no id specified, the command will show\n" 133 + " progress for currently running backup session."; 134 public static final String NO_INFO_FOUND = "No info was found for backup id: "; 135 public static final String NO_ACTIVE_SESSION_FOUND = "No active backup sessions found."; 136 137 public static final String DESCRIBE_CMD_USAGE = 138 "Usage: hbase backup describe <backup_id>\n" + " backup_id Backup image id\n"; 139 140 public static final String HISTORY_CMD_USAGE = "Usage: hbase backup history [options]"; 141 142 public static final String DELETE_CMD_USAGE = "Usage: hbase backup delete [options]"; 143 144 public static final String REPAIR_CMD_USAGE = "Usage: hbase backup repair\n"; 145 146 public static final String SET_CMD_USAGE = "Usage: hbase backup set COMMAND [name] [tables]\n" 147 + " name Backup set name\n" + " tables Comma separated list of tables.\n" 148 + "COMMAND is one of:\n" + " add add tables to a set, create a set if needed\n" 149 + " remove remove tables from a set\n" 150 + " list list all backup sets in the system\n" + " describe describe set\n" 151 + " delete delete backup set\n"; 152 public static final String MERGE_CMD_USAGE = "Usage: hbase backup merge [backup_ids]\n" 153 + " backup_ids Comma separated list of backup image ids.\n"; 154 155 public static final String USAGE_FOOTER = ""; 156 157 public static abstract class Command extends Configured { 158 CommandLine cmdline; 159 Connection conn; 160 161 Command(Configuration conf) { 162 if (conf == null) { 163 conf = HBaseConfiguration.create(); 164 } 165 setConf(conf); 166 } 167 168 public void execute() throws IOException { 169 if (cmdline.hasOption("h") || cmdline.hasOption("help")) { 170 printUsage(); 171 throw new IOException(INCORRECT_USAGE); 172 } 173 174 if (cmdline.hasOption(OPTION_YARN_QUEUE_NAME)) { 175 String queueName = cmdline.getOptionValue(OPTION_YARN_QUEUE_NAME); 176 // Set MR job queuename to configuration 177 getConf().set("mapreduce.job.queuename", queueName); 178 } 179 180 // Create connection 181 conn = ConnectionFactory.createConnection(getConf()); 182 if (requiresNoActiveSession()) { 183 // Check active session 184 try (BackupSystemTable table = new BackupSystemTable(conn)) { 185 List<BackupInfo> sessions = 186 table.getBackupHistory(NEW_TO_OLD, 1, withState(BackupState.RUNNING)); 187 188 if (sessions.size() > 0) { 189 System.err.println("Found backup session in a RUNNING state: "); 190 System.err.println(sessions.get(0)); 191 System.err.println("This may indicate that a previous session has failed abnormally."); 192 System.err.println("In this case, backup recovery is recommended."); 193 throw new IOException("Active session found, aborted command execution"); 194 } 195 } 196 } 197 if (requiresConsistentState()) { 198 // Check failed delete 199 try (BackupSystemTable table = new BackupSystemTable(conn)) { 200 String[] ids = table.getListOfBackupIdsFromDeleteOperation(); 201 202 if (ids != null && ids.length > 0) { 203 System.err.println("Found failed backup DELETE coommand. "); 204 System.err.println("Backup system recovery is required."); 205 throw new IOException("Failed backup DELETE found, aborted command execution"); 206 } 207 208 ids = table.getListOfBackupIdsFromMergeOperation(); 209 if (ids != null && ids.length > 0) { 210 System.err.println("Found failed backup MERGE coommand. "); 211 System.err.println("Backup system recovery is required."); 212 throw new IOException("Failed backup MERGE found, aborted command execution"); 213 } 214 } 215 } 216 } 217 218 public void finish() throws IOException { 219 if (conn != null) { 220 conn.close(); 221 } 222 } 223 224 protected abstract void printUsage(); 225 226 /** 227 * The command can't be run if active backup session is in progress 228 * @return true if no active sessions are in progress 229 */ 230 protected boolean requiresNoActiveSession() { 231 return false; 232 } 233 234 /** 235 * Command requires consistent state of a backup system Backup system may become inconsistent 236 * because of an abnormal termination of a backup session or delete command 237 * @return true, if yes 238 */ 239 protected boolean requiresConsistentState() { 240 return false; 241 } 242 } 243 244 private BackupCommands() { 245 throw new AssertionError("Instantiating utility class..."); 246 } 247 248 public static Command createCommand(Configuration conf, BackupCommand type, CommandLine cmdline) { 249 Command cmd; 250 switch (type) { 251 case CREATE: 252 cmd = new CreateCommand(conf, cmdline); 253 break; 254 case DESCRIBE: 255 cmd = new DescribeCommand(conf, cmdline); 256 break; 257 case PROGRESS: 258 cmd = new ProgressCommand(conf, cmdline); 259 break; 260 case DELETE: 261 cmd = new DeleteCommand(conf, cmdline); 262 break; 263 case HISTORY: 264 cmd = new HistoryCommand(conf, cmdline); 265 break; 266 case SET: 267 cmd = new BackupSetCommand(conf, cmdline); 268 break; 269 case REPAIR: 270 cmd = new RepairCommand(conf, cmdline); 271 break; 272 case MERGE: 273 cmd = new MergeCommand(conf, cmdline); 274 break; 275 case HELP: 276 default: 277 cmd = new HelpCommand(conf, cmdline); 278 break; 279 } 280 return cmd; 281 } 282 283 static int numOfArgs(String[] args) { 284 if (args == null) { 285 return 0; 286 } 287 288 return args.length; 289 } 290 291 public static class CreateCommand extends Command { 292 CreateCommand(Configuration conf, CommandLine cmdline) { 293 super(conf); 294 this.cmdline = cmdline; 295 } 296 297 @Override 298 protected boolean requiresNoActiveSession() { 299 return true; 300 } 301 302 @Override 303 protected boolean requiresConsistentState() { 304 return true; 305 } 306 307 @Override 308 public void execute() throws IOException { 309 if (cmdline == null || cmdline.getArgs() == null) { 310 printUsage(); 311 throw new IOException(INCORRECT_USAGE); 312 } 313 String[] args = cmdline.getArgs(); 314 if (args.length != 3) { 315 printUsage(); 316 throw new IOException(INCORRECT_USAGE); 317 } 318 319 if ( 320 !BackupType.FULL.toString().equalsIgnoreCase(args[1]) 321 && !BackupType.INCREMENTAL.toString().equalsIgnoreCase(args[1]) 322 ) { 323 System.out.println("ERROR: invalid backup type: " + args[1]); 324 printUsage(); 325 throw new IOException(INCORRECT_USAGE); 326 } 327 if (!verifyPath(args[2])) { 328 System.out.println("ERROR: invalid backup destination: " + args[2]); 329 printUsage(); 330 throw new IOException(INCORRECT_USAGE); 331 } 332 String targetBackupDir = args[2]; 333 // Check if backup destination is top level (root) folder - not allowed 334 if (isRootFolder(targetBackupDir)) { 335 throw new IOException(TOP_LEVEL_NOT_ALLOWED); 336 } 337 String tables; 338 339 // Check if we have both: backup set and list of tables 340 if (cmdline.hasOption(OPTION_TABLE) && cmdline.hasOption(OPTION_SET)) { 341 System.out 342 .println("ERROR: You can specify either backup set or list" + " of tables, but not both"); 343 printUsage(); 344 throw new IOException(INCORRECT_USAGE); 345 } 346 // Creates connection 347 super.execute(); 348 // Check backup set 349 String setName = null; 350 if (cmdline.hasOption(OPTION_SET)) { 351 setName = cmdline.getOptionValue(OPTION_SET); 352 tables = getTablesForSet(setName); 353 354 if (tables == null) { 355 System.out 356 .println("ERROR: Backup set '" + setName + "' is either empty or does not exist"); 357 printUsage(); 358 throw new IOException(INCORRECT_USAGE); 359 } 360 } else { 361 tables = cmdline.getOptionValue(OPTION_TABLE); 362 } 363 int bandwidth = cmdline.hasOption(OPTION_BANDWIDTH) 364 ? Integer.parseInt(cmdline.getOptionValue(OPTION_BANDWIDTH)) 365 : -1; 366 int workers = cmdline.hasOption(OPTION_WORKERS) 367 ? Integer.parseInt(cmdline.getOptionValue(OPTION_WORKERS)) 368 : -1; 369 370 boolean ignoreChecksum = cmdline.hasOption(OPTION_IGNORECHECKSUM); 371 372 BackupType backupType = BackupType.valueOf(args[1].toUpperCase()); 373 List<TableName> tableNameList = null; 374 if (tables != null) { 375 tableNameList = Lists.newArrayList(BackupUtils.parseTableNames(tables)); 376 } 377 boolean continuousBackup = cmdline.hasOption(OPTION_ENABLE_CONTINUOUS_BACKUP); 378 if (continuousBackup && !BackupType.FULL.equals(backupType)) { 379 System.out.println("ERROR: Continuous backup can Only be specified for Full Backup"); 380 printUsage(); 381 throw new IOException(INCORRECT_USAGE); 382 } 383 384 /* 385 * The `continuousBackup` flag is specified only during the first full backup to initiate 386 * continuous WAL replication. After that, it is redundant because the tables are already set 387 * up for continuous backup. If the `continuousBackup` flag is not explicitly enabled, we need 388 * to determine the backup mode based on the current state of the specified tables: - If all 389 * the specified tables are already part of continuous backup, we treat the request as a 390 * continuous backup request and proceed accordingly (since these tables are already 391 * continuously backed up, no additional setup is needed). - If none of the specified tables 392 * are part of continuous backup, we treat the request as a normal full backup without 393 * continuous backup. - If the request includes a mix of tables—some with continuous backup 394 * enabled and others without—we cannot determine a clear backup strategy. In this case, we 395 * throw an error. If all tables are already in continuous backup mode, we explicitly set the 396 * `continuousBackup` flag to `true` so that the request is processed using the continuous 397 * backup approach rather than the normal full backup flow. 398 */ 399 if (!continuousBackup && tableNameList != null && !tableNameList.isEmpty()) { 400 try (BackupSystemTable backupSystemTable = new BackupSystemTable(conn)) { 401 Set<TableName> continuousBackupTableSet = 402 backupSystemTable.getContinuousBackupTableSet().keySet(); 403 404 boolean allTablesInContinuousBackup = continuousBackupTableSet.containsAll(tableNameList); 405 boolean noTablesInContinuousBackup = 406 tableNameList.stream().noneMatch(continuousBackupTableSet::contains); 407 408 // Ensure that all tables are either fully in continuous backup or not at all 409 if (!allTablesInContinuousBackup && !noTablesInContinuousBackup) { 410 System.err 411 .println("ERROR: Some tables are already in continuous backup, while others are not. " 412 + "Cannot mix both in a single request."); 413 printUsage(); 414 throw new IOException(INCORRECT_USAGE); 415 } 416 417 // If all tables are already in continuous backup, enable the flag 418 if (allTablesInContinuousBackup) { 419 continuousBackup = true; 420 } 421 } 422 } 423 424 try (BackupAdminImpl admin = new BackupAdminImpl(conn)) { 425 BackupRequest.Builder builder = new BackupRequest.Builder(); 426 BackupRequest request = builder.withBackupType(backupType).withTableList(tableNameList) 427 .withTargetRootDir(targetBackupDir).withTotalTasks(workers) 428 .withBandwidthPerTasks(bandwidth).withNoChecksumVerify(ignoreChecksum) 429 .withBackupSetName(setName).withContinuousBackupEnabled(continuousBackup).build(); 430 String backupId = admin.backupTables(request); 431 System.out.println("Backup session " + backupId + " finished. Status: SUCCESS"); 432 } catch (IOException e) { 433 System.out.println("Backup session finished. Status: FAILURE"); 434 throw e; 435 } 436 } 437 438 private boolean isRootFolder(String targetBackupDir) { 439 Path p = new Path(targetBackupDir); 440 return p.isRoot(); 441 } 442 443 private boolean verifyPath(String path) { 444 try { 445 Path p = new Path(path); 446 Configuration conf = getConf() != null ? getConf() : HBaseConfiguration.create(); 447 URI uri = p.toUri(); 448 449 if (uri.getScheme() == null) { 450 return false; 451 } 452 453 FileSystem.get(uri, conf); 454 return true; 455 } catch (Exception e) { 456 return false; 457 } 458 } 459 460 private String getTablesForSet(String name) throws IOException { 461 try (final BackupSystemTable table = new BackupSystemTable(conn)) { 462 List<TableName> tables = table.describeBackupSet(name); 463 464 if (tables == null) { 465 return null; 466 } 467 468 return StringUtils.join(tables, BackupRestoreConstants.TABLENAME_DELIMITER_IN_COMMAND); 469 } 470 } 471 472 @Override 473 protected void printUsage() { 474 System.out.println(CREATE_CMD_USAGE); 475 Options options = new Options(); 476 options.addOption(OPTION_WORKERS, true, OPTION_WORKERS_DESC); 477 options.addOption(OPTION_BANDWIDTH, true, OPTION_BANDWIDTH_DESC); 478 options.addOption(OPTION_SET, true, OPTION_SET_BACKUP_DESC); 479 options.addOption(OPTION_TABLE, true, OPTION_TABLE_LIST_DESC); 480 options.addOption(OPTION_YARN_QUEUE_NAME, true, OPTION_YARN_QUEUE_NAME_DESC); 481 options.addOption(OPTION_DEBUG, false, OPTION_DEBUG_DESC); 482 options.addOption(OPTION_IGNORECHECKSUM, false, OPTION_IGNORECHECKSUM_DESC); 483 options.addOption(OPTION_ENABLE_CONTINUOUS_BACKUP, false, 484 OPTION_ENABLE_CONTINUOUS_BACKUP_DESC); 485 486 HelpFormatter helpFormatter = new HelpFormatter(); 487 helpFormatter.setLeftPadding(2); 488 helpFormatter.setDescPadding(8); 489 helpFormatter.setWidth(100); 490 helpFormatter.setSyntaxPrefix("Options:"); 491 helpFormatter.printHelp(" ", null, options, USAGE_FOOTER); 492 } 493 } 494 495 public static class HelpCommand extends Command { 496 HelpCommand(Configuration conf, CommandLine cmdline) { 497 super(conf); 498 this.cmdline = cmdline; 499 } 500 501 @Override 502 public void execute() throws IOException { 503 if (cmdline == null) { 504 printUsage(); 505 throw new IOException(INCORRECT_USAGE); 506 } 507 508 String[] args = cmdline.getArgs(); 509 if (args == null || args.length == 0) { 510 printUsage(); 511 throw new IOException(INCORRECT_USAGE); 512 } 513 514 if (args.length != 2) { 515 System.out.println("ERROR: Only supports help message of a single command type"); 516 printUsage(); 517 throw new IOException(INCORRECT_USAGE); 518 } 519 520 String type = args[1]; 521 522 if (BackupCommand.CREATE.name().equalsIgnoreCase(type)) { 523 System.out.println(CREATE_CMD_USAGE); 524 } else if (BackupCommand.DESCRIBE.name().equalsIgnoreCase(type)) { 525 System.out.println(DESCRIBE_CMD_USAGE); 526 } else if (BackupCommand.HISTORY.name().equalsIgnoreCase(type)) { 527 System.out.println(HISTORY_CMD_USAGE); 528 } else if (BackupCommand.PROGRESS.name().equalsIgnoreCase(type)) { 529 System.out.println(PROGRESS_CMD_USAGE); 530 } else if (BackupCommand.DELETE.name().equalsIgnoreCase(type)) { 531 System.out.println(DELETE_CMD_USAGE); 532 } else if (BackupCommand.SET.name().equalsIgnoreCase(type)) { 533 System.out.println(SET_CMD_USAGE); 534 } else { 535 System.out.println("Unknown command : " + type); 536 printUsage(); 537 } 538 } 539 540 @Override 541 protected void printUsage() { 542 System.out.println(USAGE); 543 } 544 } 545 546 public static class DescribeCommand extends Command { 547 DescribeCommand(Configuration conf, CommandLine cmdline) { 548 super(conf); 549 this.cmdline = cmdline; 550 } 551 552 @Override 553 public void execute() throws IOException { 554 if (cmdline == null || cmdline.getArgs() == null) { 555 printUsage(); 556 throw new IOException(INCORRECT_USAGE); 557 } 558 String[] args = cmdline.getArgs(); 559 if (args.length != 2) { 560 printUsage(); 561 throw new IOException(INCORRECT_USAGE); 562 } 563 564 super.execute(); 565 566 String backupId = args[1]; 567 try (final BackupSystemTable sysTable = new BackupSystemTable(conn)) { 568 BackupInfo info = sysTable.readBackupInfo(backupId); 569 if (info == null) { 570 System.out.println("ERROR: " + backupId + " does not exist"); 571 printUsage(); 572 throw new IOException(INCORRECT_USAGE); 573 } 574 System.out.println(info.getShortDescription()); 575 } 576 } 577 578 @Override 579 protected void printUsage() { 580 System.out.println(DESCRIBE_CMD_USAGE); 581 } 582 } 583 584 public static class ProgressCommand extends Command { 585 ProgressCommand(Configuration conf, CommandLine cmdline) { 586 super(conf); 587 this.cmdline = cmdline; 588 } 589 590 @Override 591 public void execute() throws IOException { 592 593 if (cmdline == null || cmdline.getArgs() == null || cmdline.getArgs().length == 1) { 594 System.out.println( 595 "No backup id was specified, " + "will retrieve the most recent (ongoing) session"); 596 } 597 String[] args = cmdline == null ? null : cmdline.getArgs(); 598 if (args != null && args.length > 2) { 599 System.err.println("ERROR: wrong number of arguments: " + args.length); 600 printUsage(); 601 throw new IOException(INCORRECT_USAGE); 602 } 603 604 super.execute(); 605 606 String backupId = (args == null || args.length <= 1) ? null : args[1]; 607 try (final BackupSystemTable sysTable = new BackupSystemTable(conn)) { 608 BackupInfo info = null; 609 610 if (backupId != null) { 611 info = sysTable.readBackupInfo(backupId); 612 } else { 613 List<BackupInfo> infos = 614 sysTable.getBackupHistory(NEW_TO_OLD, 1, withState(BackupState.RUNNING)); 615 if (infos != null && infos.size() > 0) { 616 info = infos.get(0); 617 backupId = info.getBackupId(); 618 System.out.println("Found ongoing session with backupId=" + backupId); 619 } 620 } 621 int progress = info == null ? -1 : info.getProgress(); 622 if (progress < 0) { 623 if (backupId != null) { 624 System.out.println(NO_INFO_FOUND + backupId); 625 } else { 626 System.err.println(NO_ACTIVE_SESSION_FOUND); 627 } 628 } else { 629 System.out.println(backupId + " progress=" + progress + "%"); 630 } 631 } 632 } 633 634 @Override 635 protected void printUsage() { 636 System.out.println(PROGRESS_CMD_USAGE); 637 } 638 } 639 640 public static class DeleteCommand extends Command { 641 DeleteCommand(Configuration conf, CommandLine cmdline) { 642 super(conf); 643 this.cmdline = cmdline; 644 } 645 646 @Override 647 protected boolean requiresNoActiveSession() { 648 return true; 649 } 650 651 @Override 652 public void execute() throws IOException { 653 654 if (cmdline == null || cmdline.getArgs() == null || cmdline.getArgs().length < 1) { 655 printUsage(); 656 throw new IOException(INCORRECT_USAGE); 657 } 658 659 if (!cmdline.hasOption(OPTION_KEEP) && !cmdline.hasOption(OPTION_LIST)) { 660 printUsage(); 661 throw new IOException(INCORRECT_USAGE); 662 } 663 664 boolean isForceDelete = cmdline.hasOption(OPTION_FORCE_DELETE); 665 super.execute(); 666 if (cmdline.hasOption(OPTION_KEEP)) { 667 executeDeleteOlderThan(cmdline, isForceDelete); 668 } else if (cmdline.hasOption(OPTION_LIST)) { 669 executeDeleteListOfBackups(cmdline, isForceDelete); 670 } 671 672 cleanUpUnusedBackupWALs(); 673 } 674 675 private void executeDeleteOlderThan(CommandLine cmdline, boolean isForceDelete) 676 throws IOException { 677 String value = cmdline.getOptionValue(OPTION_KEEP); 678 int days = 0; 679 try { 680 days = Integer.parseInt(value); 681 } catch (NumberFormatException e) { 682 throw new IOException(value + " is not an integer number"); 683 } 684 final long fdays = days; 685 BackupInfo.Filter dateFilter = info -> { 686 long currentTime = EnvironmentEdgeManager.currentTime(); 687 long maxTsToDelete = currentTime - fdays * 24 * 3600 * 1000; 688 return info.getCompleteTs() <= maxTsToDelete; 689 }; 690 List<BackupInfo> history = null; 691 try (final BackupSystemTable sysTable = new BackupSystemTable(conn); 692 BackupAdminImpl admin = new BackupAdminImpl(conn)) { 693 history = sysTable.getBackupHistory(dateFilter); 694 String[] backupIds = convertToBackupIds(history); 695 validatePITRBackupDeletion(backupIds, isForceDelete); 696 int deleted = admin.deleteBackups(backupIds); 697 System.out.println("Deleted " + deleted + " backups. Total older than " + days + " days: " 698 + backupIds.length); 699 } catch (IOException e) { 700 System.err.println("Delete command FAILED. Please run backup repair tool to restore backup " 701 + "system integrity"); 702 throw e; 703 } 704 } 705 706 private String[] convertToBackupIds(List<BackupInfo> history) { 707 String[] ids = new String[history.size()]; 708 for (int i = 0; i < ids.length; i++) { 709 ids[i] = history.get(i).getBackupId(); 710 } 711 return ids; 712 } 713 714 private void executeDeleteListOfBackups(CommandLine cmdline, boolean isForceDelete) 715 throws IOException { 716 String value = cmdline.getOptionValue(OPTION_LIST); 717 String[] backupIds = value.split(","); 718 validatePITRBackupDeletion(backupIds, isForceDelete); 719 try (BackupAdminImpl admin = new BackupAdminImpl(conn)) { 720 int deleted = admin.deleteBackups(backupIds); 721 System.out.println("Deleted " + deleted + " backups. Total requested: " + backupIds.length); 722 } catch (IOException e) { 723 System.err.println("Delete command FAILED. Please run backup repair tool to restore backup " 724 + "system integrity"); 725 throw e; 726 } 727 728 } 729 730 /** 731 * Validates whether the specified backups can be deleted while preserving Point-In-Time 732 * Recovery (PITR) capabilities. If a backup is the only remaining full backup enabling PITR for 733 * certain tables, deletion is prevented unless forced. 734 * @param backupIds Array of backup IDs to validate. 735 * @param isForceDelete Flag indicating whether deletion should proceed regardless of PITR 736 * constraints. 737 * @throws IOException If a backup is essential for PITR and force deletion is not enabled. 738 */ 739 private void validatePITRBackupDeletion(String[] backupIds, boolean isForceDelete) 740 throws IOException { 741 if (!isForceDelete) { 742 for (String backupId : backupIds) { 743 List<TableName> affectedTables = getTablesDependentOnBackupForPITR(backupId); 744 if (!affectedTables.isEmpty()) { 745 String errMsg = String.format( 746 "Backup %s is the only FULL backup remaining that enables PITR for tables: %s. " 747 + "Use the force option to delete it anyway.", 748 backupId, affectedTables); 749 System.err.println(errMsg); 750 throw new IOException(errMsg); 751 } 752 } 753 } 754 } 755 756 /** 757 * Identifies tables that rely on the specified backup for PITR (Point-In-Time Recovery). A 758 * table is considered dependent on the backup if it does not have any other valid full backups 759 * that can cover the PITR window enabled by the specified backup. 760 * @param backupId The ID of the backup being evaluated for PITR coverage. 761 * @return A list of tables that are dependent on the specified backup for PITR recovery. 762 * @throws IOException If there is an error retrieving the backup metadata or backup system 763 * table. 764 */ 765 private List<TableName> getTablesDependentOnBackupForPITR(String backupId) throws IOException { 766 List<TableName> dependentTables = new ArrayList<>(); 767 768 try (final BackupSystemTable backupSystemTable = new BackupSystemTable(conn)) { 769 // Fetch the target backup's info using the backup ID 770 BackupInfo targetBackup = backupSystemTable.readBackupInfo(backupId); 771 if (targetBackup == null) { 772 throw new IOException("Backup info not found for backupId: " + backupId); 773 } 774 775 // Only full backups are mandatory for PITR 776 if (!BackupType.FULL.equals(targetBackup.getType())) { 777 return List.of(); 778 } 779 780 // Retrieve the tables with continuous backup enabled along with their start times 781 Map<TableName, Long> continuousBackupStartTimes = 782 backupSystemTable.getContinuousBackupTableSet(); 783 784 // Calculate the PITR window by fetching configuration and current time 785 long pitrWindowDays = getConf().getLong(CONF_CONTINUOUS_BACKUP_PITR_WINDOW_DAYS, 786 DEFAULT_CONTINUOUS_BACKUP_PITR_WINDOW_DAYS); 787 long currentTime = EnvironmentEdgeManager.getDelegate().currentTime(); 788 final long maxAllowedPITRTime = currentTime - TimeUnit.DAYS.toMillis(pitrWindowDays); 789 790 // Check each table associated with the target backup 791 for (TableName table : targetBackup.getTableNames()) { 792 // Skip tables without continuous backup enabled 793 if (!continuousBackupStartTimes.containsKey(table)) { 794 continue; 795 } 796 797 // Calculate the PITR window this backup covers for the table 798 Optional<Pair<Long, Long>> coveredPitrWindow = getCoveredPitrWindowForTable(targetBackup, 799 continuousBackupStartTimes.get(table), maxAllowedPITRTime, currentTime); 800 801 // If this backup does not cover a valid PITR window for the table, skip 802 if (coveredPitrWindow.isEmpty()) { 803 continue; 804 } 805 806 // Check if there is any other valid backup that can cover the PITR window 807 List<BackupInfo> allBackups = 808 backupSystemTable.getBackupHistory(withState(BackupInfo.BackupState.COMPLETE)); 809 boolean hasAnotherValidBackup = 810 canAnyOtherBackupCover(allBackups, targetBackup, table, coveredPitrWindow.get(), 811 continuousBackupStartTimes.get(table), maxAllowedPITRTime, currentTime); 812 813 // If no other valid backup exists, add the table to the dependent list 814 if (!hasAnotherValidBackup) { 815 dependentTables.add(table); 816 } 817 } 818 } 819 820 return dependentTables; 821 } 822 823 /** 824 * Calculates the PITR (Point-In-Time Recovery) window that the given backup enables for a 825 * table. 826 * @param backupInfo Metadata of the backup being evaluated. 827 * @param continuousBackupStartTime When continuous backups started for the table. 828 * @param maxAllowedPITRTime The earliest timestamp from which PITR is supported in the 829 * cluster. 830 * @param currentTime Current time. 831 * @return Optional PITR window as a pair (start, end), or empty if backup is not useful for 832 * PITR. 833 */ 834 private Optional<Pair<Long, Long>> getCoveredPitrWindowForTable(BackupInfo backupInfo, 835 long continuousBackupStartTime, long maxAllowedPITRTime, long currentTime) { 836 837 long backupStartTs = backupInfo.getStartTs(); 838 long backupEndTs = backupInfo.getCompleteTs(); 839 long effectiveStart = Math.max(continuousBackupStartTime, maxAllowedPITRTime); 840 841 if (backupStartTs < continuousBackupStartTime) { 842 return Optional.empty(); 843 } 844 845 return Optional.of(Pair.newPair(Math.max(backupEndTs, effectiveStart), currentTime)); 846 } 847 848 /** 849 * Checks if any backup (excluding the current backup) can cover the specified PITR window for 850 * the given table. A backup can cover the PITR window if it fully encompasses the target time 851 * range specified. 852 * @param allBackups List of all backups available. 853 * @param currentBackup The current backup that should not be considered for 854 * coverage. 855 * @param table The table for which we need to check backup coverage. 856 * @param targetWindow A pair representing the target PITR window (start and end 857 * times). 858 * @param continuousBackupStartTime When continuous backups started for the table. 859 * @param maxAllowedPITRTime The earliest timestamp from which PITR is supported in the 860 * cluster. 861 * @param currentTime Current time. 862 * @return {@code true} if any backup (excluding the current one) fully covers the target PITR 863 * window; {@code false} otherwise. 864 */ 865 private boolean canAnyOtherBackupCover(List<BackupInfo> allBackups, BackupInfo currentBackup, 866 TableName table, Pair<Long, Long> targetWindow, long continuousBackupStartTime, 867 long maxAllowedPITRTime, long currentTime) { 868 869 long targetStart = targetWindow.getFirst(); 870 long targetEnd = targetWindow.getSecond(); 871 872 // Iterate through all backups (including the current one) 873 for (BackupInfo backup : allBackups) { 874 // Skip if the backup is not full or doesn't contain the table 875 if (!BackupType.FULL.equals(backup.getType())) continue; 876 if (!backup.getTableNames().contains(table)) continue; 877 878 // Skip the current backup itself 879 if (backup.equals(currentBackup)) continue; 880 881 // Get the covered PITR window for this backup 882 Optional<Pair<Long, Long>> coveredWindow = getCoveredPitrWindowForTable(backup, 883 continuousBackupStartTime, maxAllowedPITRTime, currentTime); 884 885 if (coveredWindow.isPresent()) { 886 Pair<Long, Long> covered = coveredWindow.get(); 887 888 // The backup must fully cover the target window 889 if (covered.getFirst() <= targetStart && covered.getSecond() >= targetEnd) { 890 return true; 891 } 892 } 893 } 894 895 return false; 896 } 897 898 /** 899 * Cleans up Write-Ahead Logs (WALs) that are no longer required for PITR after a successful 900 * backup deletion. If no full backups are present, all WALs are deleted, tables are removed 901 * from continuous backup metadata, and the associated replication peer is disabled. 902 */ 903 private void cleanUpUnusedBackupWALs() throws IOException { 904 Configuration conf = getConf() != null ? getConf() : HBaseConfiguration.create(); 905 String backupWalDir = conf.get(CONF_CONTINUOUS_BACKUP_WAL_DIR); 906 907 if (Strings.isNullOrEmpty(backupWalDir)) { 908 System.out.println("No WAL directory specified for continuous backup. Skipping cleanup."); 909 return; 910 } 911 912 try (Admin admin = conn.getAdmin(); 913 BackupSystemTable sysTable = new BackupSystemTable(conn)) { 914 // Get list of tables under continuous backup 915 Map<TableName, Long> continuousBackupTables = sysTable.getContinuousBackupTableSet(); 916 if (continuousBackupTables.isEmpty()) { 917 System.out.println("No continuous backups configured. Skipping WAL cleanup."); 918 return; 919 } 920 921 // Find the earliest timestamp after which WALs are still needed 922 long cutoffTimestamp = determineWALCleanupCutoffTime(sysTable); 923 if (cutoffTimestamp == 0) { 924 // No full backup exists. PITR cannot function without a base full backup. 925 // Clean up all WALs, remove tables from backup metadata, and disable the replication 926 // peer. 927 System.out 928 .println("No full backups found. Cleaning up all WALs and disabling replication peer."); 929 930 disableContinuousBackupReplicationPeer(admin); 931 removeAllTablesFromContinuousBackup(sysTable); 932 deleteAllBackupWALFiles(conf, backupWalDir); 933 return; 934 } 935 936 // Update metadata before actual cleanup to avoid inconsistencies 937 updateBackupTableStartTimes(sysTable, cutoffTimestamp); 938 939 // Delete WAL files older than cutoff timestamp 940 deleteOldWALFiles(conf, backupWalDir, cutoffTimestamp); 941 942 } 943 } 944 945 /** 946 * Determines the cutoff time for cleaning WAL files. 947 * @param sysTable Backup system table 948 * @return cutoff timestamp or 0 if not found 949 */ 950 long determineWALCleanupCutoffTime(BackupSystemTable sysTable) throws IOException { 951 List<BackupInfo> backupInfos = 952 sysTable.getBackupHistory(withState(BackupInfo.BackupState.COMPLETE)); 953 Collections.reverse(backupInfos); // Start from oldest 954 955 for (BackupInfo backupInfo : backupInfos) { 956 if (BackupType.FULL.equals(backupInfo.getType())) { 957 return backupInfo.getStartTs(); 958 } 959 } 960 return 0; 961 } 962 963 private void disableContinuousBackupReplicationPeer(Admin admin) throws IOException { 964 for (ReplicationPeerDescription peer : admin.listReplicationPeers()) { 965 if (peer.getPeerId().equals(CONTINUOUS_BACKUP_REPLICATION_PEER) && peer.isEnabled()) { 966 admin.disableReplicationPeer(CONTINUOUS_BACKUP_REPLICATION_PEER); 967 System.out.println("Disabled replication peer: " + CONTINUOUS_BACKUP_REPLICATION_PEER); 968 break; 969 } 970 } 971 } 972 973 /** 974 * Updates the start time for continuous backups if older than cutoff timestamp. 975 * @param sysTable Backup system table 976 * @param cutoffTimestamp Timestamp before which WALs are no longer needed 977 */ 978 void updateBackupTableStartTimes(BackupSystemTable sysTable, long cutoffTimestamp) 979 throws IOException { 980 981 Map<TableName, Long> backupTables = sysTable.getContinuousBackupTableSet(); 982 Set<TableName> tablesToUpdate = new HashSet<>(); 983 984 for (Map.Entry<TableName, Long> entry : backupTables.entrySet()) { 985 if (entry.getValue() < cutoffTimestamp) { 986 tablesToUpdate.add(entry.getKey()); 987 } 988 } 989 990 if (!tablesToUpdate.isEmpty()) { 991 sysTable.updateContinuousBackupTableSet(tablesToUpdate, cutoffTimestamp); 992 } 993 } 994 995 private void removeAllTablesFromContinuousBackup(BackupSystemTable sysTable) 996 throws IOException { 997 Map<TableName, Long> allTables = sysTable.getContinuousBackupTableSet(); 998 if (!allTables.isEmpty()) { 999 sysTable.removeContinuousBackupTableSet(allTables.keySet()); 1000 System.out.println("Removed all tables from continuous backup metadata."); 1001 } 1002 } 1003 1004 private void deleteAllBackupWALFiles(Configuration conf, String backupWalDir) 1005 throws IOException { 1006 try { 1007 BackupFileSystemManager manager = 1008 new BackupFileSystemManager(CONTINUOUS_BACKUP_REPLICATION_PEER, conf, backupWalDir); 1009 FileSystem fs = manager.getBackupFs(); 1010 Path walDir = manager.getWalsDir(); 1011 Path bulkloadDir = manager.getBulkLoadFilesDir(); 1012 1013 // Delete contents under WAL directory 1014 if (fs.exists(walDir)) { 1015 FileStatus[] walContents = fs.listStatus(walDir); 1016 for (FileStatus item : walContents) { 1017 fs.delete(item.getPath(), true); // recursive delete of each child 1018 } 1019 System.out.println("Deleted all contents under WAL directory: " + walDir); 1020 } 1021 1022 // Delete contents under bulk load directory 1023 if (fs.exists(bulkloadDir)) { 1024 FileStatus[] bulkContents = fs.listStatus(bulkloadDir); 1025 for (FileStatus item : bulkContents) { 1026 fs.delete(item.getPath(), true); // recursive delete of each child 1027 } 1028 System.out.println("Deleted all contents under Bulk Load directory: " + bulkloadDir); 1029 } 1030 1031 } catch (IOException e) { 1032 System.out.println("WARNING: Failed to delete contents under backup directories: " 1033 + backupWalDir + ". Error: " + e.getMessage()); 1034 throw e; 1035 } 1036 } 1037 1038 /** 1039 * Cleans up old WAL and bulk-loaded files based on the determined cutoff timestamp. 1040 */ 1041 void deleteOldWALFiles(Configuration conf, String backupWalDir, long cutoffTime) 1042 throws IOException { 1043 System.out.println("Starting WAL cleanup in backup directory: " + backupWalDir 1044 + " with cutoff time: " + cutoffTime); 1045 1046 BackupFileSystemManager manager = 1047 new BackupFileSystemManager(CONTINUOUS_BACKUP_REPLICATION_PEER, conf, backupWalDir); 1048 FileSystem fs = manager.getBackupFs(); 1049 Path walDir = manager.getWalsDir(); 1050 Path bulkloadDir = manager.getBulkLoadFilesDir(); 1051 1052 SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); 1053 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); 1054 1055 System.out.println("Listing directories under: " + walDir); 1056 1057 FileStatus[] directories = fs.listStatus(walDir); 1058 1059 for (FileStatus dirStatus : directories) { 1060 if (!dirStatus.isDirectory()) { 1061 continue; // Skip files, we only want directories 1062 } 1063 1064 Path dirPath = dirStatus.getPath(); 1065 String dirName = dirPath.getName(); 1066 1067 try { 1068 long dayStart = parseDayDirectory(dirName, dateFormat); 1069 System.out 1070 .println("Checking WAL directory: " + dirName + " (Start Time: " + dayStart + ")"); 1071 1072 // If WAL files of that day are older than cutoff time, delete them 1073 if (dayStart + ONE_DAY_IN_MILLISECONDS - 1 < cutoffTime) { 1074 System.out.println("Deleting outdated WAL directory: " + dirPath); 1075 fs.delete(dirPath, true); 1076 Path bulkloadPath = new Path(bulkloadDir, dirName); 1077 System.out.println("Deleting corresponding bulk-load directory: " + bulkloadPath); 1078 fs.delete(bulkloadPath, true); 1079 } 1080 } catch (ParseException e) { 1081 System.out.println("WARNING: Failed to parse directory name '" + dirName 1082 + "'. Skipping. Error: " + e.getMessage()); 1083 } catch (IOException e) { 1084 System.err.println("WARNING: Failed to delete directory '" + dirPath 1085 + "'. Skipping. Error: " + e.getMessage()); 1086 } 1087 } 1088 1089 System.out.println("Completed WAL cleanup for backup directory: " + backupWalDir); 1090 } 1091 1092 private long parseDayDirectory(String dayDir, SimpleDateFormat dateFormat) 1093 throws ParseException { 1094 return dateFormat.parse(dayDir).getTime(); 1095 } 1096 1097 @Override 1098 protected void printUsage() { 1099 System.out.println(DELETE_CMD_USAGE); 1100 Options options = new Options(); 1101 options.addOption(OPTION_KEEP, true, OPTION_KEEP_DESC); 1102 options.addOption(OPTION_LIST, true, OPTION_BACKUP_LIST_DESC); 1103 options.addOption(OPTION_FORCE_DELETE, false, OPTION_FORCE_DELETE_DESC); 1104 1105 HelpFormatter helpFormatter = new HelpFormatter(); 1106 helpFormatter.setLeftPadding(2); 1107 helpFormatter.setDescPadding(8); 1108 helpFormatter.setWidth(100); 1109 helpFormatter.setSyntaxPrefix("Options:"); 1110 helpFormatter.printHelp(" ", null, options, USAGE_FOOTER); 1111 1112 } 1113 } 1114 1115 public static class RepairCommand extends Command { 1116 RepairCommand(Configuration conf, CommandLine cmdline) { 1117 super(conf); 1118 this.cmdline = cmdline; 1119 } 1120 1121 @Override 1122 public void execute() throws IOException { 1123 super.execute(); 1124 1125 String[] args = cmdline == null ? null : cmdline.getArgs(); 1126 if (args != null && args.length > 1) { 1127 System.err.println("ERROR: wrong number of arguments: " + args.length); 1128 printUsage(); 1129 throw new IOException(INCORRECT_USAGE); 1130 } 1131 1132 Configuration conf = getConf() != null ? getConf() : HBaseConfiguration.create(); 1133 try (final Connection conn = ConnectionFactory.createConnection(conf); 1134 final BackupSystemTable sysTable = new BackupSystemTable(conn)) { 1135 // Failed backup 1136 BackupInfo backupInfo; 1137 List<BackupInfo> list = 1138 sysTable.getBackupHistory(NEW_TO_OLD, 1, withState(BackupState.RUNNING)); 1139 if (list.size() == 0) { 1140 // No failed sessions found 1141 System.out.println("REPAIR status: no failed sessions found." 1142 + " Checking failed delete backup operation ..."); 1143 repairFailedBackupDeletionIfAny(conn, sysTable); 1144 repairFailedBackupMergeIfAny(conn, sysTable); 1145 return; 1146 } 1147 backupInfo = list.get(0); 1148 // If this is a cancel exception, then we've already cleaned. 1149 // set the failure timestamp of the overall backup 1150 backupInfo.setCompleteTs(EnvironmentEdgeManager.currentTime()); 1151 // set failure message 1152 backupInfo.setFailedMsg("REPAIR status: repaired after failure:\n" + backupInfo); 1153 // set overall backup status: failed 1154 backupInfo.setState(BackupState.FAILED); 1155 // compose the backup failed data 1156 String backupFailedData = "BackupId=" + backupInfo.getBackupId() + ",startts=" 1157 + backupInfo.getStartTs() + ",failedts=" + backupInfo.getCompleteTs() + ",failedphase=" 1158 + backupInfo.getPhase() + ",failedmessage=" + backupInfo.getFailedMsg(); 1159 System.out.println(backupFailedData); 1160 TableBackupClient.cleanupAndRestoreBackupSystem(conn, backupInfo, conf); 1161 // If backup session is updated to FAILED state - means we 1162 // processed recovery already. 1163 sysTable.updateBackupInfo(backupInfo); 1164 sysTable.finishBackupExclusiveOperation(); 1165 System.out.println("REPAIR status: finished repair failed session:\n " + backupInfo); 1166 } 1167 } 1168 1169 private void repairFailedBackupDeletionIfAny(Connection conn, BackupSystemTable sysTable) 1170 throws IOException { 1171 String[] backupIds = sysTable.getListOfBackupIdsFromDeleteOperation(); 1172 if (backupIds == null || backupIds.length == 0) { 1173 System.out.println("No failed backup DELETE operation found"); 1174 // Delete backup table snapshot if exists 1175 BackupSystemTable.deleteSnapshot(conn); 1176 return; 1177 } 1178 System.out.println("Found failed DELETE operation for: " + StringUtils.join(backupIds)); 1179 System.out.println("Running DELETE again ..."); 1180 // Restore table from snapshot 1181 BackupSystemTable.restoreFromSnapshot(conn); 1182 // Finish previous failed session 1183 sysTable.finishBackupExclusiveOperation(); 1184 try (BackupAdmin admin = new BackupAdminImpl(conn)) { 1185 admin.deleteBackups(backupIds); 1186 } 1187 System.out.println("DELETE operation finished OK: " + StringUtils.join(backupIds)); 1188 } 1189 1190 public static void repairFailedBackupMergeIfAny(Connection conn, BackupSystemTable sysTable) 1191 throws IOException { 1192 1193 String[] backupIds = sysTable.getListOfBackupIdsFromMergeOperation(); 1194 if (backupIds == null || backupIds.length == 0) { 1195 System.out.println("No failed backup MERGE operation found"); 1196 // Delete backup table snapshot if exists 1197 BackupSystemTable.deleteSnapshot(conn); 1198 return; 1199 } 1200 System.out.println("Found failed MERGE operation for: " + StringUtils.join(backupIds)); 1201 1202 BackupInfo bInfo = sysTable.readBackupInfo(backupIds[0]); 1203 if (bInfo == null) { 1204 throw new IOException( 1205 "MERGE repair: failed due to null backup info for backup ID: " + backupIds[0]); 1206 } 1207 1208 // Check if backup .tmp exists 1209 String backupRoot = bInfo.getBackupRootDir(); 1210 FileSystem fs = FileSystem.get(new Path(backupRoot).toUri(), new Configuration()); 1211 String mergedBackupId = BackupUtils.findMostRecentBackupId(backupIds); 1212 Path tmpPath = HBackupFileSystem.getBackupTmpDirPathForBackupId(backupRoot, mergedBackupId); 1213 Path destPath = HBackupFileSystem.getBackupPath(backupRoot, mergedBackupId); 1214 if (fs.exists(tmpPath)) { 1215 // Move data back 1216 if (!fs.delete(destPath, true)) { 1217 System.out.println("Failed to delete " + destPath); 1218 } 1219 boolean res = fs.rename(tmpPath, destPath); 1220 if (!res) { 1221 throw new IOException( 1222 "MERGE repair: failed to rename from " + tmpPath + " to " + destPath); 1223 } 1224 System.out 1225 .println("MERGE repair: renamed from " + tmpPath + " to " + destPath + " res=" + res); 1226 } else { 1227 checkRemoveBackupImages(conn.getConfiguration(), fs, backupRoot, backupIds); 1228 } 1229 // Restore table from snapshot 1230 BackupSystemTable.restoreFromSnapshot(conn); 1231 1232 // The merged backup is now consistent. If the tmp directory was restored it already holds 1233 // the original marker; otherwise the failed merge may not have written one. Writing is 1234 // idempotent and best-effort. Write it before unlocking, so a concurrent delete or merge 1235 // cannot run before the marker is written and leave a stale marker behind. 1236 writeBackupCompleteMarker(conn.getConfiguration(), backupRoot, mergedBackupId); 1237 1238 // Unlock backup system 1239 sysTable.finishBackupExclusiveOperation(); 1240 // Finish previous failed session 1241 sysTable.finishMergeOperation(); 1242 1243 System.out.println("MERGE repair operation finished OK: " + StringUtils.join(backupIds)); 1244 } 1245 1246 private static void checkRemoveBackupImages(Configuration conf, FileSystem fs, 1247 String backupRoot, String[] backupIds) throws IOException { 1248 String mergedBackupId = BackupUtils.findMostRecentBackupId(backupIds); 1249 for (String backupId : backupIds) { 1250 if (backupId.equals(mergedBackupId)) { 1251 continue; 1252 } 1253 Path path = HBackupFileSystem.getBackupPath(backupRoot, backupId); 1254 if (fs.exists(path)) { 1255 // Delete the marker first so a failed directory delete never leaves a merged-away 1256 // backup looking complete 1257 HBackupFileSystem.deleteBackupCompleteMarker(conf, backupRoot, backupId); 1258 if (!fs.delete(path, true)) { 1259 System.out.println("MERGE repair removing: " + path + " - FAILED"); 1260 } else { 1261 System.out.println("MERGE repair removing: " + path + " - OK"); 1262 } 1263 } 1264 } 1265 } 1266 1267 @Override 1268 protected void printUsage() { 1269 System.out.println(REPAIR_CMD_USAGE); 1270 } 1271 } 1272 1273 public static class MergeCommand extends Command { 1274 MergeCommand(Configuration conf, CommandLine cmdline) { 1275 super(conf); 1276 this.cmdline = cmdline; 1277 } 1278 1279 @Override 1280 protected boolean requiresNoActiveSession() { 1281 return true; 1282 } 1283 1284 @Override 1285 protected boolean requiresConsistentState() { 1286 return true; 1287 } 1288 1289 @Override 1290 public void execute() throws IOException { 1291 super.execute(); 1292 1293 String[] args = cmdline == null ? null : cmdline.getArgs(); 1294 if (args == null || (args.length != 2)) { 1295 System.err 1296 .println("ERROR: wrong number of arguments: " + (args == null ? null : args.length)); 1297 printUsage(); 1298 throw new IOException(INCORRECT_USAGE); 1299 } 1300 1301 String[] backupIds = args[1].split(","); 1302 if (backupIds.length < 2) { 1303 String msg = "ERROR: can not merge a single backup image. " 1304 + "Number of images must be greater than 1."; 1305 System.err.println(msg); 1306 throw new IOException(msg); 1307 1308 } 1309 Configuration conf = getConf() != null ? getConf() : HBaseConfiguration.create(); 1310 try (final Connection conn = ConnectionFactory.createConnection(conf); 1311 final BackupAdminImpl admin = new BackupAdminImpl(conn)) { 1312 admin.mergeBackups(backupIds); 1313 } 1314 } 1315 1316 @Override 1317 protected void printUsage() { 1318 System.out.println(MERGE_CMD_USAGE); 1319 } 1320 } 1321 1322 public static class HistoryCommand extends Command { 1323 private final static int DEFAULT_HISTORY_LENGTH = 10; 1324 1325 HistoryCommand(Configuration conf, CommandLine cmdline) { 1326 super(conf); 1327 this.cmdline = cmdline; 1328 } 1329 1330 @Override 1331 public void execute() throws IOException { 1332 int n = parseHistoryLength(); 1333 final TableName tableName = getTableName(); 1334 final String setName = getTableSetName(); 1335 BackupInfo.Filter tableNameFilter = info -> { 1336 if (tableName == null) { 1337 return true; 1338 } 1339 1340 List<TableName> names = info.getTableNames(); 1341 return names.contains(tableName); 1342 }; 1343 BackupInfo.Filter tableSetFilter = info -> { 1344 if (setName == null) { 1345 return true; 1346 } 1347 1348 String backupId = info.getBackupId(); 1349 return backupId.startsWith(setName); 1350 }; 1351 Path backupRootPath = getBackupRootPath(); 1352 List<BackupInfo> history; 1353 if (backupRootPath == null) { 1354 // Load from backup system table 1355 super.execute(); 1356 try (final BackupSystemTable sysTable = new BackupSystemTable(conn)) { 1357 history = sysTable.getBackupHistory(tableNameFilter, tableSetFilter); 1358 history = history.subList(0, Math.min(n, history.size())); 1359 } 1360 } else { 1361 // load from backup FS 1362 history = 1363 BackupUtils.getHistory(getConf(), n, backupRootPath, tableNameFilter, tableSetFilter); 1364 } 1365 for (BackupInfo info : history) { 1366 System.out.println(info.getShortDescription()); 1367 } 1368 } 1369 1370 private Path getBackupRootPath() throws IOException { 1371 String value = null; 1372 try { 1373 value = cmdline.getOptionValue(OPTION_PATH); 1374 1375 if (value == null) { 1376 return null; 1377 } 1378 1379 return new Path(value); 1380 } catch (IllegalArgumentException e) { 1381 System.out.println("ERROR: Illegal argument for backup root path: " + value); 1382 printUsage(); 1383 throw new IOException(INCORRECT_USAGE); 1384 } 1385 } 1386 1387 private TableName getTableName() throws IOException { 1388 String value = cmdline.getOptionValue(OPTION_TABLE); 1389 1390 if (value == null) { 1391 return null; 1392 } 1393 1394 try { 1395 return TableName.valueOf(value); 1396 } catch (IllegalArgumentException e) { 1397 System.out.println("Illegal argument for table name: " + value); 1398 printUsage(); 1399 throw new IOException(INCORRECT_USAGE); 1400 } 1401 } 1402 1403 private String getTableSetName() { 1404 return cmdline.getOptionValue(OPTION_SET); 1405 } 1406 1407 private int parseHistoryLength() throws IOException { 1408 String value = cmdline.getOptionValue(OPTION_RECORD_NUMBER); 1409 try { 1410 if (value == null) { 1411 return DEFAULT_HISTORY_LENGTH; 1412 } 1413 1414 return Integer.parseInt(value); 1415 } catch (NumberFormatException e) { 1416 System.out.println("Illegal argument for history length: " + value); 1417 printUsage(); 1418 throw new IOException(INCORRECT_USAGE); 1419 } 1420 } 1421 1422 @Override 1423 protected void printUsage() { 1424 System.out.println(HISTORY_CMD_USAGE); 1425 Options options = new Options(); 1426 options.addOption(OPTION_RECORD_NUMBER, true, OPTION_RECORD_NUMBER_DESC); 1427 options.addOption(OPTION_PATH, true, OPTION_PATH_DESC); 1428 options.addOption(OPTION_TABLE, true, OPTION_TABLE_DESC); 1429 options.addOption(OPTION_SET, true, OPTION_SET_DESC); 1430 1431 HelpFormatter helpFormatter = new HelpFormatter(); 1432 helpFormatter.setLeftPadding(2); 1433 helpFormatter.setDescPadding(8); 1434 helpFormatter.setWidth(100); 1435 helpFormatter.setSyntaxPrefix("Options:"); 1436 helpFormatter.printHelp(" ", null, options, USAGE_FOOTER); 1437 } 1438 } 1439 1440 public static class BackupSetCommand extends Command { 1441 private final static String SET_ADD_CMD = "add"; 1442 private final static String SET_REMOVE_CMD = "remove"; 1443 private final static String SET_DELETE_CMD = "delete"; 1444 private final static String SET_DESCRIBE_CMD = "describe"; 1445 private final static String SET_LIST_CMD = "list"; 1446 1447 BackupSetCommand(Configuration conf, CommandLine cmdline) { 1448 super(conf); 1449 this.cmdline = cmdline; 1450 } 1451 1452 @Override 1453 public void execute() throws IOException { 1454 // Command-line must have at least one element 1455 if (cmdline == null || cmdline.getArgs() == null || cmdline.getArgs().length < 2) { 1456 printUsage(); 1457 throw new IOException(INCORRECT_USAGE); 1458 } 1459 1460 String[] args = cmdline.getArgs(); 1461 String cmdStr = args[1]; 1462 BackupCommand cmd = getCommand(cmdStr); 1463 1464 switch (cmd) { 1465 case SET_ADD: 1466 processSetAdd(args); 1467 break; 1468 case SET_REMOVE: 1469 processSetRemove(args); 1470 break; 1471 case SET_DELETE: 1472 processSetDelete(args); 1473 break; 1474 case SET_DESCRIBE: 1475 processSetDescribe(args); 1476 break; 1477 case SET_LIST: 1478 processSetList(); 1479 break; 1480 default: 1481 break; 1482 } 1483 } 1484 1485 private void processSetList() throws IOException { 1486 super.execute(); 1487 1488 // List all backup set names 1489 // does not expect any args 1490 try (BackupAdminImpl admin = new BackupAdminImpl(conn)) { 1491 List<BackupSet> list = admin.listBackupSets(); 1492 for (BackupSet bs : list) { 1493 System.out.println(bs); 1494 } 1495 } 1496 } 1497 1498 private void processSetDescribe(String[] args) throws IOException { 1499 if (args == null || args.length != 3) { 1500 printUsage(); 1501 throw new IOException(INCORRECT_USAGE); 1502 } 1503 super.execute(); 1504 1505 String setName = args[2]; 1506 try (final BackupSystemTable sysTable = new BackupSystemTable(conn)) { 1507 List<TableName> tables = sysTable.describeBackupSet(setName); 1508 BackupSet set = tables == null ? null : new BackupSet(setName, tables); 1509 if (set == null) { 1510 System.out.println("Set '" + setName + "' does not exist."); 1511 } else { 1512 System.out.println(set); 1513 } 1514 } 1515 } 1516 1517 private void processSetDelete(String[] args) throws IOException { 1518 if (args == null || args.length != 3) { 1519 printUsage(); 1520 throw new IOException(INCORRECT_USAGE); 1521 } 1522 super.execute(); 1523 1524 String setName = args[2]; 1525 try (final BackupAdminImpl admin = new BackupAdminImpl(conn)) { 1526 boolean result = admin.deleteBackupSet(setName); 1527 if (result) { 1528 System.out.println("Delete set " + setName + " OK."); 1529 } else { 1530 System.out.println("Set " + setName + " does not exist"); 1531 } 1532 } 1533 } 1534 1535 private void processSetRemove(String[] args) throws IOException { 1536 if (args == null || args.length != 4) { 1537 printUsage(); 1538 throw new IOException(INCORRECT_USAGE); 1539 } 1540 super.execute(); 1541 1542 String setName = args[2]; 1543 String[] tables = args[3].split(","); 1544 TableName[] tableNames = toTableNames(tables); 1545 try (final BackupAdminImpl admin = new BackupAdminImpl(conn)) { 1546 admin.removeFromBackupSet(setName, tableNames); 1547 } 1548 } 1549 1550 private TableName[] toTableNames(String[] tables) { 1551 TableName[] arr = new TableName[tables.length]; 1552 for (int i = 0; i < tables.length; i++) { 1553 arr[i] = TableName.valueOf(tables[i]); 1554 } 1555 return arr; 1556 } 1557 1558 private void processSetAdd(String[] args) throws IOException { 1559 if (args == null || args.length != 4) { 1560 printUsage(); 1561 throw new IOException(INCORRECT_USAGE); 1562 } 1563 super.execute(); 1564 String setName = args[2]; 1565 TableName[] tableNames = 1566 Splitter.on(',').splitToStream(args[3]).map(TableName::valueOf).toArray(TableName[]::new); 1567 try (final BackupAdminImpl admin = new BackupAdminImpl(conn)) { 1568 admin.addToBackupSet(setName, tableNames); 1569 } 1570 } 1571 1572 private BackupCommand getCommand(String cmdStr) throws IOException { 1573 switch (cmdStr) { 1574 case SET_ADD_CMD: 1575 return BackupCommand.SET_ADD; 1576 case SET_REMOVE_CMD: 1577 return BackupCommand.SET_REMOVE; 1578 case SET_DELETE_CMD: 1579 return BackupCommand.SET_DELETE; 1580 case SET_DESCRIBE_CMD: 1581 return BackupCommand.SET_DESCRIBE; 1582 case SET_LIST_CMD: 1583 return BackupCommand.SET_LIST; 1584 default: 1585 System.out.println("ERROR: Unknown command for 'set' :" + cmdStr); 1586 printUsage(); 1587 throw new IOException(INCORRECT_USAGE); 1588 } 1589 } 1590 1591 @Override 1592 protected void printUsage() { 1593 System.out.println(SET_CMD_USAGE); 1594 } 1595 } 1596}