Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(PITR): Fix main logical path of PITR restore (#1457)
Yilong Li6b9dcbc98321
diff --git a/api/issue.go b/api/issue.goindex 6a836269fe..d0f4c24e98 100644--- a/api/issue.go+++ b/api/issue.go@@ -187,7 +187,7 @@ type PITRContext struct {DatabaseID int `json:"databaseId"`// After the PITR operations, the database will be recovered to the state at this time.// Represented in UNIX timestamp in seconds.- PointInTimeTs int `json:"pointInTimeTs"`+ PointInTimeTs int64 `json:"pointInTimeTs"`}// IssueFind is the API message for finding issues.diff --git a/api/task.go b/api/task.goindex f733b0e5ea..06d360d184 100644--- a/api/task.go+++ b/api/task.go@@ -90,7 +90,7 @@ type TaskDatabasePITRRestorePayload struct {ProjectID int `json:"projectId,omitempty"`// After the PITR operations, the database will be recovered to the state at this time.// Represented in UNIX timestamp in seconds.- PointInTimeTs int `json:"pointInTimeTs,omitempty"`+ PointInTimeTs int64 `json:"pointInTimeTs,omitempty"`}// TaskDatabasePITRCutoverPayload is the task payload for PITR cutover.diff --git a/plugin/restore/mysql/mysql.go b/plugin/restore/mysql/mysql.goindex f7d13ab63f..a498702039 100644--- a/plugin/restore/mysql/mysql.go+++ b/plugin/restore/mysql/mysql.go@@ -61,41 +61,43 @@ func New(driver *mysql.Driver, instance *mysqlutil.Instance, connCfg db.Connecti// ReplayBinlog replays the binlog for `originDatabase` from `startBinlogInfo.Position` to `targetTs`.func (r *Restore) replayBinlog(ctx context.Context, originalDatabase, pitrDatabase string, startBinlogInfo api.BinlogInfo, targetTs int64) error {- if err := r.incrementalFetchAllBinlogFiles(ctx); err != nil {- return err- }-replayBinlogPaths, err := getBinlogReplayList(startBinlogInfo, r.binlogDir)if err != nil {return err}- stopDateTime := getDateTime(targetTs)// Extract the SQL statements from the binlog and replay them to the pitrDatabase via the mysql client by pipe.mysqlbinlogArgs := []string{// 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.- fmt.Sprintf(`--rewrite-db=%s->%s`, originalDatabase, pitrDatabase),+ "--rewrite-db", fmt.Sprintf("%s->%s", originalDatabase, pitrDatabase),// List entries for just this database. It's applied after the --rewrite-db option, so we should provide the rewritten database, i.e., pitrDatabase.- fmt.Sprintf("--database=%s", pitrDatabase),+ "--database", pitrDatabase,// Start decoding the binary log at the log position, this option applies to the first log file named on the command line.- fmt.Sprintf("--start-position=%d", startBinlogInfo.Position),+ "--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.- fmt.Sprintf(`--stop-datetime=%s`, stopDateTime),+ "--stop-datetime", getDateTime(targetTs),}mysqlbinlogArgs = append(mysqlbinlogArgs, replayBinlogPaths...)mysqlArgs := []string{- fmt.Sprintf("--host=%s", r.connCfg.Host),- fmt.Sprintf("--port=%s", r.connCfg.Port),- fmt.Sprintf("--user=%s", r.connCfg.Username),- fmt.Sprintf("--password=%s", r.connCfg.Password),+ "--host", r.connCfg.Host,+ "--user", r.connCfg.Username,+ }+ if r.connCfg.Port != "" {+ mysqlArgs = append(mysqlArgs, "--port", r.connCfg.Port)+ }+ if r.connCfg.Password != "" {+ mysqlArgs = append(mysqlArgs, "--password", r.connCfg.Password)}mysqlbinlogCmd := exec.CommandContext(ctx, r.mysqlutil.GetPath(mysqlutil.MySQLBinlog), mysqlbinlogArgs...)mysqlCmd := exec.CommandContext(ctx, r.mysqlutil.GetPath(mysqlutil.MySQL), mysqlArgs...)+ log.Debug("Start replay binlog commands",+ zap.String("mysqlbinlog", mysqlbinlogCmd.String()),+ zap.String("mysql", mysqlCmd.String()))mysqlRead, err := mysqlbinlogCmd.StdoutPipe()if err != nil {@@ -110,10 +112,10 @@ func (r *Restore) replayBinlog(ctx context.Context, originalDatabase, pitrDatabamysqlCmd.Stdin = mysqlReadif err := mysqlbinlogCmd.Start(); err != nil {- return fmt.Errorf("cannot start mysqlbinlog command %s, error: %w", mysqlbinlogCmd.String(), err)+ return fmt.Errorf("cannot start mysqlbinlog command, error [%w]", err)}if err := mysqlCmd.Run(); err != nil {- return fmt.Errorf("mysql command %s fails, error: %w", mysqlCmd.String(), err)+ return fmt.Errorf("mysql command fails, error [%w]", err)}if err := mysqlbinlogCmd.Wait(); err != nil {return fmt.Errorf("error occurred while waiting for mysqlbinlog to exit: %w", err)@@ -124,7 +126,7 @@ func (r *Restore) replayBinlog(ctx context.Context, originalDatabase, pitrDataba// 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 (r *Restore) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner, binlog api.BinlogInfo, database string, suffixTs int64) error {+func (r *Restore) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner, startBinlogInfo api.BinlogInfo, database string, suffixTs, targetTs int64) error {pitrDatabaseName := getPITRDatabaseName(database, suffixTs)query := fmt.Sprintf(""+// Create the pitr database.@@ -154,7 +156,7 @@ func (r *Restore) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner, bireturn err}- if err := r.replayBinlog(ctx, database, pitrDatabaseName, binlog, suffixTs); err != nil {+ if err := r.replayBinlog(ctx, database, pitrDatabaseName, startBinlogInfo, targetTs); err != nil {return fmt.Errorf("failed to replay binlog, error[%w]", err)}@@ -197,7 +199,7 @@ func getBinlogReplayList(startBinlogInfo api.BinlogInfo, binlogDir string) ([]stfor i := 1; i < len(toBeReplayedBinlogItems); i++ {if toBeReplayedBinlogItems[i].seq != toBeReplayedBinlogItems[i-1].seq+1 {- return nil, fmt.Errorf("Discontinuous binlog file extensions detected in %s and %s", toBeReplayedBinlogItems[i-1].name, toBeReplayedBinlogItems[i].name)+ return nil, fmt.Errorf("discontinuous binlog file extensions detected in %s and %s", toBeReplayedBinlogItems[i-1].name, toBeReplayedBinlogItems[i].name)}}@@ -235,11 +237,11 @@ func parseAndSortBinlogFileNames(binlogFileNames []string) ([]binlogItem, error)func (r *Restore) parseBinlogEventTimestamp(ctx context.Context, binlogInfo api.BinlogInfo) (int64, error) {args := []string{path.Join(r.binlogDir, binlogInfo.FileName),- fmt.Sprintf("--start-position %d", binlogInfo.Position),+ "--start-position", fmt.Sprintf("%d", binlogInfo.Position),// This will trick mysqlbinlog to output the binlog event header followed by a warning message telling that// the --stop-position is in the middle of the binlog event.// It's OK, since we are only parsing for the timestamp in the binlog event header.- fmt.Sprintf("--stop-position %d", binlogInfo.Position+1),+ "--stop-position", fmt.Sprintf("%d", binlogInfo.Position+1),}var buf bytes.Buffercmd := exec.CommandContext(ctx, r.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)@@ -247,7 +249,8 @@ func (r *Restore) parseBinlogEventTimestamp(ctx context.Context, binlogInfo api.cmd.Stdout = &bufif err := cmd.Run(); err != nil {- return 0, err+ log.Error("Command mysqlbinlog fails", zap.String("cmd", cmd.String()), zap.Error(err))+ return 0, fmt.Errorf("command %s fails: %w", cmd.Path, err)}timestamp, err := parseBinlogEventTimestampImpl(buf.String())@@ -281,11 +284,9 @@ func parseBinlogEventTimestampImpl(output string) (int64, error) {return 0, fmt.Errorf("no timestamp found in mysqlbinlog output")}-// Find the latest logical backup and corresponding binlog info whose time is before or equal to `targetTs`.+// GetLatestBackupBeforeOrEqualTs finds the latest logical backup and corresponding binlog info whose time is before or equal to `targetTs`.// The backupList should only contain DONE backups.-// TODO(dragonly)/TODO(zp): Use this when the apply binlog PR is ready, and remove the nolint comments.-// nolint-func (r *Restore) getLatestBackupBeforeOrEqualTs(ctx context.Context, backupList []*api.Backup, targetTs int64) (*api.Backup, error) {+func (r *Restore) GetLatestBackupBeforeOrEqualTs(ctx context.Context, backupList []*api.Backup, targetTs int64) (*api.Backup, error) {if len(backupList) == 0 {return nil, fmt.Errorf("no valid backup")}@@ -347,11 +348,13 @@ func (r *Restore) SwapPITRDatabase(ctx context.Context, database string, suffixT}// Handle the case that the original database does not exist, because user could drop a database and want to restore it.+ log.Debug("Check database exists", zap.String("database", database))dbExists, err := r.databaseExists(ctx, database)if err != nil {return pitrDatabaseName, pitrOldDatabase, fmt.Errorf("failed to check whether database %q exists, error[%w]", database, err)}if !dbExists {+ log.Debug("Database does not exist, creating...", zap.String("database", database))if _, err := db.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", database)); err != nil {return pitrDatabaseName, pitrOldDatabase, fmt.Errorf("failed to create non-exist database %q, error[%w]", database, err)}@@ -366,6 +369,13 @@ func (r *Restore) SwapPITRDatabase(ctx context.Context, database string, suffixTreturn pitrDatabaseName, pitrOldDatabase, fmt.Errorf("failed to get tables of database %q, error[%w]", pitrDatabaseName, err)}+ if len(tables) == 0 && len(tablesPITR) == 0 {+ log.Warn("Both databases are empty, skip renaming tables",+ zap.String("originalDatabase", database),+ zap.String("pitrDatabase", pitrDatabaseName))+ return pitrDatabaseName, pitrOldDatabase, nil+ }+if _, err := db.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", pitrOldDatabase)); err != nil {return pitrDatabaseName, pitrOldDatabase, err}@@ -378,6 +388,7 @@ func (r *Restore) SwapPITRDatabase(ctx context.Context, database string, suffixTtableRenames = append(tableRenames, fmt.Sprintf("`%s`.`%s` TO `%s`.`%s`", pitrDatabaseName, table.Name, database, table.Name))}renameStmt := fmt.Sprintf("RENAME TABLE %s;", strings.Join(tableRenames, ", "))+ log.Debug("generated RENAME TABLE statement", zap.String("stmt", renameStmt))if _, err := db.ExecContext(ctx, renameStmt); err != nil {return pitrDatabaseName, pitrOldDatabase, err@@ -470,7 +481,7 @@ func (r *Restore) FetchArchivedBinlogFiles(ctx context.Context) error {if _, ok := todo[serverFile.Name]; !ok {continue}- if err := r.downloadBinlogFile(ctx, serverFile); err != nil {+ if err := r.downloadBinlogFile(ctx, serverFile, false); err != nil {return fmt.Errorf("cannot sync binlog %s, error: %w", serverFile.Name, err)}}@@ -478,10 +489,10 @@ func (r *Restore) FetchArchivedBinlogFiles(ctx context.Context) error {return nil}-// incrementalFetchAllBinlogFiles fetches all the binlogs that on server but not on local.-// TODO(zp): It is not yet supported to synchronize some binlogs.-// The current practice is to download all binlogs, but in the future we hope to only synchronize to the PITR time point-func (r *Restore) incrementalFetchAllBinlogFiles(ctx context.Context) error {+// IncrementalFetchAllBinlogFiles fetches all the binlog files that on server but not on local.+// TODO(zp): It is not yet supported to synchronize some binlog files.+// The current practice is to download all binlog files, but in the future we hope to only synchronize to the PITR time point+func (r *Restore) IncrementalFetchAllBinlogFiles(ctx context.Context) error {if err := r.FetchArchivedBinlogFiles(ctx); err != nil {return err}@@ -489,37 +500,72 @@ func (r *Restore) incrementalFetchAllBinlogFiles(ctx context.Context) error {if err != nil {return err}- return r.downloadBinlogFile(ctx, *latestBinlogFileOnServer)+ return r.downloadBinlogFile(ctx, latestBinlogFileOnServer, true)}// downloadBinlogFile syncs the binlog specified by `meta` between the instance and local.-func (r *Restore) downloadBinlogFile(ctx context.Context, binlog mysql.BinlogFile) error {+// If isLast is true, it means that this is the last binlog file containing the targetTs event.+// It may keep growing as there are ongoing writes to the database. So we just need to check that+// the file size is larger or equal to the binlog file size we queried from the MySQL server earlier.+func (r *Restore) downloadBinlogFile(ctx context.Context, binlog mysql.BinlogFile, isLast bool) error {// for mysqlbinlog binary, --result-file must end with '/'resultFileDir := strings.TrimRight(r.binlogDir, "/") + "/"// TODO(zp): support ssl?- cmd := exec.CommandContext(ctx, r.mysqlutil.GetPath(mysqlutil.MySQL),+ args := []string{binlog.Name,- fmt.Sprintf("--read-from-remote-server --host=%s --port=%s --user=%s --password=%s", r.connCfg.Host, r.connCfg.Port, r.connCfg.Username, r.connCfg.Password),+ "--read-from-remote-server","--raw",- fmt.Sprintf("--result-file=%s", resultFileDir),- )+ "--host", r.connCfg.Host,+ "--user", r.connCfg.Username,+ "--result-file", resultFileDir,+ }+ if r.connCfg.Port != "" {+ args = append(args, "--port", r.connCfg.Port)+ }+ if r.connCfg.Password != "" {+ args = append(args, "--password", r.connCfg.Password)+ }++ cmd := exec.CommandContext(ctx, r.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)cmd.Stdout = os.Stderrcmd.Stderr = os.Stderr+ log.Debug("Downloading binlog files using mysqlbinlog", zap.String("cmd", cmd.String()))resultFilePath := filepath.Join(resultFileDir, binlog.Name)if err := cmd.Run(); err != nil {_ = os.Remove(resultFilePath)- return fmt.Errorf("cannot run mysqlbinlog, error: %w", err)+ return fmt.Errorf("mysqlbinlog fails, error: %w", err)}- fi, err := os.Stat(resultFilePath)+ fileInfo, err := os.Stat(resultFilePath)if err != nil {_ = os.Remove(resultFilePath)return fmt.Errorf("cannot stat %s, error: %w", resultFilePath, err)}- if fi.Size() != binlog.Size {- _ = os.Remove(resultFilePath)- return fmt.Errorf("download file %s size not match", resultFilePath)+ if !isLast {+ // Case 1: It's an archived binlog file, and we must ensure the file size equals what we queried from the MySQL server earlier.+ if fileInfo.Size() != binlog.Size {+ log.Error("Downloaded binlog file size does not match size queried on the MySQL server",+ zap.String("binlog", binlog.Name),+ zap.Int64("sizeInfo", binlog.Size),+ zap.Int64("downloadedSize", fileInfo.Size()),+ )+ _ = os.Remove(resultFilePath)+ return fmt.Errorf("downloaded binlog file[%s] size[%d] does not equal to size[%d] queried on MySQL server earlier", resultFilePath, fileInfo.Size(), binlog.Size)+ }+ } else {+ // Case 2: It's the last binlog file we need (contains the targetTs).+ // If it's the last (incomplete) binlog file on the MySQL server, it will grow as new writes hit the database server.+ // We just need to check that the downloaded file size >= queried size, so it contains the targetTs event.+ if fileInfo.Size() < binlog.Size {+ log.Error("Downloaded latest binlog file size is smaller than size queried on the MySQL server",+ zap.String("binlog", binlog.Name),+ zap.Int64("sizeInfo", binlog.Size),+ zap.Int64("downloadedSize", fileInfo.Size()),+ )+ _ = os.Remove(resultFilePath)+ return fmt.Errorf("downloaded latest binlog file[%s] size[%d] is smaller than size[%d] queried on MySQL server earlier", resultFilePath, fileInfo.Size(), binlog.Size)+ }}return nil@@ -551,16 +597,16 @@ func (r *Restore) getBinlogFilesMetaOnServer(ctx context.Context) ([]mysql.Binlo}// showLatestBinlogFile returns the metadata of latest binlog-func (r *Restore) getLatestBinlogFileMeta(ctx context.Context) (*mysql.BinlogFile, error) {+func (r *Restore) getLatestBinlogFileMeta(ctx context.Context) (mysql.BinlogFile, error) {// TODO(zp): refactor to reuse getBinlogInfo() in plugin/db/mysql.godb, err := r.driver.GetDbConnection(ctx, "")if err != nil {- return nil, err+ return mysql.BinlogFile{}, err}rows, err := db.QueryContext(ctx, `SHOW MASTER STATUS;`)if err != nil {- return nil, err+ return mysql.BinlogFile{}, err}defer rows.Close()@@ -568,11 +614,11 @@ func (r *Restore) getLatestBinlogFileMeta(ctx context.Context) (*mysql.BinlogFilif rows.Next() {var unused interface{} /*Binlog_Do_DB, Binlog_Ignore_DB, Executed_Gtid_Set*/if err := rows.Scan(&binlogFile.Name, &binlogFile.Size, &unused, &unused, &unused); err != nil {- return nil, err+ return mysql.BinlogFile{}, err}- return &binlogFile, nil+ return binlogFile, nil}- return nil, fmt.Errorf("cannot find latest binlog on instance")+ return mysql.BinlogFile{}, fmt.Errorf("cannot find latest binlog on instance")}// getBinlogNameSeq returns the numeric extension to the binary log base name by using split the dot.@@ -580,7 +626,7 @@ func (r *Restore) getLatestBinlogFileMeta(ctx context.Context) (*mysql.BinlogFilfunc getBinlogNameSeq(name string) (int64, error) {s := strings.Split(name, ".")if len(s) != 2 {- return 0, fmt.Errorf("cannot parse the the binlog name sequence, expect 1 part after split by dot, but get: %d", len(s))+ return 0, fmt.Errorf("expecting two parts in the binlog file name, but get %d", len(s))}return strconv.ParseInt(s[1], 10, 0)}diff --git a/server/backup_runner.go b/server/backup_runner.goindex f4c86f1d9b..83b631d859 100644--- a/server/backup_runner.go+++ b/server/backup_runner.go@@ -116,8 +116,8 @@ func (s *BackupRunner) Run(ctx context.Context, wg *sync.WaitGroup) {}func (s *BackupRunner) scheduleBackupTask(ctx context.Context, database *api.Database, backupName string) error {- path, err := getAndCreateBackupPath(s.server.profile.DataDir, database, backupName)- if err != nil {+ path := getBackupRelativeFilePath(database.ID, backupName)+ if err := createBackupDirectory(s.server.profile.DataDir, database.ID); err != nil {return err}diff --git a/server/database.go b/server/database.goindex d5dcea7ba7..6a55442821 100644--- a/server/database.go+++ b/server/database.go@@ -507,10 +507,11 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database not found with ID %d", id))}- backupCreate.Path, err = getAndCreateBackupPath(s.profile.DataDir, database, backupCreate.Name)- if err != nil {- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create backup directory for database ID: %v", id)).SetInternal(err)+ if err := createBackupDirectory(s.profile.DataDir, database.ID); err != nil {+ return err}+ path := getBackupRelativeFilePath(database.ID, backupCreate.Name)+ backupCreate.Path = pathdriver, err := getAdminDatabaseDriver(ctx, database.Instance, database.Name, s.pgInstanceDir)if err != nil {diff --git a/server/issue.go b/server/issue.goindex 359479b276..e04e2ae65a 100644--- a/server/issue.go+++ b/server/issue.go@@ -901,13 +901,13 @@ func getUpdateTask(database *api.Database, migrationType db.MigrationType, vcsPu}// creates PITR TaskCreate list and dependency-func createPITRTaskList(database *api.Database, projectID int, taskStatus api.TaskStatus, recoveryTime int) ([]api.TaskCreate, []api.TaskIndexDAG, error) {+func createPITRTaskList(database *api.Database, projectID int, taskStatus api.TaskStatus, targetTs int64) ([]api.TaskCreate, []api.TaskIndexDAG, error) {var taskCreateList []api.TaskCreate// task: create and restore to PITR databasepayloadRestore := api.TaskDatabasePITRRestorePayload{ProjectID: projectID,- PointInTimeTs: recoveryTime,+ PointInTimeTs: targetTs,}bytesRestore, err := json.Marshal(payloadRestore)if err != nil {diff --git a/server/task_executor_database_backup.go b/server/task_executor_database_backup.goindex c1b0946494..1ab909ed74 100644--- a/server/task_executor_database_backup.go+++ b/server/task_executor_database_backup.go@@ -91,22 +91,39 @@ func (exec *DatabaseBackupTaskExecutor) backupDatabase(ctx context.Context, instreturn payload, nil}-// getAndCreateBackupDirectory returns the path of a database backup.-func getAndCreateBackupDirectory(dataDir string, database *api.Database) (string, error) {- dir := filepath.Join("backup", "db", fmt.Sprintf("%d", database.ID))+// Get backup dir relative to the data dir.+func getBackupRelativeDir(databaseID int) string {+ return filepath.Join("backup", "db", fmt.Sprintf("%d", databaseID))+}++func getBackupRelativeFilePath(databaseID int, name string) string {+ dir := getBackupRelativeDir(databaseID)+ return filepath.Join(dir, fmt.Sprintf("%s.sql", name))+}++func getBackupAbsFilePath(dataDir string, databaseID int, name string) string {+ path := getBackupRelativeFilePath(databaseID, name)+ return filepath.Join(dataDir, path)+}++// Create backup directory for database.+func createBackupDirectory(dataDir string, databaseID int) error {+ dir := getBackupRelativeDir(databaseID)absDir := filepath.Join(dataDir, dir)- if err := os.MkdirAll(absDir, os.ModePerm); err != nil {- return "", nil- }+ return os.MkdirAll(absDir, os.ModePerm)+}- return dir, nil+func getBinlogRelativeDir(instanceID int) string {+ return filepath.Join("backup", "instance", fmt.Sprintf("%d", instanceID))}-// getAndCreateBackupPath returns the path of a database backup.-func getAndCreateBackupPath(dataDir string, database *api.Database, name string) (string, error) {- dir, err := getAndCreateBackupDirectory(dataDir, database)- if err != nil {- return "", err- }- return filepath.Join(dir, fmt.Sprintf("%s.sql", name)), nil+func getBinlogAbsDir(dataDir string, instanceID int) string {+ dir := getBinlogRelativeDir(instanceID)+ return filepath.Join(dataDir, dir)+}++func createBinlogDir(dataDir string, instanceID int) error {+ dir := getBinlogRelativeDir(instanceID)+ absDir := filepath.Join(dataDir, dir)+ return os.MkdirAll(absDir, os.ModePerm)}diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.goindex ce1b47b582..69d7bacb5b 100644--- a/server/task_executor_pitr_cutover.go+++ b/server/task_executor_pitr_cutover.go@@ -53,8 +53,8 @@ func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.return true, nil, err}- binlogDir, err := getAndCreateBinlogDirectory(server.profile.DataDir, task.Instance)- if err != nil {+ binlogDir := getBinlogAbsDir(server.profile.DataDir, task.Instance.ID)+ if err := createBinlogDir(server.profile.DataDir, task.Instance.ID); err != nil {return true, nil, err}@@ -103,6 +103,9 @@ func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.return true, nil, fmt.Errorf("failed to add migration history record, error[%w]", err)}+ // Sync database schema after restore is completed.+ server.syncEngineVersionAndSchema(ctx, task.Database.Instance)+return true, &api.TaskRunResultPayload{Detail: fmt.Sprintf("Swapped PITR database for target database %q", task.Database.Name),}, nildiff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex 66fa2db6fa..b809626136 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -2,12 +2,11 @@ package serverimport ("bufio"- "bytes""context""encoding/json""fmt""os"- "path/filepath"+ "time""github.com/bytebase/bytebase/api""github.com/bytebase/bytebase/common/log"@@ -40,17 +39,14 @@ func (exec *PITRRestoreTaskExecutor) RunOnce(ctx context.Context, server *Serverreturn true, nil, fmt.Errorf("invalid PITR restore payload[%s], error[%w]", task.Payload, err)}- return exec.pitrRestore(ctx, task, server)-}--func (exec *PITRRestoreTaskExecutor) pitrRestore(ctx context.Context, task *api.Task, server *Server) (terminated bool, result *api.TaskRunResultPayload, err error) {driver, err := getAdminDatabaseDriver(ctx, task.Instance, "", "" /* pgInstanceDir */)if err != nil {return true, nil, err}defer driver.Close(ctx)- if err := exec.doPITRRestore(ctx, task, server.store, driver, server.profile.DataDir); err != nil {+ if err := exec.doPITRRestore(ctx, task, server.store, driver, server.profile.DataDir, payload.PointInTimeTs); err != nil {+ log.Error("Failed to do PITR restore", zap.Error(err))return true, nil, err}@@ -61,7 +57,7 @@ func (exec *PITRRestoreTaskExecutor) pitrRestore(ctx context.Context, task *api.}, nil}-func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Task, store *store.Store, driver db.Driver, dataDir string) error {+func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Task, store *store.Store, driver db.Driver, dataDir string, targetTs int64) error {instance := task.Instancedatabase := task.Database@@ -70,16 +66,21 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apreturn err}- connCfg, err := getConnectionConfig(ctx, instance, database.Name)+ backupList, err := store.FindBackup(ctx, &api.BackupFind{DatabaseID: task.DatabaseID})if err != nil {return err}- binlogDir, err := getAndCreateBinlogDirectory(dataDir, task.Instance)+ connCfg, err := getConnectionConfig(ctx, instance, database.Name)if err != nil {return err}+ binlogDir := getBinlogAbsDir(dataDir, task.Instance.ID)+ if err := createBinlogDir(dataDir, task.Instance.ID); err != nil {+ return err+ }+mysqlDriver, ok := driver.(*pluginmysql.Driver)if !ok {log.Error("failed to cast driver to mysql.Driver")@@ -88,21 +89,37 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apmysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlutil, connCfg, binlogDir)- binlogInfo := api.BinlogInfo{}- // TODO(dragonly): Search and put the file io of the logical backup file here.- // Currently, let's just use the empty backup dump as a placeholder.- var buf bytes.Buffer- buf.WriteString("-- This is a fake backup dump")+ log.Debug("Download all binlog files up to targetTs", zap.Time("targetTs", time.Unix(targetTs, 0)))+ // TODO(dragonly): Do this on a regular basis.+ if err := mysqlRestore.IncrementalFetchAllBinlogFiles(ctx); err != nil {+ return err+ }++ log.Debug("Get latest backup before or equal to targetTs", zap.Time("targetTs", time.Unix(targetTs, 0)))+ backup, err := mysqlRestore.GetLatestBackupBeforeOrEqualTs(ctx, backupList, targetTs)+ if err != nil {+ log.Error("Failed to get backup before or equal to targetTs",+ zap.Time("targetTs", time.Unix(targetTs, 0)),+ zap.Error(err))+ return fmt.Errorf("failed to get latest backup before or equal to targetTs[%d], error[%w]", targetTs, err)+ }+ backupFileName := getBackupAbsFilePath(dataDir, backup.DatabaseID, backup.Name)+ backupFile, err := os.OpenFile(backupFileName, os.O_RDONLY, os.ModePerm)+ if err != nil {+ return fmt.Errorf("failed to open backup file[%s], error[%w]", backupFileName, err)+ }+ defer backupFile.Close()+ log.Debug("Successfully opened backup file", zap.String("filename", backupFileName))log.Debug("Start creating and restoring PITR database",zap.String("instance", instance.Name),zap.String("database", database.Name),)-// 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.- if err := mysqlRestore.RestorePITR(ctx, bufio.NewScanner(&buf), binlogInfo, database.Name, issue.CreatedTs); err != nil {+ startBinlogInfo := backup.Payload.BinlogInfo+ if err := mysqlRestore.RestorePITR(ctx, bufio.NewScanner(backupFile), startBinlogInfo, database.Name, 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", database.Name),@@ -113,17 +130,6 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apreturn nil}-// getAndCreateBinlogDirectory returns the path of a instance binlog directory.-func getAndCreateBinlogDirectory(dataDir string, instance *api.Instance) (string, error) {- dir := filepath.Join("backup", "instance", fmt.Sprintf("%d", instance.ID))- absDir := filepath.Join(dataDir, dir)- if err := os.MkdirAll(absDir, os.ModePerm); err != nil {- return "", nil- }-- return dir, nil-}-func getIssueByPipelineID(ctx context.Context, store *store.Store, pid int) (*api.Issue, error) {issue, err := store.GetIssueByPipelineID(ctx, pid)if err != nil {diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.goindex 282f5ac939..e5acfaa956 100644--- a/tests/backup_restore_test.go+++ b/tests/backup_restore_test.go@@ -8,17 +8,20 @@ import ("bytes""context""database/sql"+ "encoding/json""fmt""strconv""testing""time""github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common/log"dbplugin "github.com/bytebase/bytebase/plugin/db"pluginmysql "github.com/bytebase/bytebase/plugin/db/mysql"restoremysql "github.com/bytebase/bytebase/plugin/restore/mysql"resourcemysql "github.com/bytebase/bytebase/resources/mysql""github.com/bytebase/bytebase/resources/mysqlutil"+ "go.uber.org/zap/zapcore""github.com/stretchr/testify/require")@@ -73,7 +76,7 @@ func TestBackupRestoreBasic(t *testing.T) {a.NoError(err)defer driver.Close(ctx)- buf, err := doBackup(ctx, driver, database)+ buf, _, err := doBackup(ctx, driver, database)a.NoError(err)t.Logf("backup content:\n%s", buf.String())@@ -113,6 +116,7 @@ func TestBackupRestoreBasic(t *testing.T) {func TestPITR(t *testing.T) {t.Parallel()a := require.New(t)+ log.SetLevel(zapcore.DebugLevel)// common configsconst (@@ -147,45 +151,43 @@ func TestPITR(t *testing.T) {a.NoError(err)defer driver.Close(ctx)- connCfg := getMySQLConnectionConfig(strconv.Itoa(mysqlPort), database)-- buf, err := doBackup(ctx, driver, database)+ backupDump, backupPayload, err := doBackup(ctx, driver, database)a.NoError(err)- t.Logf("backup content:\n%s", buf.String())+ t.Logf("backup content:\n%s", backupDump.String())t.Log("insert more data")insertRangeData(t, db, numRowsTime0, numRowsTime1)ctxUpdateRow, cancelUpdateRow := context.WithCancel(ctx)- t1 := startUpdateRow(ctxUpdateRow, t, database, mysqlPort)- t.Logf("start to concurrently update data at t1: %v", t1)+ targetTs := startUpdateRow(ctxUpdateRow, t, database, mysqlPort) + 1+ t.Logf("start to concurrently update data at t1: %v", time.Unix(targetTs, 0))t.Log("restore to pitr database")- createPITRIssueTimestamp := time.Now().Unix()+ suffixTs := time.Now().Unix()mysqlDriver, ok := driver.(*pluginmysql.Driver)a.Equal(true, ok)binlogDir := t.TempDir()+ connCfg := getMySQLConnectionConfig(strconv.Itoa(mysqlPort), database)mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilInstance, connCfg, binlogDir)- binlogInfo := api.BinlogInfo{}- err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), binlogInfo, database, createPITRIssueTimestamp)- // TODO(zp): change to a.NoError(err) when binlogInfo is determined- a.Error(err)+ err = mysqlRestore.IncrementalFetchAllBinlogFiles(ctx)+ a.NoError(err)+ err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(backupDump), backupPayload.BinlogInfo, database, suffixTs, targetTs)+ a.NoError(err)t.Log("cutover stage")cancelUpdateRow()// We mimics the situation where the user waits for the target database idle before doing the cutover.time.Sleep(time.Second)- _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)+ _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, suffixTs)a.NoError(err)t.Log("validate table tbl0")- // TODO(dragonly): change to numRowsTime1 when RestoreIncremental is implemented- validateTbl0(t, db, numRowsTime0)+ validateTbl0(t, db, numRowsTime1)t.Log("validate table tbl1")- validateTbl1(t, db, numRowsTime0)- // TODO(dragonly): validate table _update_row_ when RestoreIncremental is implemented+ validateTbl1(t, db, numRowsTime1)t.Log("validate table _update_row_")+ validateTableUpdateRow(t, db)})t.Run("Drop Database", func(t *testing.T) {@@ -212,13 +214,16 @@ func TestPITR(t *testing.T) {connCfg := getMySQLConnectionConfig(strconv.Itoa(mysqlPort), database)- buf, err := doBackup(ctx, driver, database)+ buf, backupPayload, err := doBackup(ctx, driver, database)a.NoError(err)t.Logf("backup content:\n%s", buf.String())// 3. insert more data for incremental restoret.Log("insert more data")insertRangeData(t, db, numRowsTime0, numRowsTime1)+ // Sleep for one second so that the data in this second will be recovered by mysqlbinlog --stop-datetime.+ time.Sleep(time.Second)+ targetTs := time.Now().Unix()// 4. drop databasedropStmt := fmt.Sprintf(`DROP DATABASE %s;`, database)@@ -238,18 +243,18 @@ func TestPITR(t *testing.T) {// 6. restoret.Log("restore to pitr database")- createPITRIssueTimestamp := time.Now().Unix()+ suffixTs := time.Now().Unix()mysqlDriver, ok := driver.(*pluginmysql.Driver)a.Equal(true, ok)binlogDir := t.TempDir()mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilInstance, connCfg, binlogDir)- binlogInfo := api.BinlogInfo{}- err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), binlogInfo, database, createPITRIssueTimestamp)- // TODO(zp): change to a.NoError(err) when binlogInfo is determined- a.Error(err)+ err = mysqlRestore.IncrementalFetchAllBinlogFiles(ctx)+ a.NoError(err)+ err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), backupPayload.BinlogInfo, database, suffixTs, targetTs)+ a.NoError(err)t.Log("cutover stage")- _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)+ _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, suffixTs)a.NoError(err)})@@ -273,8 +278,7 @@ func TestPITR(t *testing.T) {defer driver.Close(ctx)connCfg := getMySQLConnectionConfig(strconv.Itoa(mysqlPort), database)-- buf, err := doBackup(ctx, driver, database)+ buf, backupPayload, err := doBackup(ctx, driver, database)a.NoError(err)t.Logf("backup content:\n%s\n", buf.String())@@ -282,10 +286,10 @@ func TestPITR(t *testing.T) {insertRangeData(t, db, numRowsTime0, numRowsTime1)ctxUpdateRow, cancelUpdateRow := context.WithCancel(ctx)- t1 := startUpdateRow(ctxUpdateRow, t, database, mysqlPort)- t.Logf("start to concurrently update data at t1: %v", t1)+ targetTs := startUpdateRow(ctxUpdateRow, t, database, mysqlPort) + 1+ t.Logf("start to concurrently update data at t1: %v", time.Unix(targetTs, 0))- createPITRIssueTimestamp := time.Now().Unix()+ suffixTs := time.Now().Unix()t.Log("mimics schema migration")dropColumnStmt := `ALTER TABLE tbl1 DROP COLUMN id;`@@ -297,26 +301,25 @@ func TestPITR(t *testing.T) {a.Equal(true, ok)binlogDir := t.TempDir()mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilInstance, connCfg, binlogDir)- binlogInfo := api.BinlogInfo{}- err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), binlogInfo, database, createPITRIssueTimestamp)- // TODO(zp): change to a.NoError(err) when binlogInfo is determined- a.Error(err)+ err = mysqlRestore.IncrementalFetchAllBinlogFiles(ctx)+ a.NoError(err)+ err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), backupPayload.BinlogInfo, database, suffixTs, targetTs)+ a.NoError(err)t.Log("cutover stage")cancelUpdateRow()// We mimics the situation where the user waits for the target database idle before doing the cutover.time.Sleep(time.Second)- _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)+ _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, suffixTs)a.NoError(err)t.Log("validate table tbl0")- // TODO(zp): change to numRowsTime1 when RestoreIncremental is implemented- validateTbl0(t, db, numRowsTime0)+ validateTbl0(t, db, numRowsTime1)t.Log("validate table tbl1")- validateTbl1(t, db, numRowsTime0)- // TODO(zp): validate table _update_row_ when RestoreIncremental is implemented+ validateTbl1(t, db, numRowsTime1)t.Log("validate table _update_row_")+ validateTableUpdateRow(t, db)})}@@ -351,7 +354,6 @@ func initPITRDB(t *testing.T, database string, port int) (*sql.DB, func()) {func insertRangeData(t *testing.T, db *sql.DB, begin, end int) {a := require.New(t)-tx, err := db.Begin()a.NoError(err)@@ -394,33 +396,58 @@ func validateTbl1(t *testing.T, db *sql.DB, numRows int) {i++}a.NoError(rows.Err())- // TODO(dragonly): change to numRowsTime1 when RestoreIncremental is implementeda.Equal(numRows, i)}-func doBackup(ctx context.Context, driver dbplugin.Driver, database string) (*bytes.Buffer, error) {+func validateTableUpdateRow(t *testing.T, db *sql.DB) {+ a := require.New(t)+ rows, err := db.Query("SELECT * FROM _update_row_;")+ a.NoError(err)++ a.Equal(true, rows.Next())+ var col int+ a.NoError(rows.Scan(&col))+ a.Equal(0, col)+ a.Equal(false, rows.Next())++ a.NoError(rows.Err())+}++func doBackup(ctx context.Context, driver dbplugin.Driver, database string) (*bytes.Buffer, *api.BackupPayload, error) {var buf bytes.Buffer- _, err := driver.Dump(ctx, database, &buf, false)- return &buf, err+ var backupPayload api.BackupPayload+ backupPayloadString, err := driver.Dump(ctx, database, &buf, false)+ if err := json.Unmarshal([]byte(backupPayloadString), &backupPayload); err != nil {+ return nil, nil, err+ }+ return &buf, &backupPayload, err}+// Concurrently update a single row to mimic the ongoing business workload.+// Returns the timestamp after inserting the initial value so we could check the PITR is done right.func startUpdateRow(ctx context.Context, t *testing.T, database string, port int) int64 {a := require.New(t)db, err := connectTestMySQL(port, database)a.NoError(err)- t.Log("Start updating data")+ t.Log("Start updating data concurrently")_, err = db.Exec("CREATE TABLE _update_row_ (id INT PRIMARY KEY);")a.NoError(err)- // init value is (0)+ // initial value is (0)_, err = db.Exec("INSERT INTO _update_row_ VALUES (0);")a.NoError(err)initTimestamp := time.Now().Unix()+ // Sleep for one second so that the concurrent update will start no earlier than initTimestamp+1.+ // This will make a clear boundary for the binlog recovery --stop-datetime.+ // For example, the recovery command is mysqlbinlog --stop-datetime `initTimestamp+1`, and the concurrent updates+ // later will no be recovered. Then we can validate by checking the table _update_row_ has the initial value (0).+ time.Sleep(time.Second)+go func() {defer db.Close()- ticker := time.NewTicker(10 * time.Millisecond)+ ticker := time.NewTicker(1 * time.Millisecond)i := 0for {select {@@ -429,7 +456,7 @@ func startUpdateRow(ctx context.Context, t *testing.T, database string, port inta.NoError(err)i++case <-ctx.Done():- t.Log("Stop updating data")+ t.Log("Stop updating data concurrently")return}}diff --git a/tests/mysql.go b/tests/mysql.goindex 11d04152c7..ef7805dfed 100644--- a/tests/mysql.go+++ b/tests/mysql.go@@ -13,7 +13,7 @@ import (func getMySQLConnectionConfig(port string, database string) db.ConnectionConfig {return db.ConnectionConfig{- Host: "localhost",+ Host: "127.0.0.1",Port: port,Username: "root",Password: "",