Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: unify internal api for backup/PITR restore task (#2258)
Yilong Li00c8787da5af
diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex c58faa7df3..4f37c71f16 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -12,7 +12,6 @@ import ("github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common""github.com/bytebase/bytebase/common/log"- "github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/mysql""github.com/bytebase/bytebase/store""go.uber.org/zap"@@ -43,109 +42,17 @@ func (exec *PITRRestoreTaskExecutor) RunOnce(ctx context.Context, server *Serverreturn true, nil, fmt.Errorf("only one of BackupID and time point can be set")}- if payload.BackupID != nil {- // TODO(dragonly): backup restore/PITR to new db do not require a cutover task.- // The current implementation here is actually not working, because it restores the backup directly to the target database, and the later cutover task will fail.- if payload.DatabaseName == nil {- return true, nil, fmt.Errorf("unexpected nil database name for backup restore")- }- // Restore full backup only- backup, err := server.store.GetBackupByID(ctx, *payload.BackupID)- if err != nil {- return true, nil, fmt.Errorf("failed to find backup with ID %d, error: %w", *payload.BackupID, err)- }- if backup == nil {- return true, nil, fmt.Errorf("backup with ID %d not found", *payload.BackupID)- }- sourceDatabase, err := server.store.GetDatabase(ctx, &api.DatabaseFind{ID: &backup.DatabaseID})- if err != nil {- return true, nil, fmt.Errorf("failed to find database for the backup: %w", err)- }- if sourceDatabase == nil {- return true, nil, fmt.Errorf("source database ID not found %v", backup.DatabaseID)- }-- targetInstanceID := task.InstanceID- if payload.TargetInstanceID != nil {- // For now, we just support restore full backup to the same instance with the origin database.- // But for generality, we will use TargetInstanceID in payload to find the target instance.- targetInstanceID = *payload.TargetInstanceID- }-- targetDatabaseFind := &api.DatabaseFind{- InstanceID: &targetInstanceID,- Name: payload.DatabaseName,- }+ // There are 2 * 2 = 4 kinds of task by combination of the following cases:+ // 1. in-place or restore to new database: the latter does not create database with _pitr/_del suffix+ // 2. backup restore or Point-in-Time restore: the former does not apply binlog/wal- targetDatabase, err := server.store.GetDatabase(ctx, targetDatabaseFind)- if err != nil {- return true, nil, fmt.Errorf("failed to find target database %q in instance %q: %w", *payload.DatabaseName, task.Instance.Name, err)- }- if targetDatabase == nil {- return true, nil, fmt.Errorf("target database %q not found in instance %q: %w", *payload.DatabaseName, task.Instance.Name, err)- }- log.Debug("Start database restore from backup...",- zap.String("source_instance", sourceDatabase.Instance.Name),- zap.String("source_database", sourceDatabase.Name),- zap.String("target_instance", targetDatabase.Instance.Name),- zap.String("target_database", targetDatabase.Name),- zap.String("backup", backup.Name),- )- // Restore the database to the target database.- if err := exec.restoreDatabase(ctx, server, targetDatabase.Instance, targetDatabase.Name, backup, server.profile.DataDir); err != nil {- return true, nil, err- }- // TODO(zp): This should be done in the same transaction as restoreDatabase to guarantee consistency.- // For now, we do this after restoreDatabase, since this one is unlikely to fail.- migrationID, version, err := createBranchMigrationHistory(ctx, server, sourceDatabase, targetDatabase, backup, task)- if err != nil {- return true, nil, err- }-- // Patch the backup id after we successfully restore the database using the backup.- // restoringDatabase is changing the customer database instance, while here we are changing our own meta db,- // and since we can't guarantee cross database transaction consistency, there is always a chance to have- // inconsistent data. We choose to do Patch afterwards since this one is unlikely to fail.- databasePatch := &api.DatabasePatch{- ID: targetDatabase.ID,- UpdaterID: api.SystemBotID,- SourceBackupID: &backup.ID,- }- if _, err = server.store.PatchDatabase(ctx, databasePatch); err != nil {- return true, nil, fmt.Errorf("failed to patch database source with ID %d and backup ID %d after restore, error: %w", targetDatabase.ID, backup.ID, err)- }-- // Sync database schema after restore is completed.- if err := server.syncDatabaseSchema(ctx, targetDatabase.Instance, targetDatabase.Name); err != nil {- log.Error("failed to sync database schema",- zap.String("instance", targetDatabase.Instance.Name),- zap.String("databaseName", targetDatabase.Name),- )- }-- return true, &api.TaskRunResultPayload{- Detail: fmt.Sprintf("Restored database %q from backup %q", targetDatabase.Name, backup.Name),- MigrationID: migrationID,- Version: version,- }, nil- }-- driver, err := server.getAdminDatabaseDriver(ctx, task.Instance, "")- if err != nil {- return true, nil, err- }- defer driver.Close(ctx)-- if err := exec.doPITRRestore(ctx, task, server.store, driver, server.profile.DataDir, *payload.PointInTimeTs, server.profile.Mode); err != nil {- log.Error("Failed to do PITR restore", zap.Error(err))- return true, nil, err+ if payload.BackupID != nil {+ resultPayload, err := exec.doBackupRestore(ctx, server, task, payload)+ return true, resultPayload, err}- log.Info("created PITR database", zap.String("target database", task.Database.Name))-- return true, &api.TaskRunResultPayload{- Detail: fmt.Sprintf("Created PITR database for target database %q", task.Database.Name),- }, nil+ resultPayload, err := exec.doPITRRestore(ctx, server, task, payload)+ return true, resultPayload, err}// IsCompleted tells the scheduler if the task execution has completed.@@ -162,45 +69,139 @@ func (exec *PITRRestoreTaskExecutor) GetProgress() api.Progress {return progress.(api.Progress)}-func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Task, store *store.Store, driver db.Driver, dataDir string, targetTs int64, mode common.ReleaseMode) error {- issue, err := getIssueByPipelineID(ctx, store, task.PipelineID)+func (exec *PITRRestoreTaskExecutor) doBackupRestore(ctx context.Context, server *Server, task *api.Task, payload api.TaskDatabasePITRRestorePayload) (*api.TaskRunResultPayload, error) {+ // TODO(dragonly): backup restore/PITR to new db do not require a cutover task.+ // The current implementation here is actually not working, because it restores the backup directly to the target database, and the later cutover task will fail.+ if payload.DatabaseName == nil {+ return nil, fmt.Errorf("unexpected nil database name for backup restore")+ }+ // Restore full backup only+ backup, err := server.store.GetBackupByID(ctx, *payload.BackupID)if err != nil {- return err+ return nil, fmt.Errorf("failed to find backup with ID %d, error: %w", *payload.BackupID, err)+ }+ if backup == nil {+ return nil, fmt.Errorf("backup with ID %d not found", *payload.BackupID)+ }+ // TODO(dragonly): We should let users restore the backup even if the source database is gone.+ sourceDatabase, err := server.store.GetDatabase(ctx, &api.DatabaseFind{ID: &backup.DatabaseID})+ if err != nil {+ return nil, fmt.Errorf("failed to find database for the backup: %w", err)+ }+ if sourceDatabase == nil {+ return nil, fmt.Errorf("source database ID not found %v", backup.DatabaseID)+ }++ targetInstanceID := task.InstanceID+ if payload.TargetInstanceID != nil {+ // For now, we just support restore full backup to the same instance with the origin database.+ // But for generality, we will use TargetInstanceID in payload to find the target instance.+ targetInstanceID = *payload.TargetInstanceID+ }++ targetDatabaseFind := &api.DatabaseFind{+ InstanceID: &targetInstanceID,+ Name: payload.DatabaseName,+ }++ targetDatabase, err := server.store.GetDatabase(ctx, targetDatabaseFind)+ if err != nil {+ return nil, fmt.Errorf("failed to find target database %q in instance %q: %w", *payload.DatabaseName, task.Instance.Name, err)+ }+ if targetDatabase == nil {+ return nil, fmt.Errorf("target database %q not found in instance %q: %w", *payload.DatabaseName, task.Instance.Name, err)+ }+ log.Debug("Start database restore from backup...",+ zap.String("source_instance", sourceDatabase.Instance.Name),+ zap.String("source_database", sourceDatabase.Name),+ zap.String("target_instance", targetDatabase.Instance.Name),+ zap.String("target_database", targetDatabase.Name),+ zap.String("backup", backup.Name),+ )+ // Restore the database to the target database.+ if err := exec.restoreDatabase(ctx, server, targetDatabase.Instance, targetDatabase.Name, backup, server.profile.DataDir); err != nil {+ return nil, err+ }+ // TODO(zp): This should be done in the same transaction as restoreDatabase to guarantee consistency.+ // For now, we do this after restoreDatabase, since this one is unlikely to fail.+ migrationID, version, err := createBranchMigrationHistory(ctx, server, sourceDatabase, targetDatabase, backup, task)+ if err != nil {+ return nil, err+ }++ // Patch the backup id after we successfully restore the database using the backup.+ // restoringDatabase is changing the customer database instance, while here we are changing our own meta db,+ // and since we can't guarantee cross database transaction consistency, there is always a chance to have+ // inconsistent data. We choose to do Patch afterwards since this one is unlikely to fail.+ databasePatch := &api.DatabasePatch{+ ID: targetDatabase.ID,+ UpdaterID: api.SystemBotID,+ SourceBackupID: &backup.ID,+ }+ if _, err = server.store.PatchDatabase(ctx, databasePatch); err != nil {+ return nil, fmt.Errorf("failed to patch database source with ID %d and backup ID %d after restore, error: %w", targetDatabase.ID, backup.ID, err)+ }++ // Sync database schema after restore is completed.+ if err := server.syncDatabaseSchema(ctx, targetDatabase.Instance, targetDatabase.Name); err != nil {+ log.Error("failed to sync database schema",+ zap.String("instance", targetDatabase.Instance.Name),+ zap.String("databaseName", targetDatabase.Name),+ )+ }++ return &api.TaskRunResultPayload{+ Detail: fmt.Sprintf("Restored database %q from backup %q", targetDatabase.Name, backup.Name),+ MigrationID: migrationID,+ Version: version,+ }, nil+}++func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *Server, task *api.Task, payload api.TaskDatabasePITRRestorePayload) (*api.TaskRunResultPayload, error) {+ driver, err := server.getAdminDatabaseDriver(ctx, task.Instance, "")+ if err != nil {+ return nil, err+ }+ defer driver.Close(ctx)+ issue, err := getIssueByPipelineID(ctx, server.store, task.PipelineID)+ if err != nil {+ return nil, err}backupStatus := api.BackupStatusDone- backupList, err := store.FindBackup(ctx, &api.BackupFind{DatabaseID: task.DatabaseID, Status: &backupStatus})+ backupList, err := server.store.FindBackup(ctx, &api.BackupFind{DatabaseID: task.DatabaseID, Status: &backupStatus})if err != nil {- return err+ return nil, err}log.Debug("Found backup list", zap.Array("backups", api.ZapBackupArray(backupList)))mysqlDriver, ok := driver.(*mysql.Driver)if !ok {log.Error("Failed to cast driver to mysql.Driver")- return fmt.Errorf("[internal] cast driver to mysql.Driver failed")+ return nil, fmt.Errorf("[internal] cast driver to mysql.Driver failed")}log.Debug("Downloading all binlog files")if err := mysqlDriver.FetchAllBinlogFiles(ctx, true /* downloadLatestBinlogFile */); err != nil {- return err+ return nil, err}+ targetTs := *payload.PointInTimeTslog.Debug("Getting latest backup before or equal to targetTs", zap.Int64("targetTs", targetTs))- backup, err := mysqlDriver.GetLatestBackupBeforeOrEqualTs(ctx, backupList, targetTs, mode)+ backup, err := mysqlDriver.GetLatestBackupBeforeOrEqualTs(ctx, backupList, targetTs, server.profile.Mode)if err != nil {targetTsHuman := time.Unix(targetTs, 0).Format(time.RFC822)log.Error("Failed to get backup before or equal to time",zap.Int64("targetTs", targetTs),zap.String("targetTsHuman", targetTsHuman),zap.Error(err))- return fmt.Errorf("failed to get latest backup before or equal to %s, error: %w", targetTsHuman, err)+ return nil, fmt.Errorf("failed to get latest backup before or equal to %s, error: %w", targetTsHuman, err)}log.Debug("Got latest backup before or equal to targetTs", zap.String("backup", backup.Name))- backupFileName := getBackupAbsFilePath(dataDir, backup.DatabaseID, backup.Name)+ backupFileName := getBackupAbsFilePath(server.profile.DataDir, backup.DatabaseID, backup.Name)backupFile, err := os.Open(backupFileName)if err != nil {- return fmt.Errorf("failed to open backup file %q, error: %w", backupFileName, err)+ return nil, fmt.Errorf("failed to open backup file %q, error: %w", backupFileName, err)}defer backupFile.Close()log.Debug("Successfully opened backup file", zap.String("filename", backupFileName))@@ -214,9 +215,9 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *ap// database's migration history, and append a new BRANCH migration.startBinlogInfo := backup.Payload.BinlogInfo- binlogDir := getBinlogAbsDir(dataDir, task.Instance.ID)+ binlogDir := getBinlogAbsDir(server.profile.DataDir, task.Instance.ID)if err := exec.updateProgress(ctx, mysqlDriver, backupFile, startBinlogInfo, binlogDir); err != nil {- return fmt.Errorf("failed to setup progress update process, error: %w", err)+ return nil, fmt.Errorf("failed to setup progress update process, error: %w", err)}if err := mysqlDriver.RestoreBackupToPITRDatabase(ctx, backupFile, task.Database.Name, issue.CreatedTs); err != nil {@@ -224,7 +225,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apzap.Int("issueID", issue.ID),zap.String("databaseName", task.Database.Name),zap.Error(err))- return fmt.Errorf("failed to perform a backup restore in the PITR database, error: %w", err)+ return nil, fmt.Errorf("failed to perform a backup restore in the PITR database, error: %w", err)}if err := mysqlDriver.ReplayBinlogToPITRDatabase(ctx, task.Database.Name, startBinlogInfo, issue.CreatedTs, targetTs); err != nil {@@ -232,10 +233,17 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apzap.Int("issueID", issue.ID),zap.String("databaseName", task.Database.Name),zap.Error(err))- return fmt.Errorf("failed to replay binlog in the PITR database, error: %w", err)+ return nil, fmt.Errorf("failed to replay binlog in the PITR database, error: %w", err)}- return nil+ targetDatabaseName := task.Database.Name+ if payload.DatabaseName != nil {+ targetDatabaseName = *payload.DatabaseName+ }+ log.Info("PITR restore success", zap.String("target database", targetDatabaseName))+ return &api.TaskRunResultPayload{+ Detail: fmt.Sprintf("PITR restore success for target database %q", targetDatabaseName),+ }, nil}func (exec *PITRRestoreTaskExecutor) updateProgress(ctx context.Context, driver *mysql.Driver, backupFile *os.File, startBinlogInfo api.BinlogInfo, binlogDir string) error {