Skip to content

Commit

Permalink
HBASE-28412 Select correct target table for incremental backup
Browse files Browse the repository at this point in the history
The restore table was wrongly selected for incremental backups causing
incremental backup to fail when the 'from_table' does not exist.
This is now fixed.
  • Loading branch information
rubenvw-ngdata committed Mar 26, 2024
1 parent 38aef80 commit e1a5222
Show file tree
Hide file tree
Showing 2 changed files with 340 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ public void run(Path[] dirPaths, TableName[] tableNames, Path restoreRootDir,
BackupUtils.getFileNameCompatibleString(newTableNames[i]), getConf());
Configuration conf = getConf();
conf.set(bulkOutputConfKey, bulkOutputPath.toString());
String[] playerArgs = { dirs,
fullBackupRestore ? newTableNames[i].getNameAsString() : tableNames[i].getNameAsString() };

String[] playerArgs = { dirs, newTableNames[i].getNameAsString() };
int result;
try {

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,339 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.backup;

import static org.apache.hadoop.hbase.backup.BackupInfo.BackupState.COMPLETE;
import static org.apache.hadoop.hbase.backup.BackupType.FULL;
import static org.apache.hadoop.hbase.backup.BackupType.INCREMENTAL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.backup.impl.BackupAdminImpl;
import org.apache.hadoop.hbase.backup.impl.BackupManager;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.io.hfile.HFile;
import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testing.TestingHBaseCluster;
import org.apache.hadoop.hbase.testing.TestingHBaseClusterOption;
import org.apache.hadoop.hbase.tool.BulkLoadHFiles;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Category(MediumTests.class)
@RunWith(Parameterized.class)
public class TestBackupRestoreWithModifications {

private static final Logger LOG =
LoggerFactory.getLogger(TestBackupRestoreWithModifications.class);

@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestBackupRestoreWithModifications.class);

@Parameterized.Parameters(name = "{index}: useBulkLoad={0}, removeTablesBeforeRestore={1}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] { { false, false }, { false, true }, { true, false } });
}

@Parameterized.Parameter(0)
public boolean useBulkLoad;

@Parameterized.Parameter(1) public boolean removeTablesBeforeRestore;

private TableName sourceTable;
private TableName targetTable;

private List<TableName> allTables;
private static TestingHBaseCluster cluster;
private static Path BACKUP_ROOT_DIR;
private static final byte[] COLUMN_FAMILY = Bytes.toBytes("0");

@BeforeClass
public static void beforeClass() throws Exception {
Configuration conf = HBaseConfiguration.create();
enableBackup(conf);
cluster = TestingHBaseCluster.create(TestingHBaseClusterOption.builder().conf(conf).build());
cluster.start();
BACKUP_ROOT_DIR = new Path(new Path(conf.get("fs.defaultFS")), new Path("/backupIT"));
}

@AfterClass
public static void afterClass() throws Exception {
cluster.stop();
}

@Before
public void setUp() throws Exception {
sourceTable =
TableName.valueOf(String.format("table-%s-%s", useBulkLoad, removeTablesBeforeRestore));
targetTable = TableName.valueOf(
String.format("another-table-%s-%s", useBulkLoad, removeTablesBeforeRestore));
allTables = Arrays.asList(sourceTable, targetTable);
createTable(sourceTable);
createTable(targetTable);
}

@After public void removeTables() throws Exception {
deleteTables();
}

@Test
public void testModificationsOnTable() throws Exception {
Instant timestamp = Instant.now();

// load some data
load(sourceTable, timestamp, "data");

String backupId = backup(FULL, allTables);
BackupInfo backupInfo = verifyBackup(backupId, FULL, COMPLETE);
assertTrue(backupInfo.getTables().contains(sourceTable));

// load new data on the same timestamp
load(sourceTable, timestamp, "changed_data");

backupId = backup(FULL, allTables);
backupInfo = verifyBackup(backupId, FULL, COMPLETE);
assertTrue(backupInfo.getTables().contains(sourceTable));

restore(backupId, sourceTable, targetTable);
if (!removeTablesBeforeRestore) {
validateDataEquals(sourceTable, "changed_data");
}
validateDataEquals(targetTable, "changed_data");
}

@Test public void testModificationsOnTableForIncremental() throws Exception {
Instant timestamp = Instant.now();

// load some data
load(sourceTable, timestamp, "data");

String backupId = backup(FULL, allTables);

BackupInfo backupInfo = verifyBackup(backupId, FULL, COMPLETE);
assertTrue(backupInfo.getTables().contains(sourceTable));

load(sourceTable, timestamp, "data");
String backupId2 = backup(INCREMENTAL, allTables);
verifyBackup(backupId2, INCREMENTAL, COMPLETE);
load(sourceTable, timestamp, "changed_data");
String backupId3 = backup(INCREMENTAL, allTables);
verifyBackup(backupId3, INCREMENTAL, COMPLETE);

FileSystem fs = FileSystem.get(cluster.getConf());
RemoteIterator<LocatedFileStatus> it = fs.listFiles(BACKUP_ROOT_DIR, true);
List<Path> backupFiles = new ArrayList<>();
while (it.hasNext()) {
Path path = it.next().getPath();
backupFiles.add(path);
}
for (Path backupFile : backupFiles) {
System.out.println(backupFile);
}

restore(backupId3, sourceTable, targetTable);
if (!removeTablesBeforeRestore) {
validateDataEquals(sourceTable, "changed_data");
}
validateDataEquals(targetTable, "changed_data");
}

private void createTable(TableName tableName) throws IOException {
TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableName)
.setColumnFamily(ColumnFamilyDescriptorBuilder.of(COLUMN_FAMILY));
try (Connection connection = ConnectionFactory.createConnection(cluster.getConf());
Admin admin = connection.getAdmin()) {
admin.createTable(builder.build());
}
}

private void deleteTables() throws IOException {
try (Connection connection = ConnectionFactory.createConnection(cluster.getConf());
Admin admin = connection.getAdmin()) {
for (TableName table : allTables) {
if (admin.tableExists(table)) {
admin.disableTable(table);
admin.deleteTable(table);
}
}
}
}

private void load(TableName tableName, Instant timestamp, String data) throws IOException {
if (useBulkLoad) {
hFileBulkLoad(tableName, timestamp, data);
} else {
putLoad(tableName, timestamp, data);
}
}

private void putLoad(TableName tableName, Instant timestamp, String data) throws IOException {
LOG.info("Writing new data to HBase using normal Puts: {}", data);
try (Connection connection = ConnectionFactory.createConnection(cluster.getConf())) {
Table table = connection.getTable(sourceTable);
List<Put> puts = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Put put = new Put(Bytes.toBytes(i), timestamp.toEpochMilli());
put.addColumn(COLUMN_FAMILY, Bytes.toBytes("data"), Bytes.toBytes(data));
puts.add(put);

if (i % 100 == 0) {
table.put(puts);
puts.clear();
}
}
if (!puts.isEmpty()) {
table.put(puts);
}
connection.getAdmin().flush(tableName);
}
}

private void hFileBulkLoad(TableName tableName, Instant timestamp, String data)
throws IOException {
FileSystem fs = FileSystem.get(cluster.getConf());
LOG.info("Writing new data to HBase using BulkLoad: {}", data);
// HFiles require this strict directory structure to allow to load them
Path hFileRootPath = new Path("/tmp/hfiles_" + UUID.randomUUID());
fs.mkdirs(hFileRootPath);
Path hFileFamilyPath = new Path(hFileRootPath, Bytes.toString(COLUMN_FAMILY));
fs.mkdirs(hFileFamilyPath);
try (HFile.Writer writer = HFile.getWriterFactoryNoCache(cluster.getConf())
.withPath(fs, new Path(hFileFamilyPath, "hfile_" + UUID.randomUUID()))
.withFileContext(new HFileContextBuilder().withTableName(tableName.toBytes())
.withColumnFamily(COLUMN_FAMILY).build())
.create()) {
for (int i = 0; i < 10; i++) {
writer.append(new KeyValue(Bytes.toBytes(i), COLUMN_FAMILY, Bytes.toBytes("data"),
timestamp.toEpochMilli(), Bytes.toBytes(data)));
}
}
Map<BulkLoadHFiles.LoadQueueItem, ByteBuffer> result =
BulkLoadHFiles.create(cluster.getConf()).bulkLoad(tableName, hFileRootPath);
assertFalse(result.isEmpty());
}

private String backup(BackupType backupType, List<TableName> tables) throws IOException {
LOG.info("Creating the backup ...");

try (Connection connection = ConnectionFactory.createConnection(cluster.getConf());
BackupAdmin backupAdmin = new BackupAdminImpl(connection)) {
BackupRequest backupRequest =
new BackupRequest.Builder().withTargetRootDir(BACKUP_ROOT_DIR.toString())
.withTableList(new ArrayList<>(tables)).withBackupType(backupType).build();
return backupAdmin.backupTables(backupRequest);
}

}

private void restore(String backupId, TableName sourceTableName, TableName targetTableName)
throws IOException {
LOG.info("Restoring data ...");

if (removeTablesBeforeRestore) {
LOG.info("Deleting the tables before restore ...");
deleteTables();
}

try (Connection connection = ConnectionFactory.createConnection(cluster.getConf());
BackupAdmin backupAdmin = new BackupAdminImpl(connection)) {
RestoreRequest restoreRequest = new RestoreRequest.Builder().withBackupId(backupId)
.withBackupRootDir(BACKUP_ROOT_DIR.toString()).withOvewrite(true)
.withFromTables(new TableName[] { sourceTableName })
.withToTables(new TableName[] { targetTableName }).build();
backupAdmin.restore(restoreRequest);
}
}

private void validateDataEquals(TableName tableName, String expectedData) throws IOException {
try (Connection connection = ConnectionFactory.createConnection(cluster.getConf());
Table table = connection.getTable(tableName)) {
Scan scan = new Scan();
scan.readAllVersions();
scan.setRaw(true);
scan.setBatch(100);

for (Result sourceResult : table.getScanner(scan)) {
List<Cell> sourceCells = sourceResult.listCells();
for (Cell cell : sourceCells) {
assertEquals(expectedData, Bytes.toStringBinary(cell.getValueArray(),
cell.getValueOffset(), cell.getValueLength()));
}
}
}
}

private BackupInfo verifyBackup(String backupId, BackupType expectedType,
BackupInfo.BackupState expectedState) throws IOException {
try (Connection connection = ConnectionFactory.createConnection(cluster.getConf());
BackupAdmin backupAdmin = new BackupAdminImpl(connection)) {
BackupInfo backupInfo = backupAdmin.getBackupInfo(backupId);

// Verify managed backup in HBase
assertEquals(backupId, backupInfo.getBackupId());
assertEquals(expectedState, backupInfo.getState());
assertEquals(expectedType, backupInfo.getType());
return backupInfo;
}
}

private static void enableBackup(Configuration conf) {
// Enable backup
conf.setBoolean(BackupRestoreConstants.BACKUP_ENABLE_KEY, true);
BackupManager.decorateMasterConfiguration(conf);
BackupManager.decorateRegionServerConfiguration(conf);
}

}

0 comments on commit e1a5222

Please sign in to comment.