Skip to content

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

feat(binlog): use a counting reader for progress estimation (#2024)

Yilong Lie7d8f259c469
diff --git a/common/counting_reader.go b/common/counting_reader.go
new file mode 100644
index 0000000000..c73ed63ab7
--- /dev/null
+++ b/common/counting_reader.go
@@ -0,0 +1,42 @@
+package common
+
+import (
+ "io"
+ "sync/atomic"
+)
+
+var (
+ _ io.Reader = (*CountingReader)(nil)
+)
+
+// CountingReader is a reader that counts the read bytes in a thread safe way.
+type CountingReader struct {
+ r io.Reader
+ count int64
+}
+
+// NewCountingReader creates a new CountingReader from an existing io.Reader.
+func NewCountingReader(r io.Reader) *CountingReader {
+ return &CountingReader{r: r}
+}
+
+// Read implements the io.Reader interface.
+func (r *CountingReader) Read(buf []byte) (int, error) {
+ n, err := r.r.Read(buf)
+ // Read() should always return a non-negative `n`.
+ // But since `n` is a signed integer, some custom
+ // implementation of an io.Reader may return negative
+ // values.
+ //
+ // Excluding such invalid values from counting,
+ // thus `if n >= 0`:
+ if n >= 0 {
+ atomic.AddInt64(&r.count, int64(n))
+ }
+ return n, err
+}
+
+// Count returns the number of read bytes.
+func (r *CountingReader) Count() int64 {
+ return atomic.LoadInt64(&r.count)
+}
diff --git a/common/util.go b/common/util.go
index ba8b1d8043..06e3980b54 100644
--- a/common/util.go
+++ b/common/util.go
@@ -3,6 +3,7 @@ package common
import (
"crypto/rand"
"math/big"
+ "os"
"path"
"regexp"
"sort"
@@ -92,3 +93,16 @@ func ParseTemplateTokens(template string) ([]string, []string) {
}
return nil, nil
}
+
+// GetFileSizeSum calculates the sum of file sizes for file names in the list.
+func GetFileSizeSum(fileNameList []string) (int64, error) {
+ var sum int64
+ for _, fileName := range fileNameList {
+ stat, err := os.Stat(fileName)
+ if err != nil {
+ return 0, err
+ }
+ sum += stat.Size()
+ }
+ return sum, nil
+}
diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.go
index 68f94c40bd..de966762b8 100644
--- a/plugin/db/mysql/mysql.go
+++ b/plugin/db/mysql/mysql.go
@@ -34,6 +34,8 @@ type Driver struct {
resourceDir string
binlogDir string
db *sql.DB
+
+ replayBinlogCounter *common.CountingReader
}
func newDriver(dc db.DriverConfig) db.Driver {
diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.go
index a23d18a76d..cbadbf10bf 100644
--- a/plugin/db/mysql/restore.go
+++ b/plugin/db/mysql/restore.go
@@ -100,7 +100,7 @@ func (driver *Driver) SetUpForPITR(binlogDir string) {
// ReplayBinlog replays the binlog for `originDatabase` from `startBinlogInfo.Position` to `targetTs`.
func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, pitrDatabase string, startBinlogInfo api.BinlogInfo, targetTs int64) error {
- replayBinlogPaths, err := getBinlogReplayList(startBinlogInfo, driver.binlogDir)
+ replayBinlogPaths, err := GetBinlogReplayList(startBinlogInfo, driver.binlogDir)
if err != nil {
return err
}
@@ -173,9 +173,11 @@ func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, pitrDa
mysqlbinlogCmd.Stderr = os.Stderr
+ countingReader := common.NewCountingReader(mysqlRead)
mysqlCmd.Stderr = os.Stderr
mysqlCmd.Stdout = os.Stderr
- mysqlCmd.Stdin = mysqlRead
+ mysqlCmd.Stdin = countingReader
+ driver.replayBinlogCounter = countingReader
if err := mysqlbinlogCmd.Start(); err != nil {
return fmt.Errorf("cannot start mysqlbinlog command, error: %w", err)
@@ -191,6 +193,14 @@ func (driver *Driver) replayBinlog(ctx context.Context, originalDatabase, pitrDa
return nil
}
+// GetReplayedBinlogBytes gets the replayed binlog bytes.
+func (driver *Driver) GetReplayedBinlogBytes() int64 {
+ if driver.replayBinlogCounter == nil {
+ return 0
+ }
+ return driver.replayBinlogCounter.Count()
+}
+
// RestorePITR is a wrapper to perform PITR. It restores a full backup followed by replaying the binlog.
// It performs the step 1 of the restore process.
// TODO(dragonly): Refactor so that the first part is in driver.Restore, and remove this wrapper.
@@ -242,8 +252,8 @@ func (driver *Driver) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner
return nil
}
-// getBinlogReplayList returns the path list of the binlog that need be replayed.
-func getBinlogReplayList(startBinlogInfo api.BinlogInfo, binlogDir string) ([]string, error) {
+// GetBinlogReplayList returns the path list of the binlog that need be replayed.
+func GetBinlogReplayList(startBinlogInfo api.BinlogInfo, binlogDir string) ([]string, error) {
startBinlogSeq, err := GetBinlogNameSeq(startBinlogInfo.FileName)
if err != nil {
return nil, fmt.Errorf("cannot parse the start binlog file name %q, error: %w", startBinlogInfo.FileName, err)
diff --git a/plugin/db/mysql/restore_test.go b/plugin/db/mysql/restore_test.go
index c26d343ed5..8eb7858a73 100644
--- a/plugin/db/mysql/restore_test.go
+++ b/plugin/db/mysql/restore_test.go
@@ -261,7 +261,7 @@ func TestGetReplayBinlogPathList(t *testing.T) {
a.NoError(err)
}
- result, err := getBinlogReplayList(test.startBinlogInfo, tmpDir)
+ result, err := GetBinlogReplayList(test.startBinlogInfo, tmpDir)
if test.err {
a.Error(err)
} else {
diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.go
index 94f5698ccf..202ec2e769 100644
--- a/server/task_executor_pitr_restore.go
+++ b/server/task_executor_pitr_restore.go
@@ -26,6 +26,7 @@ func NewPITRRestoreTaskExecutor() TaskExecutor {
// PITRRestoreTaskExecutor is the PITR restore task executor.
type PITRRestoreTaskExecutor struct {
completed int32
+ progress atomic.Value // api.Progress
}
// RunOnce will run the PITR restore task executor once.
@@ -62,11 +63,15 @@ func (exec *PITRRestoreTaskExecutor) IsCompleted() bool {
}
// GetProgress returns the task progress.
-func (*PITRRestoreTaskExecutor) GetProgress() api.Progress {
- return api.Progress{}
+func (exec *PITRRestoreTaskExecutor) GetProgress() api.Progress {
+ progress := exec.progress.Load()
+ if progress == nil {
+ return api.Progress{}
+ }
+ return progress.(api.Progress)
}
-func (*PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Task, store *store.Store, driver db.Driver, dataDir string, targetTs int64, mode common.ReleaseMode) error {
+func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Task, store *store.Store, driver db.Driver, dataDir string, targetTs int64, mode common.ReleaseMode) error {
instance := task.Instance
database := task.Database
@@ -113,7 +118,7 @@ func (*PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Tas
backupFileName := getBackupAbsFilePath(dataDir, backup.DatabaseID, backup.Name)
backupFile, err := os.OpenFile(backupFileName, os.O_RDONLY, os.ModePerm)
if err != nil {
- return fmt.Errorf("failed to open backup file: %s, error: %w", backupFileName, err)
+ return fmt.Errorf("failed to open backup file %q, error: %w", backupFileName, err)
}
defer backupFile.Close()
log.Debug("Successfully opened backup file", zap.String("filename", backupFileName))
@@ -126,6 +131,11 @@ func (*PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Tas
// 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 BASELINE migration.
startBinlogInfo := backup.Payload.BinlogInfo
+
+ if err := exec.updateProgress(ctx, mysqlDriver, backupFile, startBinlogInfo, binlogDir); err != nil {
+ return fmt.Errorf("failed to setup progress update process, error: %w", err)
+ }
+
if err := mysqlDriver.RestorePITR(ctx, bufio.NewScanner(backupFile), startBinlogInfo, database.Name, issue.CreatedTs, targetTs); err != nil {
log.Error("failed to perform a PITR restore in the PITR database",
zap.Int("issueID", issue.ID),
@@ -137,6 +147,53 @@ func (*PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Tas
return 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 {
+ return fmt.Errorf("failed to get stat of backup file %q, error: %w", backupFile.Name(), err)
+ }
+ backupFileBytes := backupFileInfo.Size()
+ replayBinlogPaths, err := mysql.GetBinlogReplayList(startBinlogInfo, binlogDir)
+ if err != nil {
+ return fmt.Errorf("failed to get binlog replay list with startBinlogInfo %+v in binlog directory %q, error: %w", startBinlogInfo, binlogDir, err)
+ }
+ totalBinlogBytes, err := common.GetFileSizeSum(replayBinlogPaths)
+ if err != nil {
+ return fmt.Errorf("failed to get file size sum of replay binlog files, error: %w", err)
+ }
+
+ go func() {
+ ticker := time.NewTicker(1 * time.Second)
+ defer ticker.Stop()
+ createdTs := time.Now().Unix()
+ exec.progress.Store(api.Progress{
+ TotalUnit: backupFileBytes + totalBinlogBytes,
+ CompletedUnit: 0,
+ CreatedTs: createdTs,
+ UpdatedTs: createdTs,
+ })
+ for {
+ select {
+ case <-ticker.C:
+ progressPrev := exec.progress.Load().(api.Progress)
+ // TODO(dragonly): Calculate restored backup bytes when using mysqldump.
+ restoredBackupFileBytes := backupFileBytes
+ replayedBinlogBytes := driver.GetReplayedBinlogBytes()
+ exec.progress.Store(api.Progress{
+ TotalUnit: progressPrev.TotalUnit,
+ CompletedUnit: restoredBackupFileBytes + replayedBinlogBytes,
+ CreatedTs: progressPrev.CreatedTs,
+ UpdatedTs: time.Now().Unix(),
+ })
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+
+ return nil
+}
+
func getIssueByPipelineID(ctx context.Context, store *store.Store, pid int) (*api.Issue, error) {
issue, err := store.GetIssueByPipelineID(ctx, pid)
if err != nil {