Skip to content

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

feat(PITR): implement GetBinlogCoordinateByTs() (#1573)

Yilong Liad502d280f18
diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.go
index 4fb17fad8a..903131bf2b 100644
--- a/plugin/db/mysql/restore.go
+++ b/plugin/db/mysql/restore.go
@@ -17,6 +17,7 @@ import (
"time"
"github.com/bytebase/bytebase/api"
+ "github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
"github.com/bytebase/bytebase/plugin/db"
"github.com/bytebase/bytebase/resources/mysqlutil"
@@ -679,6 +680,190 @@ func (r *Restore) GetSortedBinlogFilesMetaOnServer(ctx context.Context) ([]Binlo
return sortBinlogFiles(binlogFiles), nil
}
+// GetBinlogCoordinateByTs converts a timestamp to binlog coordinate using local binlog files.
+func (r *Restore) GetBinlogCoordinateByTs(ctx context.Context, targetTs int64) (*api.BinlogInfo, error) {
+ binlogFilesLocalSorted, err := GetSortedLocalBinlogFiles(r.binlogDir)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read sorted local binlog files, error: %w", err)
+ }
+ if len(binlogFilesLocalSorted) == 0 {
+ return nil, fmt.Errorf("no local binlog files found")
+ }
+ if !binlogFilesAreContinuous(binlogFilesLocalSorted) {
+ return nil, fmt.Errorf("local binlog files are not continuous")
+ }
+
+ var binlogFileTarget *BinlogFile
+ for i, file := range binlogFilesLocalSorted {
+ eventTs, err := r.parseLocalBinlogFirstEventTs(ctx, file.Name)
+ if err != nil {
+ return nil, fmt.Errorf("failed to parse the local binlog file %q's first binlog event ts, error: %w", file.Name, err)
+ }
+ if eventTs >= targetTs {
+ if i == 0 {
+ return nil, fmt.Errorf("the targetTs %d is before the first event ts %d of the oldest binlog file %q", targetTs, eventTs, file.Name)
+ }
+ // The previous local binlog file contains targetTs.
+ binlogFileTarget = &binlogFilesLocalSorted[i-1]
+ break
+ }
+ }
+ // All of the local binlog files' first event start ts <= targetTs, so we choose the last binlog file as probably "containing" targetTs.
+ // This may not be true, because possibly targetTs > last eventTs of the last binlog file.
+ // In this case, we should return an error.
+ var isLastBinlogFile bool
+ if binlogFileTarget == nil {
+ isLastBinlogFile = true
+ binlogFileTarget = &binlogFilesLocalSorted[len(binlogFilesLocalSorted)-1]
+ }
+
+ eventPos, err := r.getBinlogEventPositionAtOrAfterTs(ctx, *binlogFileTarget, targetTs)
+ if err != nil {
+ if common.ErrorCode(err) == common.NotFound {
+ // All the binlog events in this binlog file have ts < targetTs.
+ // If this is the last binlog file, the user wants to recover to a time in the future and we should return an error.
+ // Otherwise, we should return the end position of the current binlog file.
+ if isLastBinlogFile {
+ return nil, fmt.Errorf("the targetTs %d is after the last event ts of the latest binlog file %q", targetTs, binlogFileTarget.Name)
+ }
+ return &api.BinlogInfo{FileName: binlogFileTarget.Name, Position: math.MaxInt64}, nil
+ }
+ return nil, fmt.Errorf("failed to find the binlog event after targetTs %d, error: %w", targetTs, err)
+ }
+ return &api.BinlogInfo{FileName: binlogFileTarget.Name, Position: eventPos}, nil
+}
+
+func parseBinlogEventTsInLine(line string) (eventTs int64, found bool, err error) {
+ // The target line starts with string like "#220421 14:49:26 server id 1"
+ if !strings.Contains(line, "server id") {
+ return 0, false, nil
+ }
+ if strings.Contains(line, "end_log_pos 0") {
+ // https://github.com/mysql/mysql-server/blob/8.0/client/mysqlbinlog.cc#L1209-L1212
+ // Fake events with end_log_pos=0 could be generated and we need to ignore them.
+ return 0, false, nil
+ }
+ fields := strings.Fields(line)
+ // fields should starts with ["#220421", "14:49:26", "server", "id", "1", "end_log_pos", "34794"]
+ if len(fields) < 7 ||
+ (len(fields[0]) != 7 || len(fields[1]) != 8 || fields[2] != "server" || fields[3] != "id" || fields[5] != "end_log_pos") {
+ return 0, false, fmt.Errorf("found unexpected mysqlbinlog output line %q when parsing binlog event timestamp", line)
+ }
+ datetime, err := time.ParseInLocation("060102 15:04:05", fmt.Sprintf("%s %s", fields[0][1:], fields[1]), time.Local)
+ if err != nil {
+ return 0, false, err
+ }
+ return datetime.Unix(), true, nil
+}
+
+func parseBinlogEventPosInLine(line string) (pos int64, found bool, err error) {
+ // The mysqlbinlog output will contains a line starting with "# at 35065", which is the binlog event's start position.
+ if !strings.HasPrefix(line, "# at ") {
+ return 0, false, nil
+ }
+ // This is the line containing the start position of the binlog event.
+ fields := strings.Fields(line)
+ if len(fields) != 3 {
+ return 0, false, fmt.Errorf("unexpected mysqlbinlog output line %q when parsing binlog event start position", line)
+ }
+ pos, err = strconv.ParseInt(fields[2], 10, 0)
+ if err != nil {
+ return 0, false, err
+ }
+ return pos, true, nil
+}
+
+// Parse the first binlog eventTs of a local binlog file.
+func (r *Restore) parseLocalBinlogFirstEventTs(ctx context.Context, fileName string) (int64, error) {
+ args := []string{
+ // Local binlog file path.
+ path.Join(r.binlogDir, fileName),
+ // Tell mysqlbinlog to suppress the BINLOG statements for row events, which reduces the unneeded output.
+ "--base64-output=DECODE-ROWS",
+ }
+ cmd := exec.CommandContext(ctx, r.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)
+ cmd.Stderr = os.Stderr
+ pr, err := cmd.StdoutPipe()
+ if err != nil {
+ return 0, err
+ }
+ s := bufio.NewScanner(pr)
+ if err := cmd.Start(); err != nil {
+ return 0, err
+ }
+ defer func() {
+ _ = pr.Close()
+ _ = cmd.Process.Kill()
+ }()
+
+ var eventTs int64
+ for s.Scan() {
+ line := s.Text()
+ eventTsParsed, found, err := parseBinlogEventTsInLine(line)
+ if err != nil {
+ return 0, fmt.Errorf("failed to parse binlog eventTs from mysqlbinlog output, error: %w", err)
+ }
+ if !found {
+ continue
+ }
+ eventTs = eventTsParsed
+ break
+ }
+
+ return eventTs, nil
+}
+
+// Use command like mysqlbinlog --start-datetime=targetTs binlog.000001 to parse the first binlog event position with timestamp equal or after targetTs.
+// TODO(dragonly): Add integration test.
+func (r *Restore) getBinlogEventPositionAtOrAfterTs(ctx context.Context, binlogFile BinlogFile, targetTs int64) (int64, error) {
+ args := []string{
+ // Local binlog file path.
+ path.Join(r.binlogDir, binlogFile.Name),
+ // Tell mysqlbinlog to suppress the BINLOG statements for row events, which reduces the unneeded output.
+ "--base64-output=DECODE-ROWS",
+ // Instruct mysqlbinlog to start output only after encountering the first binlog event with timestamp equal or after targetTs.
+ "--start-datetime", formatDateTime(targetTs),
+ }
+ cmd := exec.CommandContext(ctx, r.mysqlutil.GetPath(mysqlutil.MySQLBinlog), args...)
+ cmd.Stderr = os.Stderr
+ pr, err := cmd.StdoutPipe()
+ if err != nil {
+ return 0, err
+ }
+ s := bufio.NewScanner(pr)
+ if err := cmd.Start(); err != nil {
+ return 0, err
+ }
+ defer func() {
+ _ = pr.Close()
+ _ = cmd.Process.Kill()
+ }()
+
+ var pos int64
+ for s.Scan() {
+ line := s.Text()
+ posParsed, found, err := parseBinlogEventPosInLine(line)
+ if err != nil {
+ return 0, fmt.Errorf("failed to parse binlog event start position from mysqlbinlog output, error: %w", err)
+ }
+ if !found {
+ continue
+ }
+ if posParsed == 4 {
+ // When invoking mysqlbinlog with --start-datetime, the first valid event will always be FORMAT_DESCRIPTION_EVENT which should be skipped.
+ continue
+ }
+ pos = posParsed
+ break
+ }
+
+ if pos == 0 {
+ return 0, common.Errorf(common.NotFound, fmt.Errorf("failed to find event position at or after targetTs %d", targetTs))
+ }
+
+ return pos, nil
+}
+
// getBinlogNameSeq returns the numeric extension to the binary log base name by using split the dot.
// For example: ("binlog.000001") => 1, ("binlog000001") => err
func getBinlogNameSeq(name string) (int64, error) {
diff --git a/plugin/db/mysql/restore_test.go b/plugin/db/mysql/restore_test.go
index b8e5760445..48104f159b 100644
--- a/plugin/db/mysql/restore_test.go
+++ b/plugin/db/mysql/restore_test.go
@@ -459,3 +459,108 @@ func TestBinlogFilesAreContinuous(t *testing.T) {
a.Equal(test.expect, result)
}
}
+
+func TestParseBinlogEventTsInLine(t *testing.T) {
+ a := require.New(t)
+ tests := []struct {
+ line string
+ eventTs int64
+ found bool
+ err bool
+ }{
+ // normal case
+ {
+ line: "#220620 13:23:55 server id 1 end_log_pos 126 CRC32 0x9a60fe57 Start: binlog v 4, server v 8.0.28 created 220620 13:23:55 at startup",
+ eventTs: time.Date(2022, 6, 20, 13, 23, 55, 0, time.Local).Unix(),
+ found: true,
+ err: false,
+ },
+ // no "server id"
+ {
+ line: "/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;",
+ eventTs: 0,
+ found: false,
+ err: false,
+ },
+ // fake event with "end_log_pos 0"
+ {
+ line: "#220609 11:59:57 server id 1 end_log_pos 0 CRC32 0x031d41f6 Start: binlog v 4, server v 8.0.28 created 220609 11:59:57",
+ eventTs: 0,
+ found: false,
+ err: false,
+ },
+ // incomplete line
+ {
+ line: "#220620 13:23:55 server id 1 end_log_",
+ eventTs: 0,
+ found: false,
+ err: true,
+ },
+ // parse time error
+ {
+ line: "#220620 99:99:99 server id 1 end_log_pos 126 CRC32 0x9a60fe57 Start: binlog v 4, server v 8.0.28 created 220620 13:23:55 at startup",
+ eventTs: 0,
+ found: false,
+ err: true,
+ },
+ }
+ for _, test := range tests {
+ eventTs, found, err := parseBinlogEventTsInLine(test.line)
+ a.Equal(test.eventTs, eventTs)
+ a.Equal(test.found, found)
+ if test.err {
+ a.Error(err)
+ } else {
+ a.NoError(err)
+ }
+ }
+}
+
+func TestParseBinlogEventPosInLine(t *testing.T) {
+ a := require.New(t)
+ tests := []struct {
+ line string
+ pos int64
+ found bool
+ err bool
+ }{
+ // normal case
+ {
+ line: "# at 34794",
+ pos: 34794,
+ found: true,
+ err: false,
+ },
+ // no "# at "
+ {
+ line: "/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;",
+ pos: 0,
+ found: false,
+ err: false,
+ },
+ // incomplete line
+ {
+ line: "# at ",
+ pos: 0,
+ found: false,
+ err: true,
+ },
+ // parse int error
+ {
+ line: "# at x",
+ pos: 0,
+ found: false,
+ err: true,
+ },
+ }
+ for _, test := range tests {
+ pos, found, err := parseBinlogEventPosInLine(test.line)
+ a.Equal(test.pos, pos)
+ a.Equal(test.found, found)
+ if test.err {
+ a.Error(err)
+ } else {
+ a.NoError(err)
+ }
+ }
+}