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.withRoot; 021import static org.apache.hadoop.hbase.backup.BackupInfo.withState; 022import static org.apache.hadoop.hbase.backup.BackupInfo.withType; 023import static org.apache.hadoop.hbase.backup.impl.BackupSystemTable.Order.NEW_TO_OLD; 024 025import com.google.errorprone.annotations.RestrictedApi; 026import java.io.IOException; 027import java.util.ArrayList; 028import java.util.Arrays; 029import java.util.Collections; 030import java.util.HashSet; 031import java.util.List; 032import java.util.Map; 033import java.util.Set; 034import org.apache.commons.lang3.StringUtils; 035import org.apache.hadoop.conf.Configuration; 036import org.apache.hadoop.fs.FileSystem; 037import org.apache.hadoop.fs.Path; 038import org.apache.hadoop.hbase.TableName; 039import org.apache.hadoop.hbase.backup.BackupAdmin; 040import org.apache.hadoop.hbase.backup.BackupClientFactory; 041import org.apache.hadoop.hbase.backup.BackupInfo; 042import org.apache.hadoop.hbase.backup.BackupInfo.BackupState; 043import org.apache.hadoop.hbase.backup.BackupMergeJob; 044import org.apache.hadoop.hbase.backup.BackupRequest; 045import org.apache.hadoop.hbase.backup.BackupRestoreConstants; 046import org.apache.hadoop.hbase.backup.BackupRestoreFactory; 047import org.apache.hadoop.hbase.backup.BackupType; 048import org.apache.hadoop.hbase.backup.HBackupFileSystem; 049import org.apache.hadoop.hbase.backup.PointInTimeRestoreRequest; 050import org.apache.hadoop.hbase.backup.RestoreRequest; 051import org.apache.hadoop.hbase.backup.util.BackupSet; 052import org.apache.hadoop.hbase.backup.util.BackupUtils; 053import org.apache.hadoop.hbase.client.Admin; 054import org.apache.hadoop.hbase.client.Connection; 055import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 056import org.apache.yetus.audience.InterfaceAudience; 057import org.slf4j.Logger; 058import org.slf4j.LoggerFactory; 059 060import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 061 062@InterfaceAudience.Private 063public class BackupAdminImpl implements BackupAdmin { 064 public final static String CHECK_OK = "Checking backup images: OK"; 065 public final static String CHECK_FAILED = 066 "Checking backup images: Failed. Some dependencies are missing for restore"; 067 private static final Logger LOG = LoggerFactory.getLogger(BackupAdminImpl.class); 068 069 private final Connection conn; 070 071 public BackupAdminImpl(Connection conn) { 072 this.conn = conn; 073 } 074 075 @Override 076 public void close() { 077 } 078 079 @Override 080 public BackupInfo getBackupInfo(String backupId) throws IOException { 081 BackupInfo backupInfo; 082 try (final BackupSystemTable table = new BackupSystemTable(conn)) { 083 if (backupId == null) { 084 List<BackupInfo> recentSessions = 085 table.getBackupHistory(NEW_TO_OLD, 1, withState(BackupState.RUNNING)); 086 if (recentSessions.isEmpty()) { 087 LOG.warn("No ongoing sessions found."); 088 return null; 089 } 090 // else show status for ongoing session 091 // must be one maximum 092 return recentSessions.get(0); 093 } else { 094 backupInfo = table.readBackupInfo(backupId); 095 return backupInfo; 096 } 097 } 098 } 099 100 @Override 101 public int deleteBackups(String[] backupIds) throws IOException { 102 103 int totalDeleted = 0; 104 105 boolean deleteSessionStarted; 106 boolean snapshotDone; 107 try (final BackupSystemTable sysTable = new BackupSystemTable(conn)) { 108 // Step 1: Make sure there is no active session 109 // is running by using startBackupSession API 110 // If there is an active session in progress, exception will be thrown 111 try { 112 sysTable.startBackupExclusiveOperation(); 113 deleteSessionStarted = true; 114 } catch (IOException e) { 115 LOG.warn("You can not run delete command while active backup session is in progress. \n" 116 + "If there is no active backup session running, run backup repair utility to " 117 + "restore \nbackup system integrity."); 118 return -1; 119 } 120 121 // Step 2: Make sure there is no failed session 122 List<BackupInfo> list = 123 sysTable.getBackupHistory(NEW_TO_OLD, 1, withState(BackupState.RUNNING)); 124 if (list.size() != 0) { 125 // ailed sessions found 126 LOG.warn("Failed backup session found. Run backup repair tool first."); 127 return -1; 128 } 129 130 // Step 3: Record delete session 131 sysTable.startDeleteOperation(backupIds); 132 // Step 4: Snapshot backup system table 133 if (!BackupSystemTable.snapshotExists(conn)) { 134 BackupSystemTable.snapshot(conn); 135 } else { 136 LOG.warn("Backup system table snapshot exists"); 137 } 138 snapshotDone = true; 139 try { 140 List<String> affectedBackupRootDirs = new ArrayList<>(); 141 for (int i = 0; i < backupIds.length; i++) { 142 BackupInfo info = sysTable.readBackupInfo(backupIds[i]); 143 if (info == null) { 144 continue; 145 } 146 affectedBackupRootDirs.add(info.getBackupRootDir()); 147 totalDeleted += deleteBackup(backupIds[i], sysTable); 148 } 149 finalizeDelete(affectedBackupRootDirs, sysTable); 150 // Finish 151 sysTable.finishDeleteOperation(); 152 // delete snapshot 153 BackupSystemTable.deleteSnapshot(conn); 154 } catch (IOException e) { 155 // Fail delete operation 156 // Step 1 157 if (snapshotDone) { 158 if (BackupSystemTable.snapshotExists(conn)) { 159 BackupSystemTable.restoreFromSnapshot(conn); 160 // delete snapshot 161 BackupSystemTable.deleteSnapshot(conn); 162 // We still have record with unfinished delete operation 163 LOG.error("Delete operation failed, please run backup repair utility to restore " 164 + "backup system integrity", e); 165 throw e; 166 } else { 167 LOG.warn("Delete operation succeeded, there were some errors: ", e); 168 } 169 } 170 171 } finally { 172 if (deleteSessionStarted) { 173 sysTable.finishBackupExclusiveOperation(); 174 } 175 } 176 } 177 return totalDeleted; 178 } 179 180 /** 181 * Updates incremental backup set for every backupRoot 182 * @param backupRoots backupRoots for which to revise the incremental backup set 183 * @param table backup system table 184 * @throws IOException if a table operation fails 185 */ 186 @RestrictedApi( 187 explanation = "Package-private for test visibility only. Do not use outside tests.", 188 link = "", 189 allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/impl/BackupAdminImpl.java)") 190 void finalizeDelete(List<String> backupRoots, BackupSystemTable table) throws IOException { 191 for (String backupRoot : backupRoots) { 192 Set<TableName> incrTableSet = table.getIncrementalBackupTableSet(backupRoot); 193 Map<TableName, List<BackupInfo>> tableMap = 194 table.getBackupHistoryForTableSet(incrTableSet, backupRoot); 195 196 // Keep only the tables that are present in other backups 197 incrTableSet.retainAll(tableMap.keySet()); 198 199 table.deleteIncrementalBackupTableSet(backupRoot); 200 if (!incrTableSet.isEmpty()) { 201 table.addIncrementalBackupTableSet(incrTableSet, backupRoot); 202 } 203 } 204 } 205 206 /** 207 * Delete single backup and all related backups <br> 208 * Algorithm:<br> 209 * Backup type: FULL or INCREMENTAL <br> 210 * Is this last backup session for table T: YES or NO <br> 211 * For every table T from table list 'tables':<br> 212 * if(FULL, YES) deletes only physical data (PD) <br> 213 * if(FULL, NO), deletes PD, scans all newer backups and removes T from backupInfo,<br> 214 * until we either reach the most recent backup for T in the system or FULL backup<br> 215 * which includes T<br> 216 * if(INCREMENTAL, YES) deletes only physical data (PD) if(INCREMENTAL, NO) deletes physical data 217 * and for table T scans all backup images between last<br> 218 * FULL backup, which is older than the backup being deleted and the next FULL backup (if exists) 219 * <br> 220 * or last one for a particular table T and removes T from list of backup tables. 221 * @param backupId backup id 222 * @param sysTable backup system table 223 * @return total number of deleted backup images 224 * @throws IOException if deleting the backup fails 225 */ 226 @RestrictedApi( 227 explanation = "Package-private for test visibility only. Do not use outside tests.", 228 link = "", 229 allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/impl/BackupAdminImpl.java)") 230 int deleteBackup(String backupId, BackupSystemTable sysTable) throws IOException { 231 BackupInfo backupInfo = sysTable.readBackupInfo(backupId); 232 233 int totalDeleted = 0; 234 if (backupInfo != null) { 235 LOG.info("Deleting backup " + backupInfo.getBackupId() + " ..."); 236 // Step 1: clean up data for backup session (idempotent) 237 BackupUtils.cleanupBackupData(backupInfo, conn.getConfiguration()); 238 // List of tables in this backup; 239 List<TableName> tables = backupInfo.getTableNames(); 240 long startTime = backupInfo.getStartTs(); 241 for (TableName tn : tables) { 242 boolean isLastBackupSession = isLastBackupSession(sysTable, tn, startTime); 243 if (isLastBackupSession) { 244 continue; 245 } 246 // else 247 List<BackupInfo> affectedBackups = getAffectedBackupSessions(backupInfo, tn, sysTable); 248 for (BackupInfo info : affectedBackups) { 249 if (info.equals(backupInfo)) { 250 continue; 251 } 252 removeTableFromBackupImage(info, tn, sysTable); 253 } 254 } 255 Map<byte[], String> map = sysTable.readBulkLoadedFiles(backupId); 256 FileSystem fs = FileSystem.get(conn.getConfiguration()); 257 boolean success = true; 258 int numDeleted = 0; 259 for (String f : map.values()) { 260 Path p = new Path(f); 261 try { 262 LOG.debug("Delete backup info " + p + " for " + backupInfo.getBackupId()); 263 if (!fs.delete(p)) { 264 if (fs.exists(p)) { 265 LOG.warn(f + " was not deleted"); 266 success = false; 267 } 268 } else { 269 numDeleted++; 270 } 271 } catch (IOException ioe) { 272 LOG.warn(f + " was not deleted", ioe); 273 success = false; 274 } 275 } 276 if (LOG.isDebugEnabled()) { 277 LOG.debug(numDeleted + " bulk loaded files out of " + map.size() + " were deleted"); 278 } 279 if (success) { 280 sysTable.deleteBulkLoadedRows(new ArrayList<>(map.keySet())); 281 } 282 283 sysTable.deleteBackupInfo(backupInfo.getBackupId()); 284 LOG.info("Delete backup " + backupInfo.getBackupId() + " completed."); 285 totalDeleted++; 286 } else { 287 LOG.warn("Delete backup failed: no information found for backupID=" + backupId); 288 } 289 return totalDeleted; 290 } 291 292 @RestrictedApi( 293 explanation = "Package-private for test visibility only. Do not use outside tests.", 294 link = "", 295 allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/impl/BackupAdminImpl.java)") 296 void removeTableFromBackupImage(BackupInfo info, TableName tn, BackupSystemTable sysTable) 297 throws IOException { 298 List<TableName> tables = info.getTableNames(); 299 LOG.debug( 300 "Remove " + tn + " from " + info.getBackupId() + " tables=" + info.getTableListAsString()); 301 if (tables.contains(tn)) { 302 tables.remove(tn); 303 304 if (tables.isEmpty()) { 305 LOG.debug("Delete backup info " + info.getBackupId()); 306 307 // Clean up data before deleting the backup info, so a failure to remove the completion 308 // marker aborts before the metadata is gone. Idempotent operation. 309 BackupUtils.cleanupBackupData(info, conn.getConfiguration()); 310 sysTable.deleteBackupInfo(info.getBackupId()); 311 } else { 312 info.setTables(tables); 313 sysTable.updateBackupInfo(info); 314 // The backup directory no longer matches its manifest, so remove the completion marker 315 // before deleting the table's data. The backup stays COMPLETE in the system table. 316 HBackupFileSystem.deleteBackupCompleteMarker(conn.getConfiguration(), 317 info.getBackupRootDir(), info.getBackupId()); 318 // Now, clean up directory for table (idempotent) 319 cleanupBackupDir(info, tn, conn.getConfiguration()); 320 } 321 } 322 } 323 324 @RestrictedApi( 325 explanation = "Package-private for test visibility only. Do not use outside tests.", 326 link = "", 327 allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/impl/BackupAdminImpl.java)") 328 List<BackupInfo> getAffectedBackupSessions(BackupInfo backupInfo, TableName tn, 329 BackupSystemTable table) throws IOException { 330 LOG.debug("GetAffectedBackupInfos for: " + backupInfo.getBackupId() + " table=" + tn); 331 long ts = backupInfo.getStartTs(); 332 List<BackupInfo> list = new ArrayList<>(); 333 List<BackupInfo> history = table.getBackupHistory(withRoot(backupInfo.getBackupRootDir())); 334 // Scan from most recent to backupInfo 335 // break when backupInfo reached 336 for (BackupInfo info : history) { 337 if (info.getStartTs() == ts) { 338 break; 339 } 340 List<TableName> tables = info.getTableNames(); 341 if (tables.contains(tn)) { 342 BackupType bt = info.getType(); 343 if (bt == BackupType.FULL) { 344 // Clear list if we encounter FULL backup 345 list.clear(); 346 } else { 347 LOG.debug("GetAffectedBackupInfos for: " + backupInfo.getBackupId() + " table=" + tn 348 + " added " + info.getBackupId() + " tables=" + info.getTableListAsString()); 349 list.add(info); 350 } 351 } 352 } 353 return list; 354 } 355 356 /** 357 * Clean up the data at target directory 358 * @throws IOException if cleaning up the backup directory fails 359 */ 360 @RestrictedApi( 361 explanation = "Package-private for test visibility only. Do not use outside tests.", 362 link = "", 363 allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/impl/BackupAdminImpl.java)") 364 void cleanupBackupDir(BackupInfo backupInfo, TableName table, Configuration conf) 365 throws IOException { 366 try { 367 // clean up the data at target directory 368 String targetDir = backupInfo.getBackupRootDir(); 369 if (targetDir == null) { 370 LOG.warn("No target directory specified for " + backupInfo.getBackupId()); 371 return; 372 } 373 374 FileSystem outputFs = getFileSystem(new Path(backupInfo.getBackupRootDir()), conf); 375 376 Path targetDirPath = new Path(BackupUtils.getTableBackupDir(backupInfo.getBackupRootDir(), 377 backupInfo.getBackupId(), table)); 378 if (outputFs.delete(targetDirPath, true)) { 379 LOG.info("Cleaning up backup data at " + targetDirPath.toString() + " done."); 380 } else { 381 LOG.info("No data has been found in " + targetDirPath.toString() + "."); 382 } 383 } catch (IOException e1) { 384 LOG.error("Cleaning up backup data of " + backupInfo.getBackupId() + " for table " + table 385 + "at " + backupInfo.getBackupRootDir() + " failed due to " + e1.getMessage() + "."); 386 throw e1; 387 } 388 } 389 390 @RestrictedApi( 391 explanation = "Package-private for test visibility only. Do not use outside tests.", 392 link = "", 393 allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/impl/BackupAdminImpl.java)") 394 FileSystem getFileSystem(Path path, Configuration conf) throws IOException { 395 return FileSystem.get(path.toUri(), conf); 396 } 397 398 @RestrictedApi( 399 explanation = "Package-private for test visibility only. Do not use outside tests.", 400 link = "", 401 allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/impl/BackupAdminImpl.java)") 402 boolean isLastBackupSession(BackupSystemTable table, TableName tn, long startTime) 403 throws IOException { 404 List<BackupInfo> history = table.getBackupHistory(); 405 for (BackupInfo info : history) { 406 List<TableName> tables = info.getTableNames(); 407 if (!tables.contains(tn)) { 408 continue; 409 } 410 return info.getStartTs() <= startTime; 411 } 412 return false; 413 } 414 415 @Override 416 public List<BackupInfo> getHistory(int n, BackupInfo.Filter... filters) throws IOException { 417 try (final BackupSystemTable table = new BackupSystemTable(conn)) { 418 return table.getBackupHistory(NEW_TO_OLD, n, filters); 419 } 420 } 421 422 @Override 423 public List<BackupSet> listBackupSets() throws IOException { 424 try (final BackupSystemTable table = new BackupSystemTable(conn)) { 425 List<String> list = table.listBackupSets(); 426 List<BackupSet> bslist = new ArrayList<>(); 427 for (String s : list) { 428 List<TableName> tables = table.describeBackupSet(s); 429 if (tables != null) { 430 bslist.add(new BackupSet(s, tables)); 431 } 432 } 433 return bslist; 434 } 435 } 436 437 @Override 438 public BackupSet getBackupSet(String name) throws IOException { 439 try (final BackupSystemTable table = new BackupSystemTable(conn)) { 440 List<TableName> list = table.describeBackupSet(name); 441 442 if (list == null) { 443 return null; 444 } 445 446 return new BackupSet(name, list); 447 } 448 } 449 450 @Override 451 public boolean deleteBackupSet(String name) throws IOException { 452 try (final BackupSystemTable table = new BackupSystemTable(conn)) { 453 if (table.describeBackupSet(name) == null) { 454 return false; 455 } 456 table.deleteBackupSet(name); 457 return true; 458 } 459 } 460 461 @Override 462 public void addToBackupSet(String name, TableName[] tables) throws IOException { 463 String[] tableNames = new String[tables.length]; 464 try (final BackupSystemTable table = new BackupSystemTable(conn); 465 final Admin admin = conn.getAdmin()) { 466 for (int i = 0; i < tables.length; i++) { 467 tableNames[i] = tables[i].getNameAsString(); 468 if (!admin.tableExists(TableName.valueOf(tableNames[i]))) { 469 throw new IOException("Cannot add " + tableNames[i] + " because it doesn't exist"); 470 } 471 } 472 table.addToBackupSet(name, tableNames); 473 LOG.info( 474 "Added tables [" + StringUtils.join(tableNames, " ") + "] to '" + name + "' backup set"); 475 } 476 } 477 478 @Override 479 public void removeFromBackupSet(String name, TableName[] tables) throws IOException { 480 LOG.info("Removing tables [" + StringUtils.join(tables, " ") + "] from '" + name + "'"); 481 try (final BackupSystemTable table = new BackupSystemTable(conn)) { 482 table.removeFromBackupSet(name, toStringArray(tables)); 483 LOG.info( 484 "Removing tables [" + StringUtils.join(tables, " ") + "] from '" + name + "' completed."); 485 } 486 } 487 488 private String[] toStringArray(TableName[] list) { 489 String[] arr = new String[list.length]; 490 for (int i = 0; i < list.length; i++) { 491 arr[i] = list[i].toString(); 492 } 493 return arr; 494 } 495 496 @Override 497 public void restore(RestoreRequest request) throws IOException { 498 if (request.isCheck()) { 499 boolean isValid = validateRequest(request); 500 if (isValid) { 501 LOG.info(CHECK_OK); 502 } else { 503 LOG.error(CHECK_FAILED); 504 } 505 return; 506 } 507 // Execute restore request 508 new RestoreTablesClient(conn, request).execute(); 509 } 510 511 public boolean validateRequest(RestoreRequest request) throws IOException { 512 // check and load backup image manifest for the tables 513 Path rootPath = new Path(request.getBackupRootDir()); 514 String backupId = request.getBackupId(); 515 TableName[] sTableArray = request.getFromTables(); 516 BackupManifest manifest = 517 HBackupFileSystem.getManifest(conn.getConfiguration(), rootPath, backupId); 518 519 // Validate the backup image and its dependencies 520 return BackupUtils.validate(Arrays.asList(sTableArray), manifest, conn.getConfiguration()); 521 } 522 523 /** 524 * Initiates Point-In-Time Restore (PITR) for the given request. 525 * <p> 526 * If {@code backupRootDir} is specified in the request, performs PITR using metadata from the 527 * provided custom backup location. Otherwise, defaults to using metadata from the backup system 528 * table. 529 * @param request PointInTimeRestoreRequest containing PITR parameters. 530 * @throws IOException if validation fails or restore cannot be completed. 531 */ 532 @Override 533 public void pointInTimeRestore(PointInTimeRestoreRequest request) throws IOException { 534 AbstractPitrRestoreHandler handler; 535 536 // Choose the appropriate handler based on whether a custom backup location is provided 537 if (request.getBackupRootDir() == null) { 538 handler = new DefaultPitrRestoreHandler(conn, request); 539 } else { 540 handler = new CustomBackupLocationPitrRestoreHandler(conn, request); 541 } 542 handler.validateAndRestore(); 543 544 LOG.info("Successfully completed Point In Time Restore for all tables."); 545 } 546 547 @Override 548 public String backupTables(BackupRequest request) throws IOException { 549 BackupType type = request.getBackupType(); 550 String targetRootDir = request.getTargetRootDir(); 551 List<TableName> tableList = request.getTableList(); 552 553 String backupId = BackupRestoreConstants.BACKUPID_PREFIX + EnvironmentEdgeManager.currentTime(); 554 if (type == BackupType.INCREMENTAL) { 555 if (request.isContinuousBackupEnabled()) { 556 Set<TableName> continuousBackupTableSet; 557 try (BackupSystemTable table = new BackupSystemTable(conn)) { 558 continuousBackupTableSet = table.getContinuousBackupTableSet().keySet(); 559 } 560 if (continuousBackupTableSet.isEmpty()) { 561 String msg = "Continuous backup table set contains no tables. " 562 + "You need to run Continuous backup first " 563 + (tableList != null ? "on " + StringUtils.join(tableList, ",") : ""); 564 throw new IOException(msg); 565 } 566 if (!continuousBackupTableSet.containsAll(tableList)) { 567 String extraTables = StringUtils.join(tableList, ","); 568 String msg = "Some tables (" + extraTables + ") haven't gone through Continuous backup. " 569 + "Perform Continuous backup on " + extraTables + " first, then retry the command"; 570 throw new IOException(msg); 571 } 572 } else { 573 Set<TableName> incrTableSet; 574 try (BackupSystemTable table = new BackupSystemTable(conn)) { 575 incrTableSet = table.getIncrementalBackupTableSet(targetRootDir); 576 } 577 578 if (incrTableSet.isEmpty()) { 579 String msg = "Incremental backup table set contains no tables. " 580 + "You need to run full backup first " 581 + (tableList != null ? "on " + StringUtils.join(tableList, ",") : ""); 582 583 throw new IOException(msg); 584 } 585 if (tableList != null) { 586 tableList.removeAll(incrTableSet); 587 if (!tableList.isEmpty()) { 588 String extraTables = StringUtils.join(tableList, ","); 589 String msg = "Some tables (" + extraTables + ") haven't gone through full backup. " 590 + "Perform full backup on " + extraTables + " first, then retry the command"; 591 throw new IOException(msg); 592 } 593 } 594 tableList = Lists.newArrayList(incrTableSet); 595 } 596 } 597 if (tableList != null && !tableList.isEmpty()) { 598 for (TableName table : tableList) { 599 String targetTableBackupDir = 600 HBackupFileSystem.getTableBackupDir(targetRootDir, backupId, table); 601 Path targetTableBackupDirPath = new Path(targetTableBackupDir); 602 FileSystem outputFs = 603 FileSystem.get(targetTableBackupDirPath.toUri(), conn.getConfiguration()); 604 if (outputFs.exists(targetTableBackupDirPath)) { 605 throw new IOException( 606 "Target backup directory " + targetTableBackupDir + " exists already."); 607 } 608 outputFs.mkdirs(targetTableBackupDirPath); 609 } 610 ArrayList<TableName> nonExistingTableList = null; 611 try (Admin admin = conn.getAdmin()) { 612 for (TableName tableName : tableList) { 613 if (!admin.tableExists(tableName)) { 614 if (nonExistingTableList == null) { 615 nonExistingTableList = new ArrayList<>(); 616 } 617 nonExistingTableList.add(tableName); 618 } 619 } 620 } 621 if (nonExistingTableList != null) { 622 // Non-continuous incremental backup is controlled by 'incremental backup table set' 623 // and not by user provided backup table list. This is an optimization to avoid copying 624 // the same set of WALs for incremental backups of different tables at different times 625 // HBASE-14038. Since continuous incremental backup and full backup backs-up user provided 626 // table list, we should inform use about non-existence of input table(s) 627 if (type == BackupType.INCREMENTAL && !request.isContinuousBackupEnabled()) { 628 // Update incremental backup set 629 tableList = excludeNonExistingTables(tableList, nonExistingTableList); 630 } else { 631 // Throw exception only in full mode - we try to backup non-existing table 632 throw new IOException( 633 "Non-existing tables found in the table list: " + nonExistingTableList); 634 } 635 } 636 } 637 638 // update table list 639 BackupRequest.Builder builder = new BackupRequest.Builder(); 640 request = builder.withBackupType(request.getBackupType()).withTableList(tableList) 641 .withTargetRootDir(request.getTargetRootDir()).withBackupSetName(request.getBackupSetName()) 642 .withTotalTasks(request.getTotalTasks()).withBandwidthPerTasks((int) request.getBandwidth()) 643 .withNoChecksumVerify(request.getNoChecksumVerify()) 644 .withContinuousBackupEnabled(request.isContinuousBackupEnabled()).build(); 645 646 TableBackupClient client; 647 try { 648 client = BackupClientFactory.create(conn, backupId, request); 649 } catch (IOException e) { 650 LOG.error("There is an active session already running"); 651 throw e; 652 } 653 654 client.execute(); 655 656 return backupId; 657 } 658 659 private List<TableName> excludeNonExistingTables(List<TableName> tableList, 660 List<TableName> nonExistingTableList) { 661 for (TableName table : nonExistingTableList) { 662 tableList.remove(table); 663 } 664 return tableList; 665 } 666 667 @Override 668 public void mergeBackups(String[] backupIds) throws IOException { 669 try (final BackupSystemTable sysTable = new BackupSystemTable(conn)) { 670 checkIfValidForMerge(backupIds, sysTable); 671 // TODO run job on remote cluster 672 BackupMergeJob job = BackupRestoreFactory.getBackupMergeJob(conn.getConfiguration()); 673 job.run(backupIds); 674 } 675 } 676 677 /** 678 * Verifies that backup images are valid for merge. 679 * <ul> 680 * <li>All backups MUST be in the same destination 681 * <li>No FULL backups are allowed - only INCREMENTAL 682 * <li>All backups must be in COMPLETE state 683 * <li>No holes in backup list are allowed 684 * </ul> 685 * <p> 686 * @param backupIds list of backup ids 687 * @param table backup system table 688 * @throws IOException if the backup image is not valid for merge 689 */ 690 @RestrictedApi( 691 explanation = "Package-private for test visibility only. Do not use outside tests.", 692 link = "", 693 allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/impl/BackupAdminImpl.java)") 694 void checkIfValidForMerge(String[] backupIds, BackupSystemTable table) throws IOException { 695 String backupRoot = null; 696 697 final Set<TableName> allTables = new HashSet<>(); 698 final Set<String> allBackups = new HashSet<>(); 699 long minTime = Long.MAX_VALUE, maxTime = Long.MIN_VALUE; 700 for (String backupId : backupIds) { 701 BackupInfo bInfo = table.readBackupInfo(backupId); 702 if (bInfo == null) { 703 String msg = "Backup session " + backupId + " not found"; 704 throw new IOException(msg); 705 } 706 if (backupRoot == null) { 707 backupRoot = bInfo.getBackupRootDir(); 708 } else if (!bInfo.getBackupRootDir().equals(backupRoot)) { 709 throw new IOException("Found different backup destinations in a list of a backup sessions " 710 + "\n1. " + backupRoot + "\n" + "2. " + bInfo.getBackupRootDir()); 711 } 712 if (bInfo.getType() == BackupType.FULL) { 713 throw new IOException("FULL backup image can not be merged for: \n" + bInfo); 714 } 715 716 if (bInfo.getState() != BackupState.COMPLETE) { 717 throw new IOException("Backup image " + backupId 718 + " can not be merged becuase of its state: " + bInfo.getState()); 719 } 720 allBackups.add(backupId); 721 allTables.addAll(bInfo.getTableNames()); 722 long time = bInfo.getStartTs(); 723 if (time < minTime) { 724 minTime = time; 725 } 726 if (time > maxTime) { 727 maxTime = time; 728 } 729 } 730 731 final long startRangeTime = minTime; 732 final long endRangeTime = maxTime; 733 final String backupDest = backupRoot; 734 // Check we have no 'holes' in backup id list 735 // Filter 1 : backupRoot 736 // Filter 2 : time range filter 737 // Filter 3 : table filter 738 BackupInfo.Filter destinationFilter = withRoot(backupDest); 739 740 BackupInfo.Filter timeRangeFilter = info -> { 741 long time = info.getStartTs(); 742 return time >= startRangeTime && time <= endRangeTime; 743 }; 744 745 BackupInfo.Filter tableFilter = info -> { 746 List<TableName> tables = info.getTableNames(); 747 return !Collections.disjoint(allTables, tables); 748 }; 749 750 BackupInfo.Filter typeFilter = withType(BackupType.INCREMENTAL); 751 BackupInfo.Filter stateFilter = withState(BackupState.COMPLETE); 752 753 List<BackupInfo> allInfos = table.getBackupHistory(destinationFilter, timeRangeFilter, 754 tableFilter, typeFilter, stateFilter); 755 if (allInfos.size() != allBackups.size()) { 756 // Yes we have at least one hole in backup image sequence 757 List<String> missingIds = new ArrayList<>(); 758 for (BackupInfo info : allInfos) { 759 if (allBackups.contains(info.getBackupId())) { 760 continue; 761 } 762 missingIds.add(info.getBackupId()); 763 } 764 String errMsg = 765 "Sequence of backup ids has 'holes'. The following backup images must be added:" 766 + org.apache.hadoop.util.StringUtils.join(",", missingIds); 767 throw new IOException(errMsg); 768 } 769 } 770}