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): download binlog files (#1547)
Yilong Li2f8d313fe786
diff --git a/plugin/restore/mysql/mysql.go b/plugin/restore/mysql/mysql.goindex 816fba1f29..3e1cc9d644 100644--- a/plugin/restore/mysql/mysql.go+++ b/plugin/restore/mysql/mysql.go@@ -264,7 +264,6 @@ func sortBinlogFiles(binlogFiles []BinlogFile) []BinlogFile {// Locate the binlog event at (filename, position), parse the event and return its timestamp.// The current mechanism is by invoking mysqlbinlog and parse the output string.// Maybe we should parse the raw binlog header to get better documented structure?-// nolintfunc (r *Restore) parseLocalBinlogEventTimestamp(ctx context.Context, binlogInfo api.BinlogInfo) (int64, error) {args := []string{path.Join(r.binlogDir, binlogInfo.FileName),@@ -495,7 +494,8 @@ func getPITROldDatabaseName(database string, suffixTs int64) string {return getSafeName(database, suffix)}-func getSortedLocalBinlogFiles(binlogDir string) ([]BinlogFile, error) {+// GetSortedLocalBinlogFiles returns a sorted BinlogFile list in the given binlog dir.+func GetSortedLocalBinlogFiles(binlogDir string) ([]BinlogFile, error) {binlogFilesInfoLocal, err := ioutil.ReadDir(binlogDir)if err != nil {return nil, err@@ -520,85 +520,67 @@ func binlogFilesAreContinuous(files []BinlogFile) bool {return true}-// FetchArchivedBinlogFiles downloads the missing binlog files from the remote instance to `binlogDir`,-// but exclude latest binlog. We may download the latest binlog only when doing PITR.-func (r *Restore) FetchArchivedBinlogFiles(ctx context.Context) error {+// Download binlog files on server.+func (r *Restore) downloadBinlogFilesOnServer(ctx context.Context, binlogFilesLocal, binlogFilesOnServerSorted []BinlogFile) error {+ if len(binlogFilesOnServerSorted) == 0 {+ log.Debug("No binlog file found on server to download")+ return nil+ }+ latestBinlogFileOnServer := binlogFilesOnServerSorted[len(binlogFilesOnServerSorted)-1]+ binlogFilesLocalMap := make(map[string]BinlogFile)+ for _, file := range binlogFilesLocal {+ binlogFilesLocalMap[file.Name] = file+ }+ log.Debug("Downloading binlog files", zap.Array("fileList", ZapBinlogFiles(binlogFilesOnServerSorted)))+ for _, fileOnServer := range binlogFilesOnServerSorted {+ fileLocal, existLocal := binlogFilesLocalMap[fileOnServer.Name]+ path := filepath.Join(r.binlogDir, fileOnServer.Name)+ if !existLocal {+ if err := r.downloadBinlogFile(ctx, fileOnServer, fileOnServer.Name == latestBinlogFileOnServer.Name); err != nil {+ log.Error("Failed to download binlog file", zap.String("path", path), zap.Error(err))+ return fmt.Errorf("failed to download binlog file[%s], error[%w]", path, err)+ }+ } else if fileLocal.Size != fileOnServer.Size {+ log.Debug("Deleting inconsistent local binlog file",+ zap.String("path", path),+ zap.Int64("sizeLocal", fileOnServer.Size),+ zap.Int64("sizeOnServer", fileOnServer.Size))+ if err := os.Remove(path); err != nil {+ log.Error("Failed to remove inconsistent local binlog file", zap.String("path", path), zap.Error(err))+ return fmt.Errorf("failed to remove inconsistent local binlog file[%s], error[%w]", path, err)+ }+ if err := r.downloadBinlogFile(ctx, fileOnServer, fileOnServer.Name == latestBinlogFileOnServer.Name); err != nil {+ log.Error("Failed to re-download inconsistent local binlog file", zap.String("path", path), zap.Error(err))+ return fmt.Errorf("failed to re-download inconsistent local binlog file[%s], error[%w]", path, err)+ }+ }+ }+ return nil+}++// FetchAllBinlogFiles downloads all binlog files on server to `binlogDir`.+func (r *Restore) FetchAllBinlogFiles(ctx context.Context) error {// Read binlog files list on server.binlogFilesOnServerSorted, err := r.GetSortedBinlogFilesMetaOnServer(ctx)if err != nil {return err}if len(binlogFilesOnServerSorted) == 0 {- // No binlog files on server, so there's nothing to download.- log.Debug("No binlog file found on server")+ log.Debug("No binlog file found on server to download")return nil}- latestBinlogFileOnServer := binlogFilesOnServerSorted[len(binlogFilesOnServerSorted)-1]log.Debug("Got sorted binlog file list on server", zap.Array("list", ZapBinlogFiles(binlogFilesOnServerSorted)))// Read the local binlog files.- binlogFilesLocalSorted, err := getSortedLocalBinlogFiles(r.binlogDir)+ binlogFilesLocalSorted, err := GetSortedLocalBinlogFiles(r.binlogDir)if err != nil {return fmt.Errorf("failed to read local binlog files, error[%w]", err)}- // build a local file size map from file name to size- localFileMap := make(map[string]int64)- for _, localFile := range binlogFilesLocalSorted {- localFileMap[localFile.Name] = localFile.Size- }-- todo := make(map[string]bool)-- for _, serverBinlog := range binlogFilesOnServerSorted {- // We don't download the latest binlog in SyncArchivedBinlogFiles()- if serverBinlog.Name == latestBinlogFileOnServer.Name {- continue- }-- localBinlogSize, ok := localFileMap[serverBinlog.Name]- if !ok {- todo[serverBinlog.Name] = true- continue- }-- if localBinlogSize != serverBinlog.Size {- // exist on local and file size not match, delete and then download it- log.Warn("inconsistent binlog file size detected", zap.String("binlogFile", serverBinlog.Name), zap.Int64("server", serverBinlog.Size), zap.Int64("local", localBinlogSize))- if err := os.Remove(filepath.Join(r.binlogDir, serverBinlog.Name)); err != nil {- return fmt.Errorf("cannot remove %s, error: %w", serverBinlog.Name, err)- }- todo[serverBinlog.Name] = true- }- }-- // download the binlog files not recorded in downloadedIndex- for _, serverFile := range binlogFilesOnServerSorted {- if _, ok := todo[serverFile.Name]; !ok {- continue- }- if err := r.downloadBinlogFile(ctx, serverFile, false); err != nil {- return fmt.Errorf("cannot sync binlog %s, error: %w", serverFile.Name, err)- }- }- return nil+ return r.downloadBinlogFilesOnServer(ctx, binlogFilesLocalSorted, binlogFilesOnServerSorted)}-// 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- }- latestBinlogFileOnServer, err := r.getLatestBinlogFileMeta(ctx)- if err != nil {- return err- }- return r.downloadBinlogFile(ctx, latestBinlogFileOnServer, true)-}--// downloadBinlogFile syncs the binlog specified by `meta` between the instance and local.+// Syncs the binlog specified by `meta` between the instance and local.// 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.@@ -698,31 +680,6 @@ func (r *Restore) GetSortedBinlogFilesMetaOnServer(ctx context.Context) ([]Binloreturn sortBinlogFiles(binlogFiles), nil}-// showLatestBinlogFile returns the metadata of latest binlog-func (r *Restore) getLatestBinlogFileMeta(ctx context.Context) (BinlogFile, error) {- // TODO(zp): refactor to reuse getBinlogInfo() in plugin/db/mysql.go- db, err := r.driver.GetDbConnection(ctx, "")- if err != nil {- return BinlogFile{}, err- }-- rows, err := db.QueryContext(ctx, `SHOW MASTER STATUS;`)- if err != nil {- return BinlogFile{}, err- }- defer rows.Close()-- var binlogFile BinlogFile- if 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 BinlogFile{}, err- }- return binlogFile, nil- }- return 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.// For example: ("binlog.000001") => 1, ("binlog000001") => errfunc getBinlogNameSeq(name string) (int64, error) {diff --git a/plugin/restore/mysql/mysql_test.go b/plugin/restore/mysql/mysql_test.goindex f0ba0b5989..b8e5760445 100644--- a/plugin/restore/mysql/mysql_test.go+++ b/plugin/restore/mysql/mysql_test.go@@ -415,6 +415,11 @@ func TestSortBinlogFiles(t *testing.T) {binlogFileNames: []BinlogFile{{Seq: 1}, {Seq: 7}, {Seq: 4}},expect: []BinlogFile{{Seq: 1}, {Seq: 4}, {Seq: 7}},},+ // Empty+ {+ binlogFileNames: []BinlogFile{},+ expect: []BinlogFile{},+ },}for _, test := range tests {diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex 30d0538d77..b33f2b8c70 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -91,9 +91,9 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apmysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlutil, connCfg, binlogDir)- log.Debug("Download all binlog files up to targetTs", zap.Time("targetTs", time.Unix(targetTs, 0)))+ log.Debug("Downloading all binlog files")// TODO(dragonly): Do this on a regular basis.- if err := mysqlRestore.IncrementalFetchAllBinlogFiles(ctx); err != nil {+ if err := mysqlRestore.FetchAllBinlogFiles(ctx); err != nil {return err}diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.goindex 994c1d8cf9..f1ffbd0fbc 100644--- a/tests/backup_restore_test.go+++ b/tests/backup_restore_test.go@@ -170,7 +170,7 @@ func TestPITR(t *testing.T) {binlogDir := t.TempDir()connCfg := getMySQLConnectionConfig(strconv.Itoa(mysqlPort), database)mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilInstance, connCfg, binlogDir)- err = mysqlRestore.IncrementalFetchAllBinlogFiles(ctx)+ err = mysqlRestore.FetchAllBinlogFiles(ctx)a.NoError(err)err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(backupDump), backupPayload.BinlogInfo, database, suffixTs, targetTs)a.NoError(err)@@ -249,7 +249,7 @@ func TestPITR(t *testing.T) {a.Equal(true, ok)binlogDir := t.TempDir()mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilInstance, connCfg, binlogDir)- err = mysqlRestore.IncrementalFetchAllBinlogFiles(ctx)+ err = mysqlRestore.FetchAllBinlogFiles(ctx)a.NoError(err)err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), backupPayload.BinlogInfo, database, suffixTs, targetTs)a.NoError(err)@@ -302,7 +302,7 @@ func TestPITR(t *testing.T) {a.Equal(true, ok)binlogDir := t.TempDir()mysqlRestore := restoremysql.New(mysqlDriver, mysqlutilInstance, connCfg, binlogDir)- err = mysqlRestore.IncrementalFetchAllBinlogFiles(ctx)+ err = mysqlRestore.FetchAllBinlogFiles(ctx)a.NoError(err)err = mysqlRestore.RestorePITR(ctx, bufio.NewScanner(buf), backupPayload.BinlogInfo, database, suffixTs, targetTs)a.NoError(err)diff --git a/tests/mysql_test.go b/tests/mysql_test.goindex e387d0b762..24a4b01270 100644--- a/tests/mysql_test.go+++ b/tests/mysql_test.go@@ -3,13 +3,21 @@ package testsimport ("context""fmt"+ "io/ioutil"+ "math/rand"+ "os"+ "path/filepath""strconv""testing"+ "time"+ "github.com/bytebase/bytebase/common/log"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""github.com/stretchr/testify/require"+ "go.uber.org/zap/zapcore")func TestCheckEngineInnoDB(t *testing.T) {@@ -120,3 +128,118 @@ func TestCheckServerVersionAndBinlogForPITR(t *testing.T) {err = mysqlRestore.CheckBinlogRowFormat(ctx)a.NoError(err)}++func TestFetchBinlogFiles(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ log.SetLevel(zapcore.DebugLevel)++ port := getTestPort(t.Name())+ _, stopFn := resourcemysql.SetupTestInstance(t, port)+ defer stopFn()++ db, err := connectTestMySQL(port, "")+ a.NoError(err)+ defer db.Close()++ driver, err := getTestMySQLDriver(ctx, strconv.Itoa(port), "")+ a.NoError(err)+ defer driver.Close(ctx)++ connCfg := getMySQLConnectionConfig(strconv.Itoa(port), "")+ mysqlDriver, ok := driver.(*pluginmysql.Driver)+ a.Equal(true, ok)+ utilDir := t.TempDir()+ utilInstance, err := mysqlutil.Install(utilDir)+ a.NoError(err)+ binlogDir := t.TempDir()+ mysqlRestore := restoremysql.New(mysqlDriver, utilInstance, connCfg, binlogDir)++ // init schema+ _, err = db.ExecContext(ctx, `+ CREATE DATABASE test;+ USE test;+ CREATE TABLE tbl (id int);+ `)+ a.NoError(err)++ // Rotate to create multiple binlog files for test.+ var startTsList []int64+ numRotate := 10+ // There'll be `numBinlogFiles` binlog files generated, and the last one contains no actual data.+ numBinlogFiles := numRotate + 1+ for i := 0; i < numRotate; i++ {+ // Record the start event ts of the current binlog file.+ startTsList = append(startTsList, time.Now().Unix())+ // Insert some data to grow the current binlog file.+ _, err = db.ExecContext(ctx, fmt.Sprintf(`+ USE test;+ INSERT INTO tbl VALUES (%d);+ `, i))+ a.NoError(err)+ // Rotate the binlog file.+ _, err = db.ExecContext(ctx, "FLUSH BINARY LOGS;")+ a.NoError(err)+ }+ t.Logf("startTsList: %v\n", startTsList)++ binlogFilesOnServerSorted, err := mysqlRestore.GetSortedBinlogFilesMetaOnServer(ctx)+ a.NoError(err)++ t.Log("Download binlog files in empty dir")+ binlogFilesBefore, err := ioutil.ReadDir(binlogDir)+ a.NoError(err)+ for _, file := range binlogFilesBefore {+ path := filepath.Join(binlogDir, file.Name())+ err = os.Remove(path)+ a.NoError(err)+ }+ err = mysqlRestore.FetchAllBinlogFiles(ctx)+ a.NoError(err)+ binlogFilesDownloaded, err := restoremysql.GetSortedLocalBinlogFiles(binlogDir)+ a.NoError(err)+ a.Equal(numBinlogFiles, len(binlogFilesDownloaded))+ for j := range binlogFilesDownloaded {+ a.Equal(binlogFilesOnServerSorted[j].Name, binlogFilesDownloaded[j].Name)+ a.Equal(binlogFilesOnServerSorted[j].Size, binlogFilesDownloaded[j].Size)+ }++ t.Log("Truncate or delete downloaded files and re-download")+ rand.Seed(time.Now().Unix())+ // Fetch and randomly truncate/delete some binlog files.t.Log("Clean up binlog dir")+ binlogFiles, err := ioutil.ReadDir(binlogDir)+ a.NoError(err)+ for _, file := range binlogFiles {+ path := filepath.Join(binlogDir, file.Name())+ err = os.Remove(path)+ a.NoError(err)+ }+ t.Log("Fetch binlog files")+ err = mysqlRestore.FetchAllBinlogFiles(ctx)+ a.NoError(err)+ binlogFilesDownloaded, err = restoremysql.GetSortedLocalBinlogFiles(binlogDir)+ a.NoError(err)+ t.Logf("Downloaded %d files to empty dir", len(binlogFilesDownloaded))+ truncateIndex := rand.Intn(numBinlogFiles)+ path := filepath.Join(binlogDir, binlogFilesDownloaded[truncateIndex].Name)+ t.Logf("Truncating file %s", binlogFilesDownloaded[truncateIndex].Name)+ err = os.Truncate(path, 1)+ a.NoError(err)+ deleteIndex := rand.Intn(numBinlogFiles)+ path = filepath.Join(binlogDir, binlogFilesDownloaded[deleteIndex].Name)+ t.Logf("Deleting file %s", binlogFilesDownloaded[deleteIndex].Name)+ err = os.Remove(path)+ a.NoError(err)+ // Re-download and check.+ t.Log("Re-downloading binlog files")+ err = mysqlRestore.FetchAllBinlogFiles(ctx)+ a.NoError(err)+ binlogFilesDownloadedAgain, err := restoremysql.GetSortedLocalBinlogFiles(binlogDir)+ a.NoError(err)+ a.Equal(numBinlogFiles, len(binlogFilesDownloadedAgain))+ for i := range binlogFilesDownloadedAgain {+ a.Equal(binlogFilesOnServerSorted[i].Name, binlogFilesDownloadedAgain[i].Name)+ a.Equal(binlogFilesOnServerSorted[i].Size, binlogFilesDownloadedAgain[i].Size)+ }+}diff --git a/tests/tests.go b/tests/tests.goindex f1320b9330..375c5023e4 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -131,6 +131,7 @@ func getTestPort(testName string) int {"TestPITR","TestCheckEngineInnoDB","TestCheckServerVersionAndBinlogForPITR",+ "TestFetchBinlogFiles","TestSchemaSystem",}