Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: support in-place backup restore (#2270)

Yilong Li0c0f5ae013f7
diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.go
index ac92d9ebc7..411dd99c53 100644
--- a/plugin/db/mysql/restore.go
+++ b/plugin/db/mysql/restore.go
@@ -38,9 +38,6 @@ import (
)
const (
- // MaxDatabaseNameLength is the allowed max database name length in MySQL.
- MaxDatabaseNameLength = 64
-
// Variable lower_case_table_names related.
// LetterCaseOnDiskLetterCaseCmp stores table and database names using the letter case specified in the CREATE TABLE or CREATE DATABASE statement.
@@ -200,14 +197,14 @@ func (driver *Driver) GetReplayedBinlogBytes() int64 {
// 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)
+ pitrDatabaseName := util.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)
+ pitrDatabaseName := util.GetPITRDatabaseName(databaseName, suffixTs)
// Create the pitr database.
stmt := fmt.Sprintf("CREATE DATABASE `%s`;", pitrDatabaseName)
db, err := driver.GetDBConnection(ctx, "")
@@ -372,8 +369,8 @@ func (driver *Driver) getLatestBackupBeforeOrEqualBinlogCoord(backupList []*api.
// It returns the pitr and old database names after swap.
// It performs the step 2 of the restore process.
func SwapPITRDatabase(ctx context.Context, conn *sql.Conn, database string, suffixTs int64) (string, string, error) {
- pitrDatabaseName := getPITRDatabaseName(database, suffixTs)
- pitrOldDatabase := getPITROldDatabaseName(database, suffixTs)
+ pitrDatabaseName := util.GetPITRDatabaseName(database, suffixTs)
+ pitrOldDatabase := util.GetPITROldDatabaseName(database, suffixTs)
// Handle the case that the original database does not exist, because user could drop a database and want to restore it.
log.Debug("Checking database exists.", zap.String("database", database))
@@ -450,20 +447,6 @@ func databaseExists(ctx context.Context, conn *sql.Conn, database string) (bool,
return true, nil
}
-// Composes a pitr database name that we use as the target database for full backup recovery and binlog recovery.
-// For example, getPITRDatabaseName("dbfoo", 1653018005) -> "dbfoo_pitr_1653018005".
-func getPITRDatabaseName(database string, suffixTs int64) string {
- suffix := fmt.Sprintf("pitr_%d", suffixTs)
- return getSafeName(database, suffix)
-}
-
-// Composes a database name that we use as the target database for swapping out the original database.
-// For example, getPITROldDatabaseName("dbfoo", 1653018005) -> "dbfoo_pitr_1653018005_del".
-func getPITROldDatabaseName(database string, suffixTs int64) string {
- suffix := fmt.Sprintf("pitr_%d_del", suffixTs)
- return getSafeName(database, suffix)
-}
-
// GetSortedLocalBinlogFiles returns a sorted BinlogFile list in the given binlog dir.
func GetSortedLocalBinlogFiles(binlogDir string) ([]BinlogFile, error) {
binlogFilesInfoLocal, err := ioutil.ReadDir(binlogDir)
@@ -850,15 +833,6 @@ func GetBinlogNameSeq(name string) (int64, error) {
return strconv.ParseInt(s[1], 10, 0)
}
-func getSafeName(baseName, suffix string) string {
- name := fmt.Sprintf("%s_%s", baseName, suffix)
- if len(name) <= MaxDatabaseNameLength {
- return name
- }
- extraCharacters := len(name) - MaxDatabaseNameLength
- return fmt.Sprintf("%s_%s", baseName[0:len(baseName)-extraCharacters], suffix)
-}
-
// checks the MySQL version is >=8.0.
func checkVersionForPITR(version string) error {
v, err := semver.Parse(version)
diff --git a/plugin/db/mysql/restore_test.go b/plugin/db/mysql/restore_test.go
index 8eb7858a73..07108e6b2f 100644
--- a/plugin/db/mysql/restore_test.go
+++ b/plugin/db/mysql/restore_test.go
@@ -7,6 +7,7 @@ import (
"time"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/plugin/db/util"
"github.com/stretchr/testify/require"
)
@@ -35,7 +36,7 @@ func TestGetSafeName(t *testing.T) {
}
for _, test := range tests {
- safeName := getSafeName(test.baseName, test.suffix)
+ safeName := util.GetSafeName(test.baseName, test.suffix)
a.Equal(test.expected, safeName)
}
}
@@ -60,7 +61,7 @@ func TestGetPITRDatabaseName(t *testing.T) {
}
for _, test := range tests {
- name := getPITRDatabaseName(test.database, int64(test.timestamp))
+ name := util.GetPITRDatabaseName(test.database, int64(test.timestamp))
a.Equal(test.expected, name)
}
}
@@ -85,7 +86,7 @@ func TestGetPITROldDatabaseName(t *testing.T) {
}
for _, test := range tests {
- name := getPITROldDatabaseName(test.database, int64(test.timestamp))
+ name := util.GetPITROldDatabaseName(test.database, int64(test.timestamp))
a.Equal(test.expected, name)
}
}
diff --git a/plugin/db/util/restore.go b/plugin/db/util/restore.go
new file mode 100644
index 0000000000..b3ac6c4079
--- /dev/null
+++ b/plugin/db/util/restore.go
@@ -0,0 +1,34 @@
+package util
+
+import "fmt"
+
+const (
+ // MaxDatabaseNameLength is the allowed max database name length in MySQL.
+ MaxDatabaseNameLength = 64
+)
+
+// TODO(dragonly): Check for PostgreSQL.
+
+// GetPITRDatabaseName composes a pitr database name that we use as the target database for full backup recovery and binlog recovery.
+// For example, GetPITRDatabaseName("dbfoo", 1653018005) -> "dbfoo_pitr_1653018005".
+func GetPITRDatabaseName(database string, suffixTs int64) string {
+ suffix := fmt.Sprintf("pitr_%d", suffixTs)
+ return GetSafeName(database, suffix)
+}
+
+// GetPITROldDatabaseName composes a database name that we use as the target database for swapping out the original database.
+// For example, GetPITROldDatabaseName("dbfoo", 1653018005) -> "dbfoo_pitr_1653018005_del".
+func GetPITROldDatabaseName(database string, suffixTs int64) string {
+ suffix := fmt.Sprintf("pitr_%d_del", suffixTs)
+ return GetSafeName(database, suffix)
+}
+
+// GetSafeName trims the name according to max allowed database name length.
+func GetSafeName(baseName, suffix string) string {
+ name := fmt.Sprintf("%s_%s", baseName, suffix)
+ if len(name) <= MaxDatabaseNameLength {
+ return name
+ }
+ extraCharacters := len(name) - MaxDatabaseNameLength
+ return fmt.Sprintf("%s_%s", baseName[0:len(baseName)-extraCharacters], suffix)
+}
diff --git a/server/issue.go b/server/issue.go
index 7b8c542536..12698e3e3f 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -911,11 +911,6 @@ func (s *Server) createPITRTaskList(ctx context.Context, originDatabase *api.Dat
BackupID: c.BackupID,
}
- // We don't support inplace backup restore yet.
- if payloadRestore.BackupID != nil && payloadRestore.TargetInstanceID == nil {
- return nil, nil, common.Errorf(common.Invalid, "unexpect restore inplace")
- }
-
if payloadRestore.TargetInstanceID != nil {
restoreTaskCreate.InstanceID = c.CreateDatabaseCtx.InstanceID
restoreTaskCreate.DatabaseName = c.CreateDatabaseCtx.DatabaseName
@@ -925,7 +920,7 @@ func (s *Server) createPITRTaskList(ctx context.Context, originDatabase *api.Dat
}
taskCreateList = append(taskCreateList, restoreTaskCreate)
- // Inplace restore needs a cutover task.
+ // In-place restore needs a cutover task.
if payloadRestore.TargetInstanceID == nil {
payloadCutover := api.TaskDatabasePITRCutoverPayload{}
bytesCutover, err := json.Marshal(payloadCutover)
diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.go
index 9fea3c3143..effbd39718 100644
--- a/server/task_executor_pitr_cutover.go
+++ b/server/task_executor_pitr_cutover.go
@@ -12,6 +12,7 @@ import (
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/plugin/db/mysql"
+ "github.com/bytebase/bytebase/plugin/db/util"
"go.uber.org/zap"
)
@@ -86,34 +87,24 @@ func (*PITRCutoverTaskExecutor) GetProgress() api.Progress {
// 1. Swap the current and PITR database.
// 2. Create a backup with type PITR. The backup is scheduled asynchronously.
// We must check the possible failed/ongoing PITR type backup in the recovery process.
-func (*PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.Task, server *Server, issue *api.Issue) (terminated bool, result *api.TaskRunResultPayload, err error) {
+func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.Task, server *Server, issue *api.Issue) (terminated bool, result *api.TaskRunResultPayload, err error) {
driver, err := server.getAdminDatabaseDriver(ctx, task.Instance, "" /* databaseName */)
if err != nil {
return true, nil, err
}
defer driver.Close(ctx)
- driverDB, err := driver.GetDBConnection(ctx, "")
- if err != nil {
- return true, nil, err
- }
- conn, err := driverDB.Conn(ctx)
- if err != nil {
- return true, nil, err
- }
- defer conn.Close()
-
- log.Debug("Swapping the original and PITR database", zap.String("originalDatabase", task.Database.Name))
- pitrDatabaseName, pitrOldDatabaseName, err := mysql.SwapPITRDatabase(ctx, conn, task.Database.Name, issue.CreatedTs)
- if err != nil {
- log.Error("Failed to swap the original and PITR database", zap.String("originalDatabase", task.Database.Name), zap.String("pitrDatabase", pitrDatabaseName), zap.Error(err))
- return true, nil, fmt.Errorf("failed to swap the original and PITR database, error: %w", err)
- }
- log.Debug("Finished swapping the original and PITR database", zap.String("originalDatabase", task.Database.Name), zap.String("pitrDatabase", pitrDatabaseName), zap.String("oldDatabase", pitrOldDatabaseName))
-
- backupName := fmt.Sprintf("%s-%s-pitr-%d", api.ProjectShortSlug(task.Database.Project), api.EnvSlug(task.Database.Instance.Environment), issue.CreatedTs)
- if _, err := server.scheduleBackupTask(ctx, task.Database, backupName, api.BackupTypePITR, api.SystemBotID); err != nil {
- return true, nil, fmt.Errorf("failed to schedule backup task for database %q after PITR, error: %w", task.Database.Name, err)
+ switch task.Instance.Engine {
+ case db.Postgres:
+ if err := exec.pitrCutoverPostgres(ctx, driver, task, issue); err != nil {
+ return true, nil, fmt.Errorf("failed to do cutover for PostgreSQL, error: %w", err)
+ }
+ case db.MySQL:
+ if err := exec.pitrCutoverMySQL(ctx, driver, server, task, issue); err != nil {
+ return true, nil, fmt.Errorf("failed to do cutover for MySQL, error: %w", err)
+ }
+ default:
+ return true, nil, fmt.Errorf("invalid database type %q for cutover task", task.Instance.Engine)
}
log.Debug("Appending new migration history record")
@@ -148,3 +139,44 @@ func (*PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.Task,
Detail: fmt.Sprintf("Swapped PITR database for target database %q", task.Database.Name),
}, nil
}
+
+func (*PITRCutoverTaskExecutor) pitrCutoverMySQL(ctx context.Context, driver db.Driver, server *Server, task *api.Task, issue *api.Issue) error {
+ driverDB, err := driver.GetDBConnection(ctx, "")
+ if err != nil {
+ return err
+ }
+ conn, err := driverDB.Conn(ctx)
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+ log.Debug("Swapping the original and PITR database", zap.String("originalDatabase", task.Database.Name))
+ pitrDatabaseName, pitrOldDatabaseName, err := mysql.SwapPITRDatabase(ctx, conn, task.Database.Name, issue.CreatedTs)
+ if err != nil {
+ log.Error("Failed to swap the original and PITR database", zap.String("originalDatabase", task.Database.Name), zap.String("pitrDatabase", pitrDatabaseName), zap.Error(err))
+ return fmt.Errorf("failed to swap the original and PITR database, error: %w", err)
+ }
+ log.Debug("Finished swapping the original and PITR database", zap.String("originalDatabase", task.Database.Name), zap.String("pitrDatabase", pitrDatabaseName), zap.String("oldDatabase", pitrOldDatabaseName))
+ // TODO(dragonly): Only needed for in-place PITR.
+ backupName := fmt.Sprintf("%s-%s-pitr-%d", api.ProjectShortSlug(task.Database.Project), api.EnvSlug(task.Database.Instance.Environment), issue.CreatedTs)
+ if _, err := server.scheduleBackupTask(ctx, task.Database, backupName, api.BackupTypePITR, api.SystemBotID); err != nil {
+ return fmt.Errorf("failed to schedule backup task for database %q after PITR, error: %w", task.Database.Name, err)
+ }
+ return nil
+}
+
+func (*PITRCutoverTaskExecutor) pitrCutoverPostgres(ctx context.Context, driver db.Driver, task *api.Task, issue *api.Issue) error {
+ pitrDatabaseName := util.GetPITRDatabaseName(task.Database.Name, issue.CreatedTs)
+ pitrOldDatabaseName := util.GetPITROldDatabaseName(task.Database.Name, issue.CreatedTs)
+ db, err := driver.GetDBConnection(ctx, db.BytebaseDatabase)
+ if err != nil {
+ return fmt.Errorf("failed to get connection for PostgreSQL, error: %w", err)
+ }
+ if _, err := db.ExecContext(ctx, fmt.Sprintf("ALTER DATABASE %s RENAME TO %s;", task.Database.Name, pitrOldDatabaseName)); err != nil {
+ return fmt.Errorf("failed to rename database %q to %q, error: %w", task.Database.Name, pitrOldDatabaseName, err)
+ }
+ if _, err := db.ExecContext(ctx, fmt.Sprintf("ALTER DATABASE %s RENAME TO %s;", pitrDatabaseName, task.Database.Name)); err != nil {
+ return fmt.Errorf("failed to rename database %q to %q, error: %w", pitrDatabaseName, task.Database.Name, err)
+ }
+ return nil
+}
diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.go
index 4f37c71f16..9ce99d239d 100644
--- a/server/task_executor_pitr_restore.go
+++ b/server/task_executor_pitr_restore.go
@@ -12,7 +12,9 @@ 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/plugin/db/util"
"github.com/bytebase/bytebase/store"
"go.uber.org/zap"
)
@@ -46,12 +48,16 @@ func (exec *PITRRestoreTaskExecutor) RunOnce(ctx context.Context, server *Server
// 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
- if payload.BackupID != nil {
- resultPayload, err := exec.doBackupRestore(ctx, server, task, payload)
+ if payload.DatabaseName != nil {
+ resultPayload, err := exec.doRestoreToNewDatabase(ctx, server, task, payload)
return true, resultPayload, err
}
- resultPayload, err := exec.doPITRRestore(ctx, server, task, payload)
+ // TODO(dragonly): Check this when creating issue.
+ if payload.TargetInstanceID != nil {
+ return true, nil, fmt.Errorf("expect targetInstanceId to be nil when databaseName is nil in TaskDatabasePITRRestorePayload")
+ }
+ resultPayload, err := exec.doRestoreInPlace(ctx, server, task, payload)
return true, resultPayload, err
}
@@ -69,12 +75,7 @@ func (exec *PITRRestoreTaskExecutor) GetProgress() api.Progress {
return progress.(api.Progress)
}
-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")
- }
+func (exec *PITRRestoreTaskExecutor) doRestoreToNewDatabase(ctx context.Context, server *Server, task *api.Task, payload api.TaskDatabasePITRRestorePayload) (*api.TaskRunResultPayload, error) {
// Restore full backup only
backup, err := server.store.GetBackupByID(ctx, *payload.BackupID)
if err != nil {
@@ -157,7 +158,7 @@ func (exec *PITRRestoreTaskExecutor) doBackupRestore(ctx context.Context, server
}, nil
}
-func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *Server, task *api.Task, payload api.TaskDatabasePITRRestorePayload) (*api.TaskRunResultPayload, error) {
+func (exec *PITRRestoreTaskExecutor) doRestoreInPlace(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
@@ -168,6 +169,10 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *
return nil, err
}
+ if task.Instance.Engine == db.Postgres {
+ return exec.doRestoreInPlacePostgres(ctx, server, driver, issue, task, payload)
+ }
+
backupStatus := api.BackupStatusDone
backupList, err := server.store.FindBackup(ctx, &api.BackupFind{DatabaseID: task.DatabaseID, Status: &backupStatus})
if err != nil {
@@ -214,7 +219,6 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *
// 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 BRANCH migration.
startBinlogInfo := backup.Payload.BinlogInfo
-
binlogDir := getBinlogAbsDir(server.profile.DataDir, task.Instance.ID)
if err := exec.updateProgress(ctx, mysqlDriver, backupFile, startBinlogInfo, binlogDir); err != nil {
return nil, fmt.Errorf("failed to setup progress update process, error: %w", err)
@@ -246,6 +250,45 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *
}, nil
}
+func (*PITRRestoreTaskExecutor) doRestoreInPlacePostgres(ctx context.Context, server *Server, driver db.Driver, issue *api.Issue, task *api.Task, payload api.TaskDatabasePITRRestorePayload) (*api.TaskRunResultPayload, error) {
+ if payload.BackupID == nil {
+ return nil, fmt.Errorf("PITR for Postgres is not implemented")
+ }
+
+ backup, err := server.store.GetBackupByID(ctx, *payload.BackupID)
+ if err != nil {
+ 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)
+ }
+ backupFileName := getBackupAbsFilePath(server.profile.DataDir, backup.DatabaseID, backup.Name)
+ backupFile, err := os.Open(backupFileName)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open backup file %q, error: %w", backupFileName, err)
+ }
+ defer backupFile.Close()
+ db, err := driver.GetDBConnection(ctx, db.BytebaseDatabase)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get connection for PostgreSQL, error: %w", err)
+ }
+ pitrDatabaseName := util.GetPITRDatabaseName(task.Database.Name, issue.CreatedTs)
+ if _, err := db.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE %s;", pitrDatabaseName)); err != nil {
+ return nil, fmt.Errorf("failed to create PITR database %q, error: %w", pitrDatabaseName, err)
+ }
+ // Switch to the PITR database.
+ // TODO(dragonly): This is a trick, needs refactor.
+ if _, err := driver.GetDBConnection(ctx, pitrDatabaseName); err != nil {
+ return nil, fmt.Errorf("failed to get connection for database %q, error: %w", pitrDatabaseName, err)
+ }
+ if err := driver.Restore(ctx, backupFile); err != nil {
+ return nil, fmt.Errorf("failed to restore backup to the PITR database %q, error: %w", pitrDatabaseName, err)
+ }
+ return &api.TaskRunResultPayload{
+ Detail: fmt.Sprintf("Restored database %q in place from backup %q", task.Database.Name, backup.Name),
+ }, nil
+}
+
func (exec *PITRRestoreTaskExecutor) updateProgress(ctx context.Context, driver *mysql.Driver, backupFile *os.File, startBinlogInfo api.BinlogInfo, binlogDir string) error {
backupFileInfo, err := backupFile.Stat()
if err != nil {