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(pitr): split backup restore and replay binlog methods for in-place PITR (#2242)
Yilong Lidbd8dd08146e
diff --git a/plugin/db/mysql/dump.go b/plugin/db/mysql/dump.goindex 907c0c066b..d6e9b62a1f 100644--- a/plugin/db/mysql/dump.go+++ b/plugin/db/mysql/dump.go@@ -662,12 +662,11 @@ func getTriggerStmt(txn *sql.Tx, dbName, triggerName string) (string, error) {}// Restore restores a database.-func (driver *Driver) Restore(ctx context.Context, sc io.Reader) (err error) {- databaseName, err := driver.databaseName(ctx)- if err != nil {- return fmt.Errorf("cannot get the database name, error: %w", err)- }+func (driver *Driver) Restore(ctx context.Context, backup io.Reader) error {+ return driver.restoreImpl(ctx, backup, driver.connCfg.Database)+}+func (driver *Driver) restoreImpl(ctx context.Context, backup io.Reader, databaseName string) error {mysqlArgs := []string{"--host", driver.connCfg.Host,"--user", driver.connCfg.Username,@@ -682,7 +681,7 @@ func (driver *Driver) Restore(ctx context.Context, sc io.Reader) (err error) {mysqlCmd := exec.CommandContext(ctx, mysqlutil.GetPath(mysqlutil.MySQL, driver.resourceDir), mysqlArgs...)var stderr bytes.Buffer- mysqlCmd.Stdin = sc+ mysqlCmd.Stdin = backupmysqlCmd.Stderr = &stderrif err := mysqlCmd.Run(); err != nil {@@ -691,15 +690,3 @@ func (driver *Driver) Restore(ctx context.Context, sc io.Reader) (err error) {return nil}--func (driver *Driver) databaseName(ctx context.Context) (string, error) {- query := `SELECT DATABASE();`- var database string- if err := driver.db.QueryRowContext(ctx, query).Scan(&database); err != nil {- if err == sql.ErrNoRows {- return "", common.FormatDBErrorEmptyRowWithQuery(query)- }- return "", util.FormatErrorWithQuery(err, query)- }- return database, nil-}diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.goindex 8dca1e40f1..ac92d9ebc7 100644--- a/plugin/db/mysql/restore.go+++ b/plugin/db/mysql/restore.go@@ -95,7 +95,7 @@ func newBinlogCoordinate(binlogFileName string, pos int64) (binlogCoordinate, er}// ReplayBinlog replays the binlog for `originDatabase` from `startBinlogInfo.Position` to `targetTs`.-func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, pitrDatabase string, startBinlogInfo api.BinlogInfo, targetTs int64) error {+func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, targetDatabase string, startBinlogInfo api.BinlogInfo, targetTs int64) error {replayBinlogPaths, err := GetBinlogReplayList(startBinlogInfo, driver.binlogDir)if err != nil {return err@@ -131,9 +131,9 @@ func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, pitrDa// Disable binary logging."--disable-log-bin",// Create rewrite rules for databases when playing back from logs written in row-based format, so that we can apply the binlog to PITR database instead of the original database.- "--rewrite-db", fmt.Sprintf("%s->%s", originalDBName, pitrDatabase),+ "--rewrite-db", fmt.Sprintf("%s->%s", originalDBName, targetDatabase),// List entries for just this database. It's applied after the --rewrite-db option, so we should provide the rewritten database, i.e., pitrDatabase.- "--database", pitrDatabase,+ "--database", targetDatabase,// Start decoding the binary log at the log position, this option applies to the first log file named on the command line."--start-position", fmt.Sprintf("%d", startBinlogInfo.Position),// Stop reading the binary log at the first event having a timestamp equal to or later than the datetime argument.@@ -197,36 +197,27 @@ func (driver *Driver) GetReplayedBinlogBytes() int64 {return driver.replayBinlogCounter.Count()}-// RestorePITR is a wrapper to perform PITR. It restores a full backup followed by replaying the binlog.-// It performs the step 1 of the restore process.-// TODO(dragonly): Refactor so that the first part is in driver.Restore, and remove this wrapper.-func (driver *Driver) RestorePITR(ctx context.Context, fullBackup io.Reader, startBinlogInfo api.BinlogInfo, database string, suffixTs, targetTs int64) error {- pitrDatabaseName := getPITRDatabaseName(database, suffixTs)- stmt := fmt.Sprintf(""+- // Create the pitr database.- "CREATE DATABASE `%s`;"+- // Change to the pitr database.- "USE `%s`;",- pitrDatabaseName, pitrDatabaseName)+// ReplayBinlogToPITRDatabase replays binlog to the PITR database.+// It's the second step of the PITR process.+func (driver *Driver) ReplayBinlogToPITRDatabase(ctx context.Context, databaseName string, startBinlogInfo api.BinlogInfo, suffixTs, targetTs int64) error {+ pitrDatabaseName := getPITRDatabaseName(databaseName, suffixTs)+ return driver.replayBinlog(ctx, databaseName, pitrDatabaseName, startBinlogInfo, targetTs)+}+// RestoreBackupToPITRDatabase restores a full backup to the PITR database.+// It's the first step of the PITR process.+func (driver *Driver) RestoreBackupToPITRDatabase(ctx context.Context, backup io.Reader, databaseName string, suffixTs int64) error {+ pitrDatabaseName := getPITRDatabaseName(databaseName, suffixTs)+ // Create the pitr database.+ stmt := fmt.Sprintf("CREATE DATABASE `%s`;", pitrDatabaseName)db, err := driver.GetDBConnection(ctx, "")if err != nil {return err}-if _, err := db.ExecContext(ctx, stmt); err != nil {return err}-- if err := driver.Restore(ctx, fullBackup); err != nil {- return err- }-- if err := driver.replayBinlog(ctx, database, pitrDatabaseName, startBinlogInfo, targetTs); err != nil {- return fmt.Errorf("failed to replay binlog, error: %w", err)- }-- return nil+ return driver.restoreImpl(ctx, backup, pitrDatabaseName)}// GetBinlogReplayList returns the path list of the binlog that need be replayed.diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.goindex ac9f830bf3..9fea3c3143 100644--- a/server/task_executor_pitr_cutover.go+++ b/server/task_executor_pitr_cutover.go@@ -124,7 +124,7 @@ func (*PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.Task,Database: task.Database.Name,Environment: task.Database.Instance.Environment.Name,Source: db.MigrationSource(task.Database.Project.WorkflowType),- Type: db.Baseline,+ Type: db.Branch,Status: db.Done,Description: fmt.Sprintf("PITR: restoring database %s", task.Database.Name),Creator: task.Creator.Name,diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex 8f7a26ca62..79e53179e2 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -44,6 +44,8 @@ func (exec *PITRRestoreTaskExecutor) RunOnce(ctx context.Context, server *Server}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")}@@ -209,7 +211,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *ap)// RestorePITR will create the pitr database.// Since it's ephemeral and will be renamed to the original database soon, we will reuse the original- // database's migration history, and append a new BASELINE migration.+ // database's migration history, and append a new BRANCH migration.startBinlogInfo := backup.Payload.BinlogInfobinlogDir := getBinlogAbsDir(dataDir, task.Instance.ID)@@ -217,12 +219,20 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apreturn fmt.Errorf("failed to setup progress update process, error: %w", err)}- if err := mysqlDriver.RestorePITR(ctx, backupFile, startBinlogInfo, task.Database.Name, issue.CreatedTs, targetTs); err != nil {+ if err := mysqlDriver.RestoreBackupToPITRDatabase(ctx, backupFile, task.Database.Name, issue.CreatedTs); err != nil {+ log.Error("failed to restore full backup in the PITR database",+ zap.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)+ }++ if err := mysqlDriver.ReplayBinlogToPITRDatabase(ctx, task.Database.Name, startBinlogInfo, issue.CreatedTs, targetTs); err != nil {log.Error("failed to perform a PITR restore in the PITR database",zap.Int("issueID", issue.ID),- zap.String("database", task.Database.Name),+ zap.String("databaseName", task.Database.Name),zap.Error(err))- return fmt.Errorf("failed to perform a PITR restore in the PITR database, error: %w", err)+ return fmt.Errorf("failed to replay binlog in the PITR database, error: %w", err)}return nil