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; 019 020import static org.apache.hadoop.hbase.backup.TestBackupUtils.assertBackupCompleteFileDoesNotExist; 021import static org.apache.hadoop.hbase.backup.TestBackupUtils.assertBackupCompleteFileExists; 022import static org.apache.hadoop.hbase.backup.util.BackupUtils.succeeded; 023import static org.junit.jupiter.api.Assertions.assertEquals; 024import static org.junit.jupiter.api.Assertions.assertFalse; 025import static org.junit.jupiter.api.Assertions.assertTrue; 026import static org.junit.jupiter.api.Assertions.fail; 027 028import java.io.IOException; 029import java.util.ArrayList; 030import java.util.List; 031import org.apache.commons.lang3.StringUtils; 032import org.apache.hadoop.conf.Configuration; 033import org.apache.hadoop.fs.FileSystem; 034import org.apache.hadoop.fs.Path; 035import org.apache.hadoop.hbase.TableName; 036import org.apache.hadoop.hbase.backup.impl.BackupAdminImpl; 037import org.apache.hadoop.hbase.backup.impl.BackupCommands; 038import org.apache.hadoop.hbase.backup.impl.BackupSystemTable; 039import org.apache.hadoop.hbase.backup.mapreduce.MapReduceBackupMergeJob; 040import org.apache.hadoop.hbase.backup.mapreduce.MapReduceHFileSplitterJob; 041import org.apache.hadoop.hbase.backup.util.BackupUtils; 042import org.apache.hadoop.hbase.client.Admin; 043import org.apache.hadoop.hbase.client.Connection; 044import org.apache.hadoop.hbase.client.ConnectionFactory; 045import org.apache.hadoop.hbase.client.Table; 046import org.apache.hadoop.hbase.testclassification.LargeTests; 047import org.apache.hadoop.hbase.util.Pair; 048import org.junit.jupiter.api.Tag; 049import org.junit.jupiter.api.Test; 050import org.slf4j.Logger; 051import org.slf4j.LoggerFactory; 052 053import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 054 055@Tag(LargeTests.TAG) 056public class TestIncrementalBackupMergeWithFailures extends TestBackupBase { 057 058 private static final Logger LOG = 059 LoggerFactory.getLogger(TestIncrementalBackupMergeWithFailures.class); 060 061 enum FailurePhase { 062 PHASE1, 063 PHASE2, 064 PHASE3, 065 PHASE4 066 } 067 068 public final static String FAILURE_PHASE_KEY = "failurePhase"; 069 070 static class BackupMergeJobWithFailures extends MapReduceBackupMergeJob { 071 FailurePhase failurePhase; 072 073 @Override 074 public void setConf(Configuration conf) { 075 super.setConf(conf); 076 String val = conf.get(FAILURE_PHASE_KEY); 077 if (val != null) { 078 failurePhase = FailurePhase.valueOf(val); 079 } else { 080 fail("Failure phase is not set"); 081 } 082 } 083 084 /** 085 * This is the exact copy of parent's run() with injections of different types of failures 086 */ 087 @Override 088 public void run(String[] backupIds) throws IOException { 089 String bulkOutputConfKey; 090 091 // TODO : run player on remote cluster 092 player = new MapReduceHFileSplitterJob(); 093 bulkOutputConfKey = MapReduceHFileSplitterJob.BULK_OUTPUT_CONF_KEY; 094 // Player reads all files in arbitrary directory structure and creates 095 // a Map task for each file 096 String bids = StringUtils.join(backupIds, ","); 097 098 if (LOG.isDebugEnabled()) { 099 LOG.debug("Merge backup images " + bids); 100 } 101 102 List<Pair<TableName, Path>> processedTableList = new ArrayList<>(); 103 boolean finishedTables = false; 104 Connection conn = ConnectionFactory.createConnection(getConf()); 105 BackupSystemTable table = new BackupSystemTable(conn); 106 FileSystem fs = FileSystem.get(getConf()); 107 108 try { 109 // Start backup exclusive operation 110 table.startBackupExclusiveOperation(); 111 // Start merge operation 112 table.startMergeOperation(backupIds); 113 114 // Select most recent backup id 115 String mergedBackupId = BackupUtils.findMostRecentBackupId(backupIds); 116 117 TableName[] tableNames = getTableNamesInBackupImages(backupIds); 118 119 BackupInfo bInfo = table.readBackupInfo(backupIds[0]); 120 String backupRoot = bInfo.getBackupRootDir(); 121 // PHASE 1 122 checkFailure(FailurePhase.PHASE1); 123 124 for (int i = 0; i < tableNames.length; i++) { 125 LOG.info("Merge backup images for " + tableNames[i]); 126 127 // Find input directories for table 128 Path[] dirPaths = findInputDirectories(fs, backupRoot, tableNames[i], backupIds); 129 String dirs = StringUtils.join(dirPaths, ","); 130 Path bulkOutputPath = BackupUtils.getBulkOutputDir( 131 BackupUtils.getFileNameCompatibleString(tableNames[i]), getConf(), false); 132 // Delete content if exists 133 if (fs.exists(bulkOutputPath)) { 134 if (!fs.delete(bulkOutputPath, true)) { 135 LOG.warn("Can not delete: " + bulkOutputPath); 136 } 137 } 138 Configuration conf = getConf(); 139 conf.set(bulkOutputConfKey, bulkOutputPath.toString()); 140 String[] playerArgs = { dirs, tableNames[i].getNameAsString() }; 141 142 // PHASE 2 143 checkFailure(FailurePhase.PHASE2); 144 player.setConf(getConf()); 145 int result = player.run(playerArgs); 146 if (succeeded(result)) { 147 // Add to processed table list 148 processedTableList.add(new Pair<>(tableNames[i], bulkOutputPath)); 149 } else { 150 throw new IOException("Can not merge backup images for " + dirs 151 + " (check Hadoop/MR and HBase logs). Player return code =" + result); 152 } 153 LOG.debug("Merge Job finished:" + result); 154 } 155 List<TableName> tableList = toTableNameList(processedTableList); 156 // PHASE 3 157 checkFailure(FailurePhase.PHASE3); 158 table.updateProcessedTablesForMerge(tableList); 159 finishedTables = true; 160 161 // (modification of a backup file system) 162 // Move existing mergedBackupId data into tmp directory 163 // we will need it later in case of a failure 164 Path tmpBackupDir = 165 HBackupFileSystem.getBackupTmpDirPathForBackupId(backupRoot, mergedBackupId); 166 Path backupDirPath = HBackupFileSystem.getBackupPath(backupRoot, mergedBackupId); 167 if (!fs.rename(backupDirPath, tmpBackupDir)) { 168 throw new IOException("Failed to rename " + backupDirPath + " to " + tmpBackupDir); 169 } else { 170 LOG.debug("Renamed " + backupDirPath + " to " + tmpBackupDir); 171 } 172 // Move new data into backup dest 173 for (Pair<TableName, Path> tn : processedTableList) { 174 moveData(fs, backupRoot, tn.getSecond(), tn.getFirst(), mergedBackupId); 175 } 176 checkFailure(FailurePhase.PHASE4); 177 // Update backup manifest 178 List<String> backupsToDelete = getBackupIdsToDelete(backupIds, mergedBackupId); 179 updateBackupManifest(tmpBackupDir.getParent().toString(), mergedBackupId, backupsToDelete); 180 // Copy meta files back from tmp to backup dir 181 copyMetaData(fs, tmpBackupDir, backupDirPath); 182 // Delete tmp dir (Rename back during repair) 183 if (!fs.delete(tmpBackupDir, true)) { 184 // WARN and ignore 185 LOG.warn("Could not delete tmp dir: " + tmpBackupDir); 186 } 187 // Delete old data 188 deleteBackupImages(backupsToDelete, conn, fs, backupRoot); 189 // Finish merge session 190 table.finishMergeOperation(); 191 // Release lock 192 table.finishBackupExclusiveOperation(); 193 // Write the completion marker after the merge is fully finalized and the lock is 194 // released, so external consumers never observe it on a partially-merged backup. 195 HBackupFileSystem.writeBackupCompleteMarker(conf, backupRoot, mergedBackupId); 196 } catch (RuntimeException e) { 197 throw e; 198 } catch (Exception e) { 199 LOG.error(e.toString(), e); 200 if (!finishedTables) { 201 // cleanup bulk directories and finish merge 202 // merge MUST be repeated (no need for repair) 203 cleanupBulkLoadDirs(fs, toPathList(processedTableList)); 204 table.finishMergeOperation(); 205 table.finishBackupExclusiveOperation(); 206 throw new IOException("Backup merge operation failed, you should try it again", e); 207 } else { 208 // backup repair must be run 209 throw new IOException( 210 "Backup merge operation failed, run backup repair tool to restore system's integrity", 211 e); 212 } 213 } finally { 214 table.close(); 215 conn.close(); 216 } 217 } 218 219 private void checkFailure(FailurePhase phase) throws IOException { 220 if (failurePhase != null && failurePhase == phase) { 221 throw new IOException(phase.toString()); 222 } 223 } 224 } 225 226 @Test 227 public void TestIncBackupMergeRestore() throws Exception { 228 int ADD_ROWS = 99; 229 // #1 - create full backup for all tables 230 LOG.info("create full backup image for all tables"); 231 232 List<TableName> tables = Lists.newArrayList(table1, table2); 233 // Set custom Merge Job implementation 234 conf1.setClass(BackupRestoreFactory.HBASE_BACKUP_MERGE_IMPL_CLASS, 235 BackupMergeJobWithFailures.class, BackupMergeJob.class); 236 237 Connection conn = ConnectionFactory.createConnection(conf1); 238 239 Admin admin = conn.getAdmin(); 240 BackupAdminImpl client = new BackupAdminImpl(conn); 241 242 BackupRequest request = createBackupRequest(BackupType.FULL, tables, BACKUP_ROOT_DIR); 243 String backupIdFull = client.backupTables(request); 244 245 assertTrue(checkSucceeded(backupIdFull)); 246 247 // #2 - insert some data to table1 248 Table t1 = insertIntoTable(conn, table1, famName, 1, ADD_ROWS); 249 LOG.debug("writing " + ADD_ROWS + " rows to " + table1); 250 251 assertEquals(NB_ROWS_IN_BATCH + ADD_ROWS, TEST_UTIL.countRows(t1)); 252 t1.close(); 253 LOG.debug("written " + ADD_ROWS + " rows to " + table1); 254 255 Table t2 = insertIntoTable(conn, table2, famName, 1, ADD_ROWS); 256 257 assertEquals(NB_ROWS_IN_BATCH + ADD_ROWS, TEST_UTIL.countRows(t2)); 258 t2.close(); 259 LOG.debug("written " + ADD_ROWS + " rows to " + table2); 260 261 // #3 - incremental backup for multiple tables 262 tables = Lists.newArrayList(table1, table2); 263 request = createBackupRequest(BackupType.INCREMENTAL, tables, BACKUP_ROOT_DIR); 264 String backupIdIncMultiple = client.backupTables(request); 265 266 assertTrue(checkSucceeded(backupIdIncMultiple)); 267 268 t1 = insertIntoTable(conn, table1, famName, 2, ADD_ROWS); 269 t1.close(); 270 271 t2 = insertIntoTable(conn, table2, famName, 2, ADD_ROWS); 272 t2.close(); 273 274 // #3 - incremental backup for multiple tables 275 request = createBackupRequest(BackupType.INCREMENTAL, tables, BACKUP_ROOT_DIR); 276 String backupIdIncMultiple2 = client.backupTables(request); 277 assertTrue(checkSucceeded(backupIdIncMultiple2)); 278 // #4 Merge backup images with failures 279 280 for (FailurePhase phase : FailurePhase.values()) { 281 Configuration conf = conn.getConfiguration(); 282 283 conf.set(FAILURE_PHASE_KEY, phase.toString()); 284 285 try (BackupAdmin bAdmin = new BackupAdminImpl(conn)) { 286 String[] backups = new String[] { backupIdIncMultiple, backupIdIncMultiple2 }; 287 bAdmin.mergeBackups(backups); 288 fail("Expected IOException"); 289 } catch (IOException e) { 290 BackupSystemTable table = new BackupSystemTable(conn); 291 if (phase.ordinal() < FailurePhase.PHASE4.ordinal()) { 292 // No need to repair: 293 // Both Merge and backup exclusive operations are finished 294 assertFalse(table.isMergeInProgress()); 295 // Merge failed before filesystem modifications — original markers intact 296 assertBackupCompleteFileExists(conf, BACKUP_ROOT_DIR, backupIdIncMultiple); 297 assertBackupCompleteFileExists(conf, BACKUP_ROOT_DIR, backupIdIncMultiple2); 298 try { 299 table.finishBackupExclusiveOperation(); 300 fail("IOException is expected"); 301 } catch (IOException ee) { 302 // Expected 303 } 304 } else { 305 // Repair is required 306 assertTrue(table.isMergeInProgress()); 307 // Merge failed during finalization — merged backup must NOT appear complete 308 assertBackupCompleteFileDoesNotExist(conf, BACKUP_ROOT_DIR, backupIdIncMultiple2); 309 try { 310 table.startBackupExclusiveOperation(); 311 fail("IOException is expected"); 312 } catch (IOException ee) { 313 // Expected - clean up before proceeding 314 // table.finishMergeOperation(); 315 // table.finishBackupExclusiveOperation(); 316 } 317 } 318 table.close(); 319 LOG.debug("Expected :" + e.getMessage()); 320 } 321 } 322 // Now merge w/o failures 323 Configuration conf = conn.getConfiguration(); 324 conf.unset(FAILURE_PHASE_KEY); 325 conf.unset(BackupRestoreFactory.HBASE_BACKUP_MERGE_IMPL_CLASS); 326 // Now run repair 327 BackupSystemTable sysTable = new BackupSystemTable(conn); 328 BackupCommands.RepairCommand.repairFailedBackupMergeIfAny(conn, sysTable); 329 // Now repeat merge 330 try (BackupAdmin bAdmin = new BackupAdminImpl(conn)) { 331 String[] backups = new String[] { backupIdIncMultiple, backupIdIncMultiple2 }; 332 bAdmin.mergeBackups(backups); 333 } 334 335 // After successful merge, the merged-into backup should have the marker 336 assertBackupCompleteFileExists(conf1, BACKUP_ROOT_DIR, backupIdIncMultiple2); 337 // The merged-away backup should no longer exist 338 assertBackupCompleteFileDoesNotExist(conf1, BACKUP_ROOT_DIR, backupIdIncMultiple); 339 340 // #6 - restore incremental backup for multiple tables, with overwrite 341 TableName[] tablesRestoreIncMultiple = new TableName[] { table1, table2 }; 342 TableName[] tablesMapIncMultiple = new TableName[] { table1_restore, table2_restore }; 343 client.restore(BackupUtils.createRestoreRequest(BACKUP_ROOT_DIR, backupIdIncMultiple2, false, 344 tablesRestoreIncMultiple, tablesMapIncMultiple, true)); 345 346 Table hTable = conn.getTable(table1_restore); 347 LOG.debug("After incremental restore: " + hTable.getDescriptor()); 348 LOG.debug("f1 has " + TEST_UTIL.countRows(hTable, famName) + " rows"); 349 assertEquals(NB_ROWS_IN_BATCH + 2 * ADD_ROWS, TEST_UTIL.countRows(hTable, famName)); 350 351 hTable.close(); 352 353 hTable = conn.getTable(table2_restore); 354 assertEquals(NB_ROWS_IN_BATCH + 2 * ADD_ROWS, TEST_UTIL.countRows(hTable)); 355 hTable.close(); 356 357 admin.close(); 358 conn.close(); 359 } 360}