Skip to content

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

feat(PITR): periodically download binlog files for MySQL instances (#1823)

Yilong Li138b92637525
diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.go
index e7b45929ff..13c8e0b4cd 100644
--- a/plugin/db/mysql/restore.go
+++ b/plugin/db/mysql/restore.go
@@ -494,7 +494,7 @@ func binlogFilesAreContinuous(files []BinlogFile) bool {
}
// Download binlog files on server.
-func (driver *Driver) downloadBinlogFilesOnServer(ctx context.Context, binlogFilesLocal, binlogFilesOnServerSorted []BinlogFile) error {
+func (driver *Driver) downloadBinlogFilesOnServer(ctx context.Context, binlogFilesLocal, binlogFilesOnServerSorted []BinlogFile, downloadLatestBinlogFile bool) error {
if len(binlogFilesOnServerSorted) == 0 {
log.Debug("No binlog file found on server to download")
return nil
@@ -506,6 +506,9 @@ func (driver *Driver) downloadBinlogFilesOnServer(ctx context.Context, binlogFil
}
log.Debug("Downloading binlog files", zap.Array("fileList", ZapBinlogFiles(binlogFilesOnServerSorted)))
for _, fileOnServer := range binlogFilesOnServerSorted {
+ if fileOnServer.Name == latestBinlogFileOnServer.Name && !downloadLatestBinlogFile {
+ continue
+ }
fileLocal, existLocal := binlogFilesLocalMap[fileOnServer.Name]
path := filepath.Join(driver.binlogDir, fileOnServer.Name)
if !existLocal {
@@ -532,7 +535,7 @@ func (driver *Driver) downloadBinlogFilesOnServer(ctx context.Context, binlogFil
}
// FetchAllBinlogFiles downloads all binlog files on server to `binlogDir`.
-func (driver *Driver) FetchAllBinlogFiles(ctx context.Context) error {
+func (driver *Driver) FetchAllBinlogFiles(ctx context.Context, downloadLatestBinlogFile bool) error {
// Read binlog files list on server.
binlogFilesOnServerSorted, err := driver.GetSortedBinlogFilesMetaOnServer(ctx)
if err != nil {
@@ -550,7 +553,7 @@ func (driver *Driver) FetchAllBinlogFiles(ctx context.Context) error {
return fmt.Errorf("failed to read local binlog files, error: %w", err)
}
- return driver.downloadBinlogFilesOnServer(ctx, binlogFilesLocalSorted, binlogFilesOnServerSorted)
+ return driver.downloadBinlogFilesOnServer(ctx, binlogFilesLocalSorted, binlogFilesOnServerSorted, downloadLatestBinlogFile)
}
// Syncs the binlog specified by `meta` between the instance and local.
diff --git a/server/backup_runner.go b/server/backup_runner.go
index 38796e512c..374a6a0776 100644
--- a/server/backup_runner.go
+++ b/server/backup_runner.go
@@ -11,21 +11,28 @@ import (
"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/plugin/db/mysql"
+ "github.com/bytebase/bytebase/resources/mysqlutil"
"go.uber.org/zap"
)
// NewBackupRunner creates a new backup runner.
func NewBackupRunner(server *Server, backupRunnerInterval time.Duration) *BackupRunner {
return &BackupRunner{
- server: server,
- backupRunnerInterval: backupRunnerInterval,
+ server: server,
+ backupRunnerInterval: backupRunnerInterval,
+ downloadBinlogInstanceIDs: make(map[int]bool),
}
}
// BackupRunner is the backup runner scheduling automatic backups.
type BackupRunner struct {
- server *Server
- backupRunnerInterval time.Duration
+ server *Server
+ backupRunnerInterval time.Duration
+ downloadBinlogInstanceIDs map[int]bool
+ downloadBinlogWg sync.WaitGroup
+ downloadBinlogMu sync.Mutex
}
// Run is the runner for backup runner.
@@ -51,13 +58,69 @@ func (s *BackupRunner) Run(ctx context.Context, wg *sync.WaitGroup) {
}
}()
s.startAutoBackups(ctx, runningTasks, &mu)
+ s.downloadBinlogFiles(ctx)
}()
case <-ctx.Done(): // if cancel() execute
+ s.downloadBinlogWg.Wait()
return
}
}
}
+func (s *BackupRunner) downloadBinlogFiles(ctx context.Context) {
+ instanceList, err := s.server.store.FindInstanceWithDatabaseBackupEnabled(ctx, db.MySQL)
+ if err != nil {
+ log.Error("Failed to retrieve MySQL instance list with at least one database backup enabled", zap.Error(err))
+ return
+ }
+
+ s.downloadBinlogMu.Lock()
+ defer s.downloadBinlogMu.Unlock()
+ for _, instance := range instanceList {
+ if _, ok := s.downloadBinlogInstanceIDs[instance.ID]; !ok {
+ s.downloadBinlogInstanceIDs[instance.ID] = true
+ go s.downloadBinlogFilesForInstance(ctx, instance, s.server.profile.DataDir, s.server.mysqlutil)
+ s.downloadBinlogWg.Add(1)
+ }
+ }
+}
+
+func (s *BackupRunner) downloadBinlogFilesForInstance(ctx context.Context, instance *api.Instance, dataDir string, mysqlutil mysqlutil.Instance) {
+ log.Debug("Downloading binlog files for MySQL instance", zap.String("instance", instance.Name))
+ defer func() {
+ s.downloadBinlogMu.Lock()
+ delete(s.downloadBinlogInstanceIDs, instance.ID)
+ s.downloadBinlogMu.Unlock()
+ s.downloadBinlogWg.Done()
+ }()
+ driver, err := getAdminDatabaseDriver(ctx, instance, "", "" /* pgInstanceDir */)
+ if err != nil {
+ if common.ErrorCode(err) == common.DbConnectionFailure {
+ log.Warn("Cannot connect to instance", zap.String("instance", instance.Name), zap.Error(err))
+ return
+ }
+ log.Error("Failed to get driver for MySQL instance when downloading binlog", zap.String("instance", instance.Name), zap.Error(err))
+ return
+ }
+ defer driver.Close(ctx)
+
+ binlogDir := getBinlogAbsDir(dataDir, instance.ID)
+ if err := createBinlogDir(dataDir, instance.ID); err != nil {
+ log.Error("Failed to create binlog directory", zap.Error(err))
+ return
+ }
+ mysqlDriver, ok := driver.(*mysql.Driver)
+ if !ok {
+ log.Error("Failed to cast driver to mysql.Driver", zap.String("instance", instance.Name))
+ return
+ }
+ mysqlDriver.SetUpForPITR(mysqlutil, binlogDir)
+ if err := mysqlDriver.FetchAllBinlogFiles(ctx, false /* downloadLatestBinlogFile */); err != nil {
+ log.Error("Failed to download all binlog files for instance", zap.String("instance", instance.Name), zap.Error(err))
+ return
+ }
+}
+
func (s *BackupRunner) startAutoBackups(ctx context.Context, runningTasks map[int]bool, mu *sync.RWMutex) {
// Find all databases that need a backup in this hour.
t := time.Now().UTC().Truncate(time.Hour)
@@ -147,7 +210,7 @@ func (s *Server) scheduleBackupTask(ctx context.Context, database *api.Database,
backupNew, err := s.store.CreateBackup(ctx, backupCreate)
if err != nil {
if common.ErrorCode(err) == common.Conflict {
- // Backup already exists for the database.
+ log.Debug("Backup already exists for the database", zap.String("backup", backupName), zap.String("database", database.Name))
return nil, nil
}
return nil, fmt.Errorf("failed to create backup %q, error: %w", backupName, err)
diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.go
index cfd2e973c4..a5e750606b 100644
--- a/server/task_executor_pitr_restore.go
+++ b/server/task_executor_pitr_restore.go
@@ -86,8 +86,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *ap
mysqlDriver.SetUpForPITR(exec.mysqlutil, binlogDir)
log.Debug("Downloading all binlog files")
- // TODO(dragonly): Do this on a regular basis.
- if err := mysqlDriver.FetchAllBinlogFiles(ctx); err != nil {
+ if err := mysqlDriver.FetchAllBinlogFiles(ctx, true /* downloadLatestBinlogFile */); err != nil {
return err
}
diff --git a/store/instance.go b/store/instance.go
index 51cd0f047a..ac4d6592dc 100644
--- a/store/instance.go
+++ b/store/instance.go
@@ -179,6 +179,72 @@ func (s *Store) CountInstanceGroupByEngineAndEnvironmentID(ctx context.Context)
return res, nil
}
+// FindInstanceWithDatabaseBackupEnabled finds instances with at least one database who enables backup policy.
+func (s *Store) FindInstanceWithDatabaseBackupEnabled(ctx context.Context, engineType db.Type) ([]*api.Instance, error) {
+ rows, err := s.db.db.QueryContext(ctx, `
+ SELECT DISTINCT
+ instance.id,
+ instance.row_status,
+ instance.creator_id,
+ instance.created_ts,
+ instance.updater_id,
+ instance.updated_ts,
+ instance.environment_id,
+ instance.name,
+ instance.engine,
+ instance.engine_version,
+ instance.external_link,
+ instance.host,
+ instance.port
+ FROM instance
+ JOIN db ON db.instance_id = instance.id
+ JOIN backup_setting AS bs ON db.id = bs.database_id
+ WHERE bs.enabled = true AND instance.row_status = $1 AND instance.engine = $2
+ `, api.Normal, engineType)
+
+ if err != nil {
+ return nil, FormatError(err)
+ }
+ defer rows.Close()
+
+ // Iterate over result set and deserialize rows into instanceRawList.
+ var instanceRawList []*instanceRaw
+ for rows.Next() {
+ var instanceRaw instanceRaw
+ if err := rows.Scan(
+ &instanceRaw.ID,
+ &instanceRaw.RowStatus,
+ &instanceRaw.CreatorID,
+ &instanceRaw.CreatedTs,
+ &instanceRaw.UpdaterID,
+ &instanceRaw.UpdatedTs,
+ &instanceRaw.EnvironmentID,
+ &instanceRaw.Name,
+ &instanceRaw.Engine,
+ &instanceRaw.EngineVersion,
+ &instanceRaw.ExternalLink,
+ &instanceRaw.Host,
+ &instanceRaw.Port,
+ ); err != nil {
+ return nil, FormatError(err)
+ }
+ instanceRawList = append(instanceRawList, &instanceRaw)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, FormatError(err)
+ }
+
+ var instanceList []*api.Instance
+ for _, raw := range instanceRawList {
+ instance, err := s.composeInstance(ctx, raw)
+ if err != nil {
+ return nil, fmt.Errorf("failed to compose Instance with instanceRaw[%+v], error: %w", raw, err)
+ }
+ instanceList = append(instanceList, instance)
+ }
+ return instanceList, nil
+}
+
// GetInstanceAdminPasswordByID gets admin password of instance
func (s *Store) GetInstanceAdminPasswordByID(ctx context.Context, instanceID int) (string, error) {
dataSourceFind := &api.DataSourceFind{
diff --git a/tests/mysql_test.go b/tests/mysql_test.go
index bdc4fd7a95..e3a5c6a1a1 100644
--- a/tests/mysql_test.go
+++ b/tests/mysql_test.go
@@ -185,7 +185,7 @@ func TestFetchBinlogFiles(t *testing.T) {
err = os.Remove(path)
a.NoError(err)
}
- err = mysqlDriver.FetchAllBinlogFiles(ctx)
+ err = mysqlDriver.FetchAllBinlogFiles(ctx, true /* downloadLatestBinlogFile */)
a.NoError(err)
binlogFilesDownloaded, err := pluginmysql.GetSortedLocalBinlogFiles(binlogDir)
a.NoError(err)
@@ -206,7 +206,7 @@ func TestFetchBinlogFiles(t *testing.T) {
a.NoError(err)
}
t.Log("Fetch binlog files")
- err = mysqlDriver.FetchAllBinlogFiles(ctx)
+ err = mysqlDriver.FetchAllBinlogFiles(ctx, true /* downloadLatestBinlogFile */)
a.NoError(err)
binlogFilesDownloaded, err = pluginmysql.GetSortedLocalBinlogFiles(binlogDir)
a.NoError(err)
@@ -223,7 +223,7 @@ func TestFetchBinlogFiles(t *testing.T) {
a.NoError(err)
// Re-download and check.
t.Log("Re-downloading binlog files")
- err = mysqlDriver.FetchAllBinlogFiles(ctx)
+ err = mysqlDriver.FetchAllBinlogFiles(ctx, true /* downloadLatestBinlogFile */)
a.NoError(err)
binlogFilesDownloadedAgain, err := pluginmysql.GetSortedLocalBinlogFiles(binlogDir)
a.NoError(err)