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): sync binlog (#1327)
h3n4l7acd7e4c9e76
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex fbba77efd0..d2a605034a 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -52,6 +52,12 @@ type BinlogInfo struct {Position int64 `json:"position"`}+// BinlogFile is the metadata of the MySQL binlog file+type BinlogFile struct {+ Name string+ Size int64+}+// This is encoded in JSON and stored in the backup table, representing PITR related info.type backupPayload struct {BinlogInfo BinlogInfo `json:"binlogInfo"`diff --git a/plugin/restore/mysql/mysql.go b/plugin/restore/mysql/mysql.goindex ce7e00956a..bd5af95b35 100644--- a/plugin/restore/mysql/mysql.go+++ b/plugin/restore/mysql/mysql.go@@ -4,11 +4,19 @@ import ("bufio""context""fmt"+ "io/ioutil"+ "os"+ "os/exec"+ "path/filepath""strings"- "github.com/bytebase/bytebase/plugin/db/mysql"+ "github.com/bytebase/bytebase/api"+ mysql "github.com/bytebase/bytebase/plugin/db/mysql")+// TODO(zp): refactor this when sure the mysqlbinlog path+var mysqlbinlogBinPath = "UNKNOWN"+const (// MaxDatabaseNameLength is the allowed max database name length in MySQLMaxDatabaseNameLength = 64@@ -144,6 +152,159 @@ func getPITROldDatabaseName(database string, suffixTs int64) string {return getSafeName(database, suffix)}+// SyncArchivedBinlogFiles syncs the binlogs between the instance and `saveDir`,+// but exclude latest binlog. We will download the latest binlog only when doing PITR.+func (r *Restore) SyncArchivedBinlogFiles(ctx context.Context, instance *api.Instance, saveDir string) error {+ binlogFilesLocal, err := ioutil.ReadDir(saveDir)+ if err != nil {+ return err+ }++ binlogFilesOnServer, err := r.getBinlogFilesMetaOnServer(ctx)+ if err != nil {+ return err+ }++ latestBinlogFileOnServer, err := r.getLatestBinlogFileMeta(ctx)+ if err != nil {+ return err+ }++ // build a local file size map from file name to size+ localFileMap := make(map[string]int64)++ for _, localFile := range binlogFilesLocal {+ localFileMap[localFile.Name()] = localFile.Size()+ }++ todo := make(map[string]bool)++ for _, serverBinlog := range binlogFilesOnServer {+ // 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+ if err := os.Remove(filepath.Join(saveDir, 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 binlogFilesOnServer {+ if _, ok := todo[serverFile.Name]; !ok {+ continue+ }+ if err := r.downloadBinlogFile(ctx, instance, saveDir, serverFile); err != nil {+ return fmt.Errorf("cannot sync binlog %s, error: %w", serverFile.Name, err)+ }+ }++ return nil+}++// SyncLatestBinlog syncs the latest binlog between the instance and `saveDir`+func (r *Restore) SyncLatestBinlog(ctx context.Context, instance *api.Instance, saveDir string) error {+ latestBinlogFileOnServer, err := r.getLatestBinlogFileMeta(ctx)+ if err != nil {+ return err+ }+ return r.downloadBinlogFile(ctx, instance, saveDir, *latestBinlogFileOnServer)+}++// downloadBinlogFile syncs the binlog specified by `meta` between the instance and local.+func (r *Restore) downloadBinlogFile(ctx context.Context, instance *api.Instance, saveDir string, binlog mysql.BinlogFile) error {+ // for mysqlbinlog binary, --result-file must end with '/'+ resultFileDir := strings.TrimRight(saveDir, "/") + "/"+ // TODO(zp): support ssl?+ cmd := exec.CommandContext(ctx, filepath.Join(mysqlbinlogBinPath, "bin", "mysqlbinlog"),+ binlog.Name,+ fmt.Sprintf("--read-from-remote-server --host=%s --port=%s --user=%s --password=%s", instance.Host, instance.Port, instance.Username, instance.Password),+ "--raw",+ fmt.Sprintf("--result-file=%s", resultFileDir),+ )+ cmd.Stdout = os.Stderr+ cmd.Stderr = os.Stderr++ resultFilePath := filepath.Join(resultFileDir, binlog.Name)+ if err := cmd.Run(); err != nil {+ _ = os.Remove(resultFilePath)+ return fmt.Errorf("cannot run mysqlbinlog, error: %w", err)+ }++ fi, 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)+ }++ return nil+}++// getBinlogFilesMetaOnServer returns the metadata of binlogs+func (r *Restore) getBinlogFilesMetaOnServer(ctx context.Context) ([]mysql.BinlogFile, error) {+ db, err := r.driver.GetDbConnection(ctx, "")+ if err != nil {+ return nil, err+ }++ rows, err := db.QueryContext(ctx, `SHOW BINARY LOGS;`)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var binlogFiles []mysql.BinlogFile+ for rows.Next() {+ var binlogFile mysql.BinlogFile+ var unused interface{}+ if err := rows.Scan(&binlogFile.Name, &binlogFile.Size, &unused /*Encrypted column*/); err != nil {+ return nil, err+ }+ binlogFiles = append(binlogFiles, binlogFile)+ }+ return binlogFiles, nil+}++// showLatestBinlogFile returns the metadata of latest binlog+func (r *Restore) getLatestBinlogFileMeta(ctx context.Context) (*mysql.BinlogFile, error) {+ //TODO(zp): refactor to reuse getBinlogInfo() in plugin/db/mysql.go+ db, err := r.driver.GetDbConnection(ctx, "")+ if err != nil {+ return nil, err+ }++ rows, err := db.QueryContext(ctx, `SHOW MASTER STATUS;`)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var binlogFile mysql.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 nil, err+ }+ return &binlogFile, nil+ }+ return nil, fmt.Errorf("cannot find latest binlog on instance")+}+func getSafeName(baseName, suffix string) string {name := fmt.Sprintf("%s_%s", baseName, suffix)if len(name) <= MaxDatabaseNameLength {