Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(flashback): generate and store rollback SQL for executed DML task (#3365)
Yilong Lie40baffc3f7d
diff --git a/api/task.go b/api/task.goindex 96e8588d47..dbe8fd52f1 100644--- a/api/task.go+++ b/api/task.go@@ -152,6 +152,9 @@ type TaskDatabaseDataUpdatePayload struct {BinlogFileEnd string `json:"binlogFileEnd,omitempty"`BinlogPosStart int64 `json:"binlogPosStart,omitempty"`BinlogPosEnd int64 `json:"binlogPosEnd,omitempty"`+ RollbackError string `json:"rollbackError,omitempty"`+ // RollbackStatement is the generated rollback SQL statement for the DML task.+ RollbackStatement string `json:"rollbackStatement,omitempty"`}// TaskDatabaseBackupPayload is the task payload for database backup.diff --git a/plugin/db/mysql/rollback.go b/plugin/db/mysql/rollback.goindex 911937de9e..2f11589148 100644--- a/plugin/db/mysql/rollback.go+++ b/plugin/db/mysql/rollback.go@@ -52,9 +52,11 @@ func (txn BinlogTransaction) GetRollbackSQL(tables map[string][]string) (string,// binlogFileNameList is a list of binlog file names, such as ["binlog.000001", "binlog.000002"].// binlogPosStart is the start position in the first binlog file.// binlogPosEnd is the end position in the last binlog file.+// threadID is used to filter the binlog events of the target transaction. It is recorded after executing the transaction using the same connection.// The binlog file names and positions are used to specify the binlog events range for rollback SQL generation.// tableCatalog is a map from table names to column names. It is used to map positional placeholders in the binlog events to the actual columns to generate valid SQL statements.-func (driver *Driver) GenerateRollbackSQL(ctx context.Context, binlogFileNameList []string, binlogPosStart, binlogPosEnd int64, tableCatalog map[string][]string) (string, error) {+// TODO(dragonly): parse/filter/generate rollback SQL in stream. Limit the generated SQL size to 8MB for now.+func (driver *Driver) GenerateRollbackSQL(ctx context.Context, binlogFileNameList []string, binlogPosStart, binlogPosEnd int64, threadID string, tableCatalog map[string][]string) (string, error) {args := binlogFileNameListargs = append(args,"--read-from-remote-server",@@ -100,10 +102,6 @@ func (driver *Driver) GenerateRollbackSQL(ctx context.Context, binlogFileNameLisreturn "", errors.WithMessage(err, "failed to parse binlog stream")}- threadID, err := driver.GetMigrationConnID(ctx)- if err != nil {- return "", err- }txnList, err = FilterBinlogTransactionsByThreadID(txnList, threadID)if err != nil {return "", errors.WithMessage(err, "failed to filter binlog transactions by thread ID")diff --git a/server/rollback_runner.go b/server/rollback_runner.gonew file mode 100644index 0000000000..bec0de4ff1--- /dev/null+++ b/server/rollback_runner.go@@ -0,0 +1,160 @@+package server++import (+ "context"+ "encoding/json"+ "fmt"+ "sync"+ "time"++ "github.com/pkg/errors"+ "go.uber.org/zap"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common/log"+ "github.com/bytebase/bytebase/plugin/db"+ "github.com/bytebase/bytebase/plugin/db/mysql"+ "github.com/bytebase/bytebase/store"+)++// NewRollbackRunner creates a new rollback runner.+func NewRollbackRunner(store *store.Store, dataDir string) *RollbackRunner {+ return &RollbackRunner{+ store: store,+ dataDir: dataDir,+ }+}++// RollbackRunner is the rollback runner generating rollback SQL statements.+type RollbackRunner struct {+ store *store.Store+ dataDir string+ generateMap sync.Map+}++// Run starts the rollback runner.+func (r *RollbackRunner) Run(ctx context.Context, wg *sync.WaitGroup) {+ ticker := time.NewTicker(1 * time.Second)+ defer ticker.Stop()+ defer wg.Done()+ r.retryGenerateRollbackSQL(ctx)+ for {+ select {+ case <-ticker.C:+ log.Debug("Received signal for generating rollback SQL.")+ r.generateMap.Range(func(key, value any) bool {+ task := value.(*api.Task)+ log.Debug(fmt.Sprintf("Generating rollback SQL for task %d", task.ID))+ r.generateRollbackSQL(ctx, task)+ r.generateMap.Delete(key)+ return true+ })+ case <-ctx.Done(): // if cancel() execute+ return+ }+ }+}++// retryGenerateRollbackSQL retries generating rollback SQL for tasks.+// It is currently called when Bytebase server starts and only rerun unfinished generation.+func (r *RollbackRunner) retryGenerateRollbackSQL(ctx context.Context) {+ find := &api.TaskFind{+ StatusList: &[]api.TaskStatus{api.TaskDone},+ TypeList: &[]api.TaskType{api.TaskDatabaseDataUpdate},+ Payload: "payload->>'threadID'!='' AND payload->>'rollbackError' IS NULL AND payload->>'rollbackStatement' IS NULL",+ }+ taskList, err := r.store.FindTask(ctx, find, true)+ if err != nil {+ log.Error("Failed to get running DML tasks", zap.Error(err))+ return+ }+ for _, task := range taskList {+ log.Debug("retry generate rollback SQL for task", zap.Int("ID", task.ID), zap.String("name", task.Name))+ r.generateMap.Store(task.ID, task)+ }+}++func (r *RollbackRunner) generateRollbackSQL(ctx context.Context, task *api.Task) {+ defer func() {+ if r := recover(); r != nil {+ err, ok := r.(error)+ if !ok {+ err = errors.Errorf("%v", r)+ }+ log.Error("Rollback runner PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))+ }+ }()++ payload := &api.TaskDatabaseDataUpdatePayload{}+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {+ log.Error("Invalid database data update payload", zap.Error(err))+ return+ }++ rollbackSQL, err := r.generateRollbackSQLImpl(ctx, task, payload)+ if err != nil {+ log.Error("Failed to generate rollback SQL statement", zap.Error(err))+ payload.RollbackError = err.Error()+ }+ payload.RollbackStatement = rollbackSQL++ payloadBytes, err := json.Marshal(payload)+ if err != nil {+ log.Error("Failed to marshal task payload", zap.Error(err))+ return+ }+ payloadString := string(payloadBytes)+ patch := &api.TaskPatch{+ ID: task.ID,+ UpdaterID: api.SystemBotID,+ Payload: &payloadString,+ }+ if _, err := r.store.PatchTask(ctx, patch); err != nil {+ log.Error("Failed to patch task with the MySQL thread ID", zap.Int("taskID", task.ID))+ return+ }+ log.Debug("Rollback SQL generation success", zap.Int("taskID", task.ID))+}++func (r *RollbackRunner) generateRollbackSQLImpl(ctx context.Context, task *api.Task, payload *api.TaskDatabaseDataUpdatePayload) (string, error) {+ basename, seqStart, err := mysql.ParseBinlogName(payload.BinlogFileStart)+ if err != nil {+ return "", errors.WithMessagef(err, "invalid start binlog file name %s", payload.BinlogFileStart)+ }+ _, seqEnd, err := mysql.ParseBinlogName(payload.BinlogFileEnd)+ if err != nil {+ return "", errors.WithMessagef(err, "Invalid end binlog file name %s", payload.BinlogFileEnd)+ }+ binlogFileNameList := mysql.GenBinlogFileNames(basename, seqStart, seqEnd)++ driver, err := getAdminDatabaseDriver(ctx, task.Instance, "", "", r.dataDir)+ if err != nil {+ return "", errors.WithMessage(err, "failed to get admin database driver")+ }+ list, err := driver.FindMigrationHistoryList(ctx, &db.MigrationHistoryFind{ID: &payload.MigrationID})+ if err != nil {+ return "", errors.WithMessagef(err, "failed to find migration history with ID %d", payload.MigrationID)+ }+ if len(list) == 0 {+ return "", errors.WithMessagef(err, "migration history with ID %d not found", payload.MigrationID)+ }+ if len(list) > 1 {+ return "", errors.WithMessagef(err, "found %d migration history record, expecting one", len(list))+ }+ history := list[0]+ tableMap, err := mysql.GetTableColumns(history.Schema)+ if err != nil {+ return "", errors.WithMessage(err, "failed to parse the schema")+ }++ mysqlDriver, ok := driver.(*mysql.Driver)+ if !ok {+ return "", errors.Errorf("failed to cast driver to mysql.Driver")+ }+ rollbackSQL, err := mysqlDriver.GenerateRollbackSQL(ctx, binlogFileNameList, payload.BinlogPosStart, payload.BinlogPosEnd, payload.ThreadID, tableMap)+ if err != nil {+ return "", errors.WithMessage(err, "failed to generate rollback SQL statement")+ }++ return rollbackSQL, nil+}diff --git a/server/server.go b/server/server.goindex 3c23f72db2..0311b44897 100644--- a/server/server.go+++ b/server/server.go@@ -57,6 +57,7 @@ type Server struct {BackupRunner *BackupRunnerAnomalyScanner *AnomalyScannerApplicationRunner *ApplicationRunner+ RollbackRunner *RollbackRunnerrunnerWG sync.WaitGroupActivityManager *ActivityManager@@ -303,6 +304,9 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {// Anomaly scanners.AnomalyScanner = NewAnomalyScanner(s)+ // Rollback SQL generator+ s.RollbackRunner = NewRollbackRunner(s.store, s.profile.DataDir)+// Metric reporters.initMetricReporter(config.workspaceID)}@@ -531,6 +535,8 @@ func (s *Server) Run(ctx context.Context, port int) error {go s.AnomalyScanner.Run(ctx, &s.runnerWG)s.runnerWG.Add(1)go s.ApplicationRunner.Run(ctx, &s.runnerWG)+ s.runnerWG.Add(1)+ go s.RollbackRunner.Run(ctx, &s.runnerWG)if s.MetricReporter != nil {s.runnerWG.Add(1)diff --git a/server/task_executor.go b/server/task_executor.goindex 2d7d224e90..7d58897c6d 100644--- a/server/task_executor.go+++ b/server/task_executor.go@@ -166,10 +166,12 @@ func executeMigration(ctx context.Context, server *Server, task *api.Task, state}if task.Type == api.TaskDatabaseDataUpdate && task.Instance.Engine == db.MySQL {- _, err := setMigrationIDAndEndBinlogCoordinate(ctx, driver, task, server.store, migrationID)+ updatedTask, err := setMigrationIDAndEndBinlogCoordinate(ctx, driver, task, server.store, migrationID)if err != nil {return 0, "", errors.Wrap(err, "failed to update the task payload for MySQL rollback SQL")}+ // The runner will periodically scan the map to generate rollback SQL asynchronously.+ server.RollbackRunner.generateMap.Store(updatedTask.ID, updatedTask)}return migrationID, schema, nildiff --git a/tests/rollback_test.go b/tests/rollback_test.goindex 4dead517cf..acb2cffe1d 100644--- a/tests/rollback_test.go+++ b/tests/rollback_test.go@@ -56,7 +56,9 @@ func TestRollback(t *testing.T) {tableCatalog := map[string][]string{"user": {"id", "name", "balance"},}- rollbackSQL, err := mysqlDriver.GenerateRollbackSQL(ctx, binlogFileList, 0, math.MaxInt64, tableCatalog)+ threadID, err := mysqlDriver.GetMigrationConnID(ctx)+ a.NoError(err)+ rollbackSQL, err := mysqlDriver.GenerateRollbackSQL(ctx, binlogFileList, 0, math.MaxInt64, threadID, tableCatalog)a.NoError(err)_, err = db.ExecContext(ctx, rollbackSQL)a.NoError(err)