Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(retention-policy): check expired backups by row status (#2826)
Yilong Li2920781056f0
diff --git a/api/backup.go b/api/backup.goindex af6d93b473..0009b008c3 100644--- a/api/backup.go+++ b/api/backup.go@@ -136,7 +136,8 @@ type BackupCreate struct {// BackupFind is the API message for finding backups.type BackupFind struct {- ID *int+ ID *int+ RowStatus *RowStatus// Related fieldsDatabaseID *intdiff --git a/server/backup_runner.go b/server/backup_runner.goindex 9859a4315f..a83d8e74bc 100644--- a/server/backup_runner.go+++ b/server/backup_runner.go@@ -86,7 +86,11 @@ func (r *BackupRunner) purgeExpiredBackupData(ctx context.Context) {if bs.RetentionPeriodTs == api.BackupRetentionPeriodUnset {continue // next database}- backupList, err := r.server.store.FindBackup(ctx, &api.BackupFind{DatabaseID: &bs.DatabaseID})+ statusNormal := api.Normal+ backupList, err := r.server.store.FindBackup(ctx, &api.BackupFind{+ DatabaseID: &bs.DatabaseID,+ RowStatus: &statusNormal,+ })if err != nil {log.Error("Failed to get backups for database.", zap.Int("databaseID", bs.DatabaseID), zap.String("database", bs.Database.Name))return@@ -215,6 +219,7 @@ func (r *BackupRunner) purgeBackup(ctx context.Context, backup *api.Backup) erroif _, err := r.server.store.PatchBackup(ctx, &backupPatch); err != nil {return errors.Wrapf(err, "failed to update status for deleted backup %q for database with ID %d", backup.Name, backup.DatabaseID)}+ log.Debug("Archived expired backup record", zap.String("name", backup.Name), zap.Int("id", backup.ID))switch backup.StorageBackend {case api.BackupStorageBackendLocal:@@ -222,13 +227,13 @@ func (r *BackupRunner) purgeBackup(ctx context.Context, backup *api.Backup) erroif err := os.Remove(backupFilePath); err != nil {return errors.Wrapf(err, "failed to delete an expired backup file %q", backupFilePath)}- log.Info(fmt.Sprintf("Deleted expired local backup file %s", backupFilePath))+ log.Debug(fmt.Sprintf("Deleted expired local backup file %s", backupFilePath))case api.BackupStorageBackendS3:backupFilePath := getBackupRelativeFilePath(backup.DatabaseID, backup.Name)if _, err := r.server.s3Client.DeleteObjects(ctx, backupFilePath); err != nil {return errors.Wrapf(err, "failed to delete backup file %s in the cloud storage", backupFilePath)}- log.Info(fmt.Sprintf("Deleted expired backup file %s in the cloud storage", backupFilePath))+ log.Debug(fmt.Sprintf("Deleted expired backup file %s in the cloud storage", backupFilePath))}return nildiff --git a/store/backup.go b/store/backup.goindex 4f1db36244..23f3a95418 100644--- a/store/backup.go+++ b/store/backup.go@@ -19,6 +19,7 @@ type backupRaw struct {ID int// Standard fields+ RowStatus api.RowStatusCreatorID intCreatedTs int64UpdaterID int@@ -47,6 +48,7 @@ func (raw *backupRaw) toBackup() *api.Backup {ID: raw.ID,// Standard fields+ RowStatus: raw.RowStatus,CreatorID: raw.CreatorID,CreatedTs: raw.CreatedTs,UpdaterID: raw.UpdaterID,@@ -463,7 +465,7 @@ func (*Store) createBackupImpl(ctx context.Context, tx *Tx, create *api.BackupCrpath)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)- RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, status, type, storage_backend, migration_history_version, path, comment+ RETURNING id, row_status, creator_id, created_ts, updater_id, updated_ts, database_id, name, status, type, storage_backend, migration_history_version, path, comment`var backupRaw backupRawif err := tx.QueryRowContext(ctx, query,@@ -478,6 +480,7 @@ func (*Store) createBackupImpl(ctx context.Context, tx *Tx, create *api.BackupCrcreate.Path,).Scan(&backupRaw.ID,+ &backupRaw.RowStatus,&backupRaw.CreatorID,&backupRaw.CreatedTs,&backupRaw.UpdaterID,@@ -505,6 +508,9 @@ func (*Store) findBackupImpl(ctx context.Context, tx *Tx, find *api.BackupFind)if v := find.ID; v != nil {where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)}+ if v := find.RowStatus; v != nil {+ where, args = append(where, fmt.Sprintf("row_status = $%d", len(args)+1)), append(args, *v)+ }if v := find.DatabaseID; v != nil {where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)}@@ -518,6 +524,7 @@ func (*Store) findBackupImpl(ctx context.Context, tx *Tx, find *api.BackupFind)rows, err := tx.QueryContext(ctx, `SELECTid,+ row_status,creator_id,created_ts,updater_id,@@ -547,6 +554,7 @@ func (*Store) findBackupImpl(ctx context.Context, tx *Tx, find *api.BackupFind)var payload []byteif err := rows.Scan(&backupRaw.ID,+ &backupRaw.RowStatus,&backupRaw.CreatorID,&backupRaw.CreatedTs,&backupRaw.UpdaterID,@@ -604,11 +612,12 @@ func (*Store) patchBackupImpl(ctx context.Context, tx *Tx, patch *api.BackupPatcUPDATE backupSET `+strings.Join(set, ", ")+`WHERE id = $%d- RETURNING id, creator_id, created_ts, updater_id, updated_ts, database_id, name, status, type, storage_backend, migration_history_version, path, comment, payload+ RETURNING id, row_status, creator_id, created_ts, updater_id, updated_ts, database_id, name, status, type, storage_backend, migration_history_version, path, comment, payload`, len(args)),args...,).Scan(&backupRaw.ID,+ &backupRaw.RowStatus,&backupRaw.CreatorID,&backupRaw.CreatedTs,&backupRaw.UpdaterID,diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.goindex cb91110192..0d6b311565 100644--- a/tests/backup_restore_test.go+++ b/tests/backup_restore_test.go@@ -8,6 +8,8 @@ import ("database/sql""encoding/json""fmt"+ "os"+ "path/filepath""sort""strconv""strings"@@ -68,6 +70,35 @@ func TestRestoreToNewDatabase(t *testing.T) {validateTableUpdateRow(t, mysqlDB, database.Name)}+func TestRetentionPolicy(t *testing.T) {+ t.Parallel()+ a := require.New(t)+ ctx := context.Background()+ port := getTestPort(t.Name())+ ctl := &controller{}+ _, _, database, backup, cleanFn := setUpForPITRTest(ctx, t, ctl, port)+ defer cleanFn()++ metaDB, err := sql.Open("pgx", fmt.Sprintf("host=/tmp port=%d user=bbtest database=bbtest", port+2))+ a.NoError(err)+ a.NoError(metaDB.Ping())++ // Check that the backup file exist+ backupFilePath := filepath.Join(ctl.profile.DataDir, "backup", "db", fmt.Sprintf("%d", database.ID), fmt.Sprintf("%s.sql", backup.Name))+ _, err = os.Stat(backupFilePath)+ a.NoError(err)++ // Change retention period to 1s, and the backup should be quickly removed.+ _, err = metaDB.ExecContext(ctx, fmt.Sprintf("UPDATE backup_setting SET enabled=true, retention_period_ts=1 WHERE database_id=%d;", database.ID))+ a.NoError(err)+ err = ctl.waitBackupArchived(database.ID, backup.ID)+ a.NoError(err)+ // Wait for 1s to delete the file.+ time.Sleep(1 * time.Second)+ _, err = os.Stat(backupFilePath)+ a.Equal(true, os.IsNotExist(err))+}+// TestPITRGeneral tests for the general PITR cases:// 1. buggy application.// 2. bad schema migration.diff --git a/tests/tests.go b/tests/tests.goindex 574ae088a4..c4a78cdab1 100644--- a/tests/tests.go+++ b/tests/tests.go@@ -104,6 +104,7 @@ var (type controller struct {server *server.Server+ profile server.Profileclient *http.Clientcookie stringvcsProvider fake.VCSProvider@@ -142,6 +143,7 @@ func getTestPort(testName string) int {// PITR related cases"TestRestoreToNewDatabase",+ "TestRetentionPolicy","TestPITRGeneral","TestPITRDropDatabase","TestPITRInvalidTimePoint",@@ -190,6 +192,7 @@ func (ctl *controller) StartServer(ctx context.Context, dataDir string, vcsProvireturn err}ctl.server = server+ ctl.profile = profilereturn ctl.start(ctx, vcsProviderCreator, port)}@@ -1327,6 +1330,35 @@ func (ctl *controller) waitBackup(databaseID, backupID int) error {return errors.Errorf("failed to wait for backup as this condition should never be reached")}+// waitBackupArchived waits for a backup to be archived.+func (ctl *controller) waitBackupArchived(databaseID, backupID int) error {+ ticker := time.NewTicker(100 * time.Millisecond)+ defer ticker.Stop()++ log.Debug("Waiting for backup.", zap.Int("id", backupID))+ for range ticker.C {+ backups, err := ctl.listBackups(databaseID)+ if err != nil {+ return err+ }+ var backup *api.Backup+ for _, b := range backups {+ if b.ID == backupID {+ backup = b+ break+ }+ }+ if backup == nil {+ return errors.Errorf("backup %d for database %d not found", backupID, databaseID)+ }+ if backup.RowStatus == api.Archived {+ return nil+ }+ }+ // Ideally, this should never happen because the ticker will not stop till the backup is finished.+ return errors.Errorf("failed to wait for backup as this condition should never be reached")+}+// createSheet creates a sheet.func (ctl *controller) createSheet(sheetCreate api.SheetCreate) (*api.Sheet, error) {buf := new(bytes.Buffer)