Skip to content

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

feat(backup): retention policy executor (#1950)

Yilong Li4acafdedc3e9
diff --git a/api/backup.go b/api/backup.go
index d69acd3b78..e60dece92a 100644
--- a/api/backup.go
+++ b/api/backup.go
@@ -7,6 +7,11 @@ import (
"go.uber.org/zap/zapcore"
)
+const (
+ // BackupRetentionPeriodUnset is the unset value of a backup retention period.
+ BackupRetentionPeriodUnset = 0
+)
+
// BackupStatus is the status of a backup.
type BackupStatus string
@@ -71,6 +76,7 @@ type Backup struct {
ID int `jsonapi:"primary,backup"`
// Standard fields
+ RowStatus RowStatus `jsonapi:"attr,rowStatus"`
CreatorID int
Creator *Principal `jsonapi:"relation,creator"`
CreatedTs int64 `jsonapi:"attr,createdTs"`
@@ -153,6 +159,7 @@ type BackupPatch struct {
ID int
// Standard fields
+ RowStatus *RowStatus
// Value is assigned from the jwt subject field passed by the client.
UpdaterID int
diff --git a/plugin/db/mysql/restore.go b/plugin/db/mysql/restore.go
index e16816c3a9..5483f75b3f 100644
--- a/plugin/db/mysql/restore.go
+++ b/plugin/db/mysql/restore.go
@@ -62,7 +62,7 @@ type BinlogFile struct {
}
func newBinlogFile(name string, size int64) (BinlogFile, error) {
- seq, err := getBinlogNameSeq(name)
+ seq, err := GetBinlogNameSeq(name)
if err != nil {
return BinlogFile{}, err
}
@@ -86,7 +86,7 @@ type binlogCoordinate struct {
}
func newBinlogCoordinate(binlogFileName string, pos int64) (binlogCoordinate, error) {
- seq, err := getBinlogNameSeq(binlogFileName)
+ seq, err := GetBinlogNameSeq(binlogFileName)
if err != nil {
return binlogCoordinate{}, err
}
@@ -241,7 +241,7 @@ func (driver *Driver) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner
// 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)
+ 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)
}
@@ -704,7 +704,7 @@ func (driver *Driver) getBinlogCoordinateByTs(ctx context.Context, targetTs int6
binlogFileTarget = &binlogFilesLocalSorted[len(binlogFilesLocalSorted)-1]
}
log.Debug("Found potential binlog file containing targetTs", zap.String("binlogFile", binlogFileTarget.Name), zap.Int64("targetTs", targetTs), zap.Bool("isLastBinlogFile", isLastBinlogFile))
- targetSeq, err := getBinlogNameSeq(binlogFileTarget.Name)
+ targetSeq, err := GetBinlogNameSeq(binlogFileTarget.Name)
if err != nil {
return nil, fmt.Errorf("failed to parse seq from binlog file name %q", binlogFileTarget.Name)
}
@@ -856,9 +856,9 @@ func (driver *Driver) getBinlogEventPositionAtOrAfterTs(ctx context.Context, bin
return pos, nil
}
-// getBinlogNameSeq returns the numeric extension to the binary log base name by using split the dot.
+// 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) {
+func GetBinlogNameSeq(name string) (int64, error) {
s := strings.Split(name, ".")
if len(s) != 2 {
return 0, fmt.Errorf("failed to parse binlog extension, expecting two parts in the binlog file name %q but got %d", name, len(s))
diff --git a/plugin/db/mysql/restore_test.go b/plugin/db/mysql/restore_test.go
index 320280e8ab..c26d343ed5 100644
--- a/plugin/db/mysql/restore_test.go
+++ b/plugin/db/mysql/restore_test.go
@@ -163,7 +163,7 @@ func TestGetBinlogFileNameSeqNumber(t *testing.T) {
},
}
for _, test := range tests {
- ext, err := getBinlogNameSeq(test.name)
+ ext, err := GetBinlogNameSeq(test.name)
a.EqualValues(test.expect, ext)
if test.err {
a.Error(err)
diff --git a/server/backup_runner.go b/server/backup_runner.go
index eedcc333a3..0649f64435 100644
--- a/server/backup_runner.go
+++ b/server/backup_runner.go
@@ -4,7 +4,11 @@ import (
"context"
"encoding/json"
"fmt"
+ "io/ioutil"
+ "math"
"net/http"
+ "os"
+ "path"
"sync"
"time"
@@ -60,7 +64,7 @@ func (r *BackupRunner) Run(ctx context.Context, wg *sync.WaitGroup) {
}()
r.startAutoBackups(ctx, runningTasks, &mu)
r.downloadBinlogFiles(ctx)
-
+ r.purgeExpiredBackupData(ctx)
}()
case <-ctx.Done(): // if cancel() execute
r.backupWg.Wait()
@@ -70,6 +74,127 @@ func (r *BackupRunner) Run(ctx context.Context, wg *sync.WaitGroup) {
}
}
+// TODO(dragonly): Make best effort to assure that users could recover to at least RetentionPeriodTs ago.
+// This may require pending deleting expired backup files and binlog files.
+func (r *BackupRunner) purgeExpiredBackupData(ctx context.Context) {
+ backupSettingList, err := r.server.store.FindBackupSetting(ctx, api.BackupSettingFind{})
+ if err != nil {
+ log.Error("Failed to find all the backup settings.", zap.Error(err))
+ return
+ }
+
+ log.Debug("Deleting expired backups.")
+ for _, bs := range backupSettingList {
+ if bs.RetentionPeriodTs == api.BackupRetentionPeriodUnset {
+ continue // next database
+ }
+ backupList, err := r.server.store.FindBackup(ctx, &api.BackupFind{DatabaseID: &bs.DatabaseID})
+ if err != nil {
+ log.Error("Failed to get backups for database.", zap.Int("databaseID", bs.DatabaseID), zap.String("database", bs.Database.Name))
+ return
+ }
+ for _, backup := range backupList {
+ backupTime := time.Unix(backup.UpdatedTs, 0)
+ expireTime := backupTime.Add(time.Duration(bs.RetentionPeriodTs) * time.Second)
+ if time.Now().After(expireTime) {
+ if err := r.purgeBackup(ctx, backup); err != nil {
+ log.Error("Failed to purge backup", zap.String("backup", backup.Name), zap.Error(err))
+ }
+ }
+ }
+ }
+
+ log.Debug("Deleting expired MySQL binlog files.")
+ instanceList, err := r.server.store.FindInstance(ctx, &api.InstanceFind{})
+ if err != nil {
+ log.Error("Failed to find non-archived instances.", zap.Error(err))
+ return
+ }
+
+ for _, instance := range instanceList {
+ if instance.Engine != db.MySQL {
+ log.Error("Instance is not a MySQL instance", zap.String("instance", instance.Name))
+ continue
+ }
+ maxRetentionPeriodTs, err := r.getMaxRetentionPeriodTsForMySQLInstance(ctx, instance)
+ if err != nil {
+ log.Error("Failed to get max retention period for MySQL instance", zap.String("instance", instance.Name), zap.Error(err))
+ continue
+ }
+ if maxRetentionPeriodTs == math.MaxInt {
+ log.Info("All the databases in the MySQL instance have unset retention period. Skip deleting binlog files.", zap.String("instance", instance.Name))
+ continue
+ }
+ log.Debug("Deleting old binlog files for MySQL instance.", zap.String("instance", instance.Name))
+ if err := r.purgeBinlogFiles(instance.ID, maxRetentionPeriodTs); err != nil {
+ log.Error("Failed to purge binlog files for instance", zap.String("instance", instance.Name), zap.Int("retentionPeriodTs", maxRetentionPeriodTs), zap.Error(err))
+ }
+ }
+}
+
+func (r *BackupRunner) getMaxRetentionPeriodTsForMySQLInstance(ctx context.Context, instance *api.Instance) (int, error) {
+ backupSettingList, err := r.server.store.FindBackupSetting(ctx, api.BackupSettingFind{InstanceID: &instance.ID})
+ if err != nil {
+ log.Error("Failed to find backup settings for instance.", zap.String("instance", instance.Name), zap.Error(err))
+ return 0, fmt.Errorf("failed to find backup settings for instance %q, error: %w", instance.Name, err)
+ }
+ maxRetentionPeriodTs := math.MaxInt
+ for _, bs := range backupSettingList {
+ if bs.RetentionPeriodTs != api.BackupRetentionPeriodUnset && bs.RetentionPeriodTs < maxRetentionPeriodTs {
+ maxRetentionPeriodTs = bs.RetentionPeriodTs
+ }
+ }
+ return maxRetentionPeriodTs, nil
+}
+
+func (r *BackupRunner) purgeBinlogFiles(instanceID, retentionPeriodTs int) error {
+ binlogDir := getBinlogAbsDir(r.server.profile.DataDir, instanceID)
+ binlogFileInfoList, err := ioutil.ReadDir(binlogDir)
+ if err != nil {
+ return fmt.Errorf("failed to read backup directory %q, error: %w", binlogDir, err)
+ }
+ 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,
+ // which in turn is later than the last event timestamp of the binlog file.
+ // This is not accurate and gives about 10 minutes (backup runner interval) more retention time to the binlog files, which is acceptable.
+ expireTime := binlogFileInfo.ModTime().Add(time.Duration(retentionPeriodTs) * time.Second)
+ if time.Now().After(expireTime) {
+ binlogFilePath := path.Join(binlogDir, binlogFileInfo.Name())
+ if err := os.Remove(binlogFilePath); err != nil {
+ log.Warn("Failed to remove an expired binlog file.", zap.String("path", binlogFilePath), zap.Error(err))
+ continue
+ }
+ log.Info("Deleted expired binlog file.", zap.String("path", binlogFilePath))
+ }
+ }
+ return nil
+}
+
+func (r *BackupRunner) purgeBackup(ctx context.Context, backup *api.Backup) error {
+ archive := api.Archived
+ backupPatch := api.BackupPatch{
+ ID: backup.ID,
+ RowStatus: &archive,
+ }
+ if _, err := r.server.store.PatchBackup(ctx, &backupPatch); err != nil {
+ log.Error("Failed to update status for deleted backup.", zap.String("name", backup.Name), zap.Int("databaseId", backup.DatabaseID))
+ return fmt.Errorf("failed to update status for deleted backup %q for database with ID %d, error: %w", backup.Name, backup.DatabaseID, err)
+ }
+
+ backupFilePath := getBackupAbsFilePath(r.server.profile.DataDir, backup.DatabaseID, backup.Name)
+ if err := os.Remove(backupFilePath); err != nil {
+ log.Error("Failed to delete an expired backup file.", zap.String("path", backupFilePath), zap.Error(err))
+ return fmt.Errorf("failed to delete an expired backup file %q, error: %w", backupFilePath, err)
+ }
+ log.Info("Deleted expired backup file.", zap.String("path", backupFilePath))
+
+ return nil
+}
+
func (r *BackupRunner) downloadBinlogFiles(ctx context.Context) {
instanceList, err := r.server.store.FindInstanceWithDatabaseBackupEnabled(ctx, db.MySQL)
if err != nil {
diff --git a/store/backup.go b/store/backup.go
index fcbc86627f..29d0f8cc17 100644
--- a/store/backup.go
+++ b/store/backup.go
@@ -538,6 +538,9 @@ func (*Store) patchBackupImpl(ctx context.Context, tx *sql.Tx, patch *api.Backup
set, args = append(set, fmt.Sprintf("updater_id = $%d", len(args)+1)), append(args, patch.UpdaterID)
set, args = append(set, fmt.Sprintf("status = $%d", len(args)+1)), append(args, patch.Status)
set, args = append(set, fmt.Sprintf("comment = $%d", len(args)+1)), append(args, patch.Comment)
+ if v := patch.RowStatus; v != nil {
+ set, args = append(set, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, *v)
+ }
if patch.Payload == "" {
patch.Payload = "{}"
}