Skip to content

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

feat(PITR): write binlog metadata file on downloading (#2330)

Yilong Li7479fc3bb009
diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.go
index bd4c6b7366..926ce990f6 100644
--- a/plugin/db/mysql/restore.go
+++ b/plugin/db/mysql/restore.go
@@ -12,8 +12,10 @@ import (
"bytes"
"context"
"database/sql"
+ "encoding/json"
"fmt"
"io"
+ "io/fs"
"io/ioutil"
"math"
"os"
@@ -49,6 +51,9 @@ const (
// LetterCaseOnDiskLowerCaseCmp stores table and database names are stored on disk using the letter case specified in the CREATE TABLE or CREATE DATABASE statement, but MySQL converts them to lowercase on lookup.
// Name comparisons are not case-sensitive.
LetterCaseOnDiskLowerCaseCmp = 2
+
+ // binlog metadata file suffix.
+ binlogMetaSuffix = ".meta"
)
// BinlogFile is the metadata of the MySQL binlog file.
@@ -92,6 +97,10 @@ func newBinlogCoordinate(binlogFileName string, pos int64) (binlogCoordinate, er
return binlogCoordinate{Seq: seq, Pos: pos}, nil
}
+type binlogFileMeta struct {
+ FirstEventTs int64 `json:"first_event_ts"`
+}
+
// ReplayBinlog replays the binlog for `originDatabase` from `startBinlogInfo.Position` to `targetTs`, read binlog from `driver.binlogDir``.
func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, targetDatabase string, startBinlogInfo api.BinlogInfo, targetTs int64) error {
return driver.replayBinlogReadFromDir(ctx, originalDatabase, targetDatabase, startBinlogInfo, targetTs, driver.binlogDir)
@@ -248,7 +257,7 @@ func GetBinlogReplayList(startBinlogInfo api.BinlogInfo, binlogDir string) ([]st
var binlogFilesToReplay []BinlogFile
for _, f := range binlogFiles {
- if f.IsDir() {
+ if strings.HasSuffix(f.Name(), binlogMetaSuffix) {
continue
}
binlogFile, err := newBinlogFile(f.Name(), f.Size())
@@ -471,7 +480,11 @@ func (driver *Driver) GetSortedLocalBinlogFiles() ([]BinlogFile, error) {
return nil, err
}
var binlogFilesLocal []BinlogFile
+ // TODO(dragonly): Get binlog files according to the metadata files.
for _, fileInfo := range binlogFilesInfoLocal {
+ if strings.HasSuffix(fileInfo.Name(), binlogMetaSuffix) {
+ continue
+ }
binlogFile, err := newBinlogFile(fileInfo.Name(), fileInfo.Size())
if err != nil {
return nil, err
@@ -548,7 +561,7 @@ func (driver *Driver) FetchAllBinlogFiles(ctx context.Context, downloadLatestBin
}
log.Debug("Got sorted binlog file list on server", zap.Array("list", ZapBinlogFiles(binlogFilesOnServerSorted)))
- // Read the local binlog files.
+ // Read the local binlog metadata files.
binlogFilesLocalSorted, err := driver.GetSortedLocalBinlogFiles()
if err != nil {
return errors.Wrap(err, "failed to read local binlog files")
@@ -563,7 +576,7 @@ func (driver *Driver) FetchAllBinlogFiles(ctx context.Context, downloadLatestBin
// the file size is larger or equal to the binlog file size we queried from the MySQL server earlier.
func (driver *Driver) downloadBinlogFile(ctx context.Context, binlogFileToDownload BinlogFile, isLast bool) error {
// for mysqlbinlog binary, --result-file must end with '/'
- resultFileDir := strings.TrimRight(driver.binlogDir, "/") + "/"
+ mysqlbinlogResultFileDir := strings.TrimRight(driver.binlogDir, "/") + "/"
// TODO(zp): support ssl?
args := []string{
binlogFileToDownload.Name,
@@ -573,7 +586,7 @@ func (driver *Driver) downloadBinlogFile(ctx context.Context, binlogFileToDownlo
"--raw",
"--host", driver.connCfg.Host,
"--user", driver.connCfg.Username,
- "--result-file", resultFileDir,
+ "--result-file", mysqlbinlogResultFileDir,
}
if driver.connCfg.Port != "" {
args = append(args, "--port", driver.connCfg.Port)
@@ -587,17 +600,17 @@ func (driver *Driver) downloadBinlogFile(ctx context.Context, binlogFileToDownlo
cmd.Stderr = os.Stderr
log.Debug("Downloading binlog files using mysqlbinlog", zap.String("cmd", cmd.String()))
- resultFilePath := filepath.Join(resultFileDir, binlogFileToDownload.Name)
+ binlogFilePath := filepath.Join(driver.binlogDir, binlogFileToDownload.Name)
if err := cmd.Run(); err != nil {
log.Error("Failed to execute mysqlbinlog binary", zap.Error(err))
return errors.Wrap(err, "failed to execute mysqlbinlog binary")
}
- log.Debug("Checking downloaded binlog file stat", zap.String("path", resultFilePath))
- fileInfo, err := os.Stat(resultFilePath)
+ log.Debug("Checking downloaded binlog file stat", zap.String("path", binlogFilePath))
+ fileInfo, err := os.Stat(binlogFilePath)
if err != nil {
- log.Error("Failed to get stat of the binlog file.", zap.String("path", resultFilePath), zap.Error(err))
- return errors.Wrapf(err, "failed to get stat of the binlog file %q", resultFilePath)
+ log.Error("Failed to get stat of the binlog file.", zap.String("path", binlogFilePath), zap.Error(err))
+ return errors.Wrapf(err, "failed to get stat of the binlog file %q", binlogFilePath)
}
if !isLast && fileInfo.Size() != binlogFileToDownload.Size {
log.Error("Downloaded archived binlog file size is not equal to size queried on the MySQL server earlier.",
@@ -605,9 +618,36 @@ func (driver *Driver) downloadBinlogFile(ctx context.Context, binlogFileToDownlo
zap.Int64("sizeInfo", binlogFileToDownload.Size),
zap.Int64("downloadedSize", fileInfo.Size()),
)
- return errors.Errorf("downloaded archived binlog file %q size %d is not equal to size %d queried on MySQL server earlier", resultFilePath, fileInfo.Size(), binlogFileToDownload.Size)
+ return errors.Errorf("downloaded archived binlog file %q size %d is not equal to size %d queried on MySQL server earlier", binlogFilePath, fileInfo.Size(), binlogFileToDownload.Size)
}
+ if err := driver.writeBinlogMetadataFile(ctx, fileInfo); err != nil {
+ return errors.Wrapf(err, "failed to write binlog metadata file for binlog file %q", binlogFilePath)
+ }
+
+ return nil
+}
+
+func (driver *Driver) writeBinlogMetadataFile(ctx context.Context, binlogFileInfo fs.FileInfo) error {
+ eventTs, err := driver.parseLocalBinlogFirstEventTs(ctx, binlogFileInfo.Name())
+ if err != nil {
+ return errors.Wrapf(err, "failed to parse the local binlog file %q's first binlog event ts", binlogFileInfo.Name())
+ }
+ metadataFilePath := filepath.Join(driver.binlogDir, binlogFileInfo.Name()+".meta")
+ metadataFile, err := os.Create(metadataFilePath)
+ if err != nil {
+ return errors.Wrapf(err, "failed to create binlog metadata file %q", metadataFilePath)
+ }
+ metadata := binlogFileMeta{
+ FirstEventTs: eventTs,
+ }
+ metadataBytes, err := json.Marshal(metadata)
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal binlog metadata %+v", metadata)
+ }
+ if _, err := metadataFile.Write(metadataBytes); err != nil {
+ return errors.Wrapf(err, "failed to write binlog metadata file %q", metadataFilePath)
+ }
return nil
}
diff --git a/plugin/db/mysql/restore_test.go b/plugin/db/mysql/restore_test.go
index 07108e6b2f..7fef92c3df 100644
--- a/plugin/db/mysql/restore_test.go
+++ b/plugin/db/mysql/restore_test.go
@@ -177,23 +177,13 @@ func TestGetBinlogFileNameSeqNumber(t *testing.T) {
func TestGetReplayBinlogPathList(t *testing.T) {
a := require.New(t)
tests := []struct {
- subDirNames []string
binlogFileNames []string
startBinlogInfo api.BinlogInfo
expect []string
err bool
}{
- {
- // Test skip directory
- subDirNames: []string{"subdir_a", "subdir_b"},
- binlogFileNames: []string{},
- startBinlogInfo: api.BinlogInfo{},
- expect: []string{},
- err: false,
- },
{
// Test skip stale binlog
- subDirNames: []string{},
binlogFileNames: []string{"binlog.000001", "binlog.000002", "binlog.000003"},
startBinlogInfo: api.BinlogInfo{
FileName: "binlog.000002",
@@ -203,8 +193,7 @@ func TestGetReplayBinlogPathList(t *testing.T) {
err: false,
},
{
- // Test binlogs no hole
- subDirNames: []string{},
+ // Test binlog files no hole
binlogFileNames: []string{"binlog.000001", "binlog.000002", "binlog.000004"},
startBinlogInfo: api.BinlogInfo{
FileName: "binlog.000002",
@@ -215,7 +204,6 @@ func TestGetReplayBinlogPathList(t *testing.T) {
},
{
// Test mysql-bin prefix
- subDirNames: []string{},
binlogFileNames: []string{"mysql-bin.000001", "mysql-bin.000002", "mysql-bin.000003"},
startBinlogInfo: api.BinlogInfo{
FileName: "bin.000001",
@@ -226,7 +214,6 @@ func TestGetReplayBinlogPathList(t *testing.T) {
},
{
// Test out of binlog.999999
- subDirNames: []string{},
binlogFileNames: []string{"binlog.999999", "binlog.1000000", "binlog.1000001"},
startBinlogInfo: api.BinlogInfo{
FileName: "binlog.999999",
@@ -235,26 +222,11 @@ func TestGetReplayBinlogPathList(t *testing.T) {
expect: []string{"binlog.999999", "binlog.1000000", "binlog.1000001"},
err: false,
},
- {
- subDirNames: []string{"sub_dir"},
- binlogFileNames: []string{"binlog.000001", "binlog.000002", "binlog.000003"},
- startBinlogInfo: api.BinlogInfo{
- FileName: "binlog.000002",
- Position: 0xdeadbeaf,
- },
- expect: []string{"binlog.000002", "binlog.000003"},
- err: false,
- },
}
for _, test := range tests {
tmpDir := t.TempDir()
- for _, subDir := range test.subDirNames {
- err := os.MkdirAll(filepath.Join(tmpDir, subDir), os.ModePerm)
- a.NoError(err)
- }
-
for _, binlogFileName := range test.binlogFileNames {
f, err := os.Create(filepath.Join(tmpDir, binlogFileName))
a.NoError(err)
diff --git a/server/backup_runner.go b/server/backup_runner.go
index 3aaf54c63e..ca9f5528f7 100644
--- a/server/backup_runner.go
+++ b/server/backup_runner.go
@@ -147,6 +147,7 @@ func (r *BackupRunner) getMaxRetentionPeriodTsForMySQLInstance(ctx context.Conte
return maxRetentionPeriodTs, nil
}
+// TODO(dragonly): Remove metadata as well.
func (r *BackupRunner) purgeBinlogFiles(instanceID, retentionPeriodTs int) error {
binlogDir := getBinlogAbsDir(r.server.profile.DataDir, instanceID)
binlogFileInfoList, err := ioutil.ReadDir(binlogDir)
@@ -155,7 +156,6 @@ func (r *BackupRunner) purgeBinlogFiles(instanceID, retentionPeriodTs int) error
}
for _, binlogFileInfo := range binlogFileInfoList {
if _, err := mysql.GetBinlogNameSeq(binlogFileInfo.Name()); err != nil {
- log.Warn("Found an irregular file in binlog directory.", zap.String("path", binlogFileInfo.Name()))
continue // next binlog file
}
// We use modification time of local binlog files which is later than the modification time of that on the MySQL server,