Skip to content

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

feat: replay binlog from s3 (#2482)

Yilong Li8f26c54b4da8
diff --git a/common/util.go b/common/util.go
index 3f48584043..005e5c8e2c 100644
--- a/common/util.go
+++ b/common/util.go
@@ -5,6 +5,7 @@ import (
"math/big"
"os"
"path"
+ "path/filepath"
"regexp"
"sort"
"strings"
@@ -107,3 +108,10 @@ func GetFileSizeSum(fileNameList []string) (int64, error) {
}
return sum, nil
}
+
+// GetBinlogRelativeDir composes the relative directory for binlog.
+// It's useful to convert a local absolute binlog directory path to the cloud path.
+func GetBinlogRelativeDir(binlogDir string) string {
+ instanceID := filepath.Base(binlogDir)
+ return filepath.Join("backup", "instance", instanceID)
+}
diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.go
index 17a5f1dff0..587e255ba2 100644
--- a/plugin/db/mysql/restore.go
+++ b/plugin/db/mysql/restore.go
@@ -127,7 +127,6 @@ func readBinlogMetaFile(binlogDir, fileName string) (binlogFileMeta, error) {
// replayBinlogFromDir replays the binlog for `originDatabase` from `startBinlogInfo.Position` to `targetTs`, read binlog from `binlogDir`.
func (driver *Driver) replayBinlogFromDir(ctx context.Context, originalDatabase, targetDatabase string, startBinlogInfo, targetBinlogInfo api.BinlogInfo, targetTs int64, binlogDir string) error {
- // TODO(dragonly): find the last binlog file need to replay.
replayBinlogPaths, err := GetBinlogReplayList(startBinlogInfo, targetBinlogInfo, binlogDir)
if err != nil {
return errors.Wrapf(err, "failed to get binlog replay list in directory %s", binlogDir)
@@ -334,12 +333,12 @@ func sortBinlogFiles(binlogFiles []BinlogFile) []BinlogFile {
// 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.
-func (driver *Driver) GetLatestBackupBeforeOrEqualTs(ctx context.Context, backupList []*api.Backup, targetTs int64) (*api.Backup, *api.BinlogInfo, error) {
+func (driver *Driver) GetLatestBackupBeforeOrEqualTs(ctx context.Context, backupList []*api.Backup, targetTs int64, client *bbs3.Client) (*api.Backup, *api.BinlogInfo, error) {
if len(backupList) == 0 {
return nil, nil, errors.Errorf("no valid backup")
}
- targetBinlogCoordinate, err := driver.getBinlogCoordinateByTs(ctx, targetTs)
+ targetBinlogCoordinate, err := driver.getBinlogCoordinateByTs(ctx, targetTs, client)
if err != nil {
log.Error("Failed to get binlog coordinate by targetTs", zap.Int64("targetTs", targetTs), zap.Error(err))
return nil, nil, errors.Wrapf(err, "failed to get binlog coordinate by targetTs %d", targetTs)
@@ -560,11 +559,6 @@ func binlogMetaAreContinuous(files []binlogFileMeta) bool {
return true
}
-func getBinlogRelativeDir(binlogDir string) string {
- instanceID := filepath.Base(binlogDir)
- return filepath.Join("backup", "instance", instanceID)
-}
-
// Download binlog files on server.
func (driver *Driver) downloadBinlogFilesOnServer(ctx context.Context, metaList []binlogFileMeta, binlogFilesOnServerSorted []BinlogFile, downloadLatestBinlogFile bool, uploader *bbs3.Client) error {
if len(binlogFilesOnServerSorted) == 0 {
@@ -621,10 +615,11 @@ func (driver *Driver) FetchAllBinlogFiles(ctx context.Context, downloadLatestBin
log.Debug("No binlog file found on server to download")
return nil
}
- log.Debug("Got sorted binlog file list on server", zap.Array("list", ZapBinlogFiles(binlogFilesOnServerSorted)))
- if err := driver.syncBinlogMetaFileFromCloud(ctx, client); err != nil {
- return errors.Wrap(err, "failed to sync binlog metadata files from the cloud")
+ if client != nil {
+ if err := driver.syncBinlogMetaFileFromCloud(ctx, client); err != nil {
+ return errors.Wrap(err, "failed to sync binlog metadata files from the cloud")
+ }
}
metaList, err := getSortedLocalBinlogFilesMeta(driver.binlogDir)
@@ -640,30 +635,19 @@ func (driver *Driver) FetchAllBinlogFiles(ctx context.Context, downloadLatestBin
}
func (driver *Driver) syncBinlogMetaFileFromCloud(ctx context.Context, client *bbs3.Client) error {
- if client == nil {
- return nil
- }
-
metaListToDownload, err := driver.getBinlogMetaFileListToDownload(ctx, client)
if err != nil {
return errors.Wrapf(err, "failed to get binlog metadata file list on cloud in directory %q", driver.binlogDir)
}
log.Debug(fmt.Sprintf("Downloading %d binlog metadata file from cloud storage", len(metaListToDownload)))
- relativeDir := getBinlogRelativeDir(driver.binlogDir)
- tempDir := os.TempDir()
for _, metaFileName := range metaListToDownload {
- metaFilePathTemp := filepath.Join(tempDir, metaFileName)
- metaFileTemp, err := os.Create(metaFilePathTemp)
- if err != nil {
- return errors.Wrapf(err, "failed to create temporary binlog metadata file %q", metaFileName)
- }
- if _, err := client.DownloadObject(ctx, path.Join(relativeDir, metaFileName), metaFileTemp); err != nil {
- return errors.Wrapf(err, "failed to download binlog metadata file %q", metaFileName)
- }
- metaFilePath := filepath.Join(driver.binlogDir, metaFileName)
- if err := os.Rename(metaFilePathTemp, metaFilePath); err != nil {
- return errors.Wrapf(err, "failed to rename %q to %q", metaFilePathTemp, metaFilePath)
+ // Use filepath.Join to compose an OS-specific local file system path.
+ filePathLocal := filepath.Join(driver.binlogDir, metaFileName)
+ // Use path.Join to compose a path on cloud which always uses / as the separator.
+ filePathOnCloud := path.Join(common.GetBinlogRelativeDir(driver.binlogDir), metaFileName)
+ if err := client.DownloadFileFromCloud(ctx, filePathLocal, filePathOnCloud); err != nil {
+ return errors.Wrapf(err, "failed to download binlog metadata file %s from the cloud storage", metaFileName)
}
}
@@ -768,7 +752,7 @@ func (driver *Driver) uploadBinlogFileToCloud(ctx context.Context, uploader *bbs
}
defer binlogFile.Close()
defer os.Remove(binlogFilePath)
- relativeDir := getBinlogRelativeDir(driver.binlogDir)
+ relativeDir := common.GetBinlogRelativeDir(driver.binlogDir)
if _, err := uploader.UploadObject(ctx, path.Join(relativeDir, binlogFileName), binlogFile); err != nil {
// Remove the local metadata file so that it can be re-uploaded later.
if err := os.Remove(metaFilePath); err != nil {
@@ -850,7 +834,7 @@ func (driver *Driver) GetSortedBinlogFilesOnServer(ctx context.Context) ([]Binlo
}
// getBinlogCoordinateByTs converts a timestamp to binlog coordinate using local binlog files.
-func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int64) (*binlogCoordinate, error) {
+func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int64, client *bbs3.Client) (*binlogCoordinate, error) {
metaList, err := getSortedLocalBinlogFilesMeta(driver.binlogDir)
if err != nil {
return nil, errors.Wrap(err, "failed to read local binlog metadata files")
@@ -883,6 +867,15 @@ func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int6
}
log.Debug("Found potential binlog file containing targetTs", zap.String("binlogFile", targetMeta.binlogName), zap.Int64("targetTs", targetTs), zap.Bool("isLastBinlogFile", isLastBinlogFile))
+ if client != nil {
+ // Use filepath.Join to compose an OS-specific local file system path.
+ filePathLocal := filepath.Join(driver.binlogDir, targetMeta.binlogName)
+ // Use path.Join to compose a path on cloud which always uses / as the separator.
+ filePathOnCloud := path.Join(common.GetBinlogRelativeDir(driver.binlogDir), targetMeta.binlogName)
+ if err := client.DownloadFileFromCloud(ctx, filePathLocal, filePathOnCloud); err != nil {
+ return nil, errors.Wrapf(err, "failed to download binlog file %s from the cloud storage", targetMeta.binlogName)
+ }
+ }
eventPos, err := driver.getBinlogEventPositionAtOrAfterTs(ctx, targetMeta.binlogName, targetTs)
if err != nil {
if common.ErrorCode(err) == common.NotFound {
@@ -1028,6 +1021,7 @@ func (driver *Driver) getBinlogEventPositionAtOrAfterTs(ctx context.Context, bin
}
if pos == 0 {
+ // TODO(dragonly): Check for mysqlbinlog process exit error to give more specific error messages, e.g., file not exist.
return 0, common.Errorf(common.NotFound, "failed to find event position at or after targetTs %d", targetTs)
}
diff --git a/plugin/storage/s3/s3.go b/plugin/storage/s3/s3.go
index 21863d2fc3..3f2475236e 100644
--- a/plugin/storage/s3/s3.go
+++ b/plugin/storage/s3/s3.go
@@ -4,6 +4,8 @@ package s3
import (
"context"
"io"
+ "os"
+ "path/filepath"
"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
@@ -92,3 +94,23 @@ func (c *Client) DeleteObject(ctx context.Context, path string) (*s3.DeleteObjec
func (c *Client) GetBucket() string {
return c.bucket
}
+
+// DownloadFileFromCloud downloads a binlog or metadata file from the cloud storage.
+// In case of network errors which will get partially downloaded files, we first download to a temporary file.
+// After that, we then rename it to the target file path.
+func (c *Client) DownloadFileFromCloud(ctx context.Context, filePathLocal, filePathOnCloud string) error {
+ tempDir := os.TempDir()
+ baseName := filepath.Base(filePathLocal)
+ filePathTemp := filepath.Join(tempDir, baseName)
+ fileTemp, err := os.Create(filePathTemp)
+ if err != nil {
+ return errors.Wrapf(err, "failed to create the local temporary file %s", filePathTemp)
+ }
+ if _, err := c.DownloadObject(ctx, filePathOnCloud, fileTemp); err != nil {
+ return errors.Wrapf(err, "failed to download file %q from the cloud storage", filePathOnCloud)
+ }
+ if err := os.Rename(filePathTemp, filePathLocal); err != nil {
+ return errors.Wrapf(err, "failed to rename %q to %q", filePathTemp, filePathLocal)
+ }
+ return nil
+}
diff --git a/server/backup_runner.go b/server/backup_runner.go
index 766a9a5de7..2c10a837da 100644
--- a/server/backup_runner.go
+++ b/server/backup_runner.go
@@ -206,6 +206,7 @@ func (r *BackupRunner) downloadBinlogFiles(ctx context.Context) {
return
}
+ log.Debug(fmt.Sprintf("Downloading binlog files for %d MySQL instances.", len(instanceList)))
r.downloadBinlogMu.Lock()
defer r.downloadBinlogMu.Unlock()
for _, instance := range instanceList {
diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.go
index a7fa566597..88b63002aa 100644
--- a/server/task_executor_pitr_cutover.go
+++ b/server/task_executor_pitr_cutover.go
@@ -102,6 +102,9 @@ func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.
return true, nil, err
}
+ // 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 BRANCH migration.
log.Debug("Appending new migration history record")
m := &db.MigrationInfo{
ReleaseVersion: server.profile.Version,
diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.go
index 6eb36969b7..ba797ce117 100644
--- a/server/task_executor_pitr_restore.go
+++ b/server/task_executor_pitr_restore.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"os"
+ "path"
"path/filepath"
"sync/atomic"
"time"
@@ -19,6 +20,7 @@ import (
"github.com/bytebase/bytebase/plugin/db/mysql"
"github.com/bytebase/bytebase/plugin/db/pg"
"github.com/bytebase/bytebase/plugin/db/util"
+ bbs3 "github.com/bytebase/bytebase/plugin/storage/s3"
"github.com/bytebase/bytebase/store"
)
@@ -214,7 +216,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *
targetTs := *payload.PointInTimeTs
log.Debug("Getting latest backup before or equal to targetTs", zap.Int64("targetTs", targetTs))
- backup, targetBinlogInfo, err := mysqlSourceDriver.GetLatestBackupBeforeOrEqualTs(ctx, backupList, targetTs)
+ backup, targetBinlogInfo, err := mysqlSourceDriver.GetLatestBackupBeforeOrEqualTs(ctx, backupList, targetTs, server.s3Client)
if err != nil {
targetTsHuman := time.Unix(targetTs, 0).Format(time.RFC822)
log.Error("Failed to get backup before or equal to time",
@@ -223,30 +225,47 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *
zap.Error(err))
return nil, errors.Wrapf(err, "failed to get latest backup before or equal to %s", targetTsHuman)
}
+ startBinlogInfo := backup.Payload.BinlogInfo
+ binlogDir := getBinlogAbsDir(server.profile.DataDir, task.Instance.ID)
log.Debug("Got latest backup before or equal to targetTs", zap.String("backup", backup.Name))
- backupFileName := getBackupAbsFilePath(server.profile.DataDir, backup.DatabaseID, backup.Name)
- backupFile, err := os.Open(backupFileName)
+
+ backupAbsPathLocal := getBackupAbsFilePath(server.profile.DataDir, backup.DatabaseID, backup.Name)
+ if backup.StorageBackend == api.BackupStorageBackendS3 {
+ if err := downloadBackupFileFromCloud(ctx, server, backup.Path, backupAbsPathLocal); err != nil {
+ return nil, errors.Wrapf(err, "failed to download backup %q from S3", backup.Path)
+ }
+ defer os.Remove(backupAbsPathLocal)
+ replayBinlogPathList, err := downloadBinlogFilesFromCloud(ctx, server.s3Client, startBinlogInfo, *targetBinlogInfo, binlogDir)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to download binlog files from %s to %s from S3", startBinlogInfo.FileName, targetBinlogInfo.FileName)
+ }
+ defer func() {
+ for _, binlogPath := range replayBinlogPathList {
+ if err := os.Remove(binlogPath); err != nil {
+ log.Warn("Failed to remove downloaded local binlog file after PITR", zap.String("path", binlogPath))
+ }
+ }
+ }()
+ }
+
+ backupFile, err := os.Open(backupAbsPathLocal)
if err != nil {
- return nil, errors.Wrapf(err, "failed to open backup file %q", backupFileName)
+ return nil, errors.Wrapf(err, "failed to open backup file %q", backupAbsPathLocal)
}
defer backupFile.Close()
- log.Debug("Successfully opened backup file", zap.String("filename", backupFileName))
+ log.Debug("Successfully opened backup file", zap.String("filename", backupAbsPathLocal))
log.Debug("Start creating and restoring PITR database",
zap.String("instance", task.Instance.Name),
zap.String("database", task.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 BRANCH migration.
- startBinlogInfo := backup.Payload.BinlogInfo
- binlogDir := getBinlogAbsDir(server.profile.DataDir, task.Instance.ID)
if err := exec.updateProgress(ctx, mysqlTargetDriver, backupFile, startBinlogInfo, *targetBinlogInfo, binlogDir); err != nil {
return nil, errors.Wrap(err, "failed to setup progress update process")
}
if payload.DatabaseName != nil {
+ // case 1: PITR to a new database.
if err := mysqlTargetDriver.RestoreBackupToDatabase(ctx, backupFile, *payload.DatabaseName); err != nil {
log.Error("failed to restore full backup in the new database",
zap.Int("issueID", issue.ID),
@@ -262,6 +281,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *
return nil, errors.Wrap(err, "failed to perform a PITR restore in the new database")
}
} else {
+ // case 2: in-place PITR.
if err := mysqlTargetDriver.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),
@@ -288,6 +308,21 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, server *
}, nil
}
+func downloadBinlogFilesFromCloud(ctx context.Context, client *bbs3.Client, startBinlogInfo, targetBinlogInfo api.BinlogInfo, binlogDir string) ([]string, error) {
+ replayBinlogPathList, err := mysql.GetBinlogReplayList(startBinlogInfo, targetBinlogInfo, binlogDir)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to get binlog replay list in directory %s", binlogDir)
+ }
+ for _, binlogFilePath := range replayBinlogPathList {
+ // Use path.Join to compose a path on cloud which always uses / as the separator.
+ filePathOnCloud := path.Join(common.GetBinlogRelativeDir(binlogDir), filepath.Base(binlogFilePath))
+ if err := client.DownloadFileFromCloud(ctx, binlogFilePath, filePathOnCloud); err != nil {
+ return nil, errors.Wrapf(err, "failed to download binlog file %s from the cloud storage", binlogFilePath)
+ }
+ }
+ return replayBinlogPathList, nil
+}
+
func (*PITRRestoreTaskExecutor) doRestoreInPlacePostgres(ctx context.Context, server *Server, issue *api.Issue, task *api.Task, payload api.TaskDatabasePITRRestorePayload) (*api.TaskRunResultPayload, error) {
if payload.BackupID == nil {
return nil, errors.Errorf("PITR for Postgres is not implemented")