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(PITR): implement PITR cutover task executor (#1328)
Yilong Li3ff6500588d6
diff --git a/api/task.go b/api/task.goindex 532af15f16..f733b0e5ea 100644--- a/api/task.go+++ b/api/task.go@@ -78,8 +78,6 @@ const (TaskDatabasePITRRestore TaskType = "bb.task.database.pitr.restore"// TaskDatabasePITRCutover is the task type for swapping the pitr and original database.TaskDatabasePITRCutover TaskType = "bb.task.database.pitr.cutover"- // TaskDatabasePITRDelete is the task type fo deleting the original database.- TaskDatabasePITRDelete TaskType = "bb.task.database.pitr.delete")// These payload types are only used when marshalling to the json format for saving into the database.@@ -99,10 +97,6 @@ type TaskDatabasePITRRestorePayload struct {// It is currently only a placeholder.type TaskDatabasePITRCutoverPayload struct{}-// TaskDatabasePITRDeletePayload is the task payload for deleting the original database after a successful PITR cutover.-// It is currently only a placeholder.-type TaskDatabasePITRDeletePayload struct{}-// TaskDatabaseCreatePayload is the task payload for creating databases.type TaskDatabaseCreatePayload struct {// The project owning the database.diff --git a/plugin/db/mysql/mysql.go b/plugin/db/mysql/mysql.goindex a0bf60afe9..55c30da560 100644--- a/plugin/db/mysql/mysql.go+++ b/plugin/db/mysql/mysql.go@@ -1251,6 +1251,7 @@ type triggerSchema struct {}// GetTables gets all tables of a database.+// TODO(dragonly): Refactor to 2 variants that one takes a txn arg and one does not, for different use cases.func GetTables(txn *sql.Tx, dbName string) ([]*TableSchema, error) {var tables []*TableSchemaquery := fmt.Sprintf("SHOW FULL TABLES FROM `%s`;", dbName)diff --git a/plugin/restore/mysql/mysql.go b/plugin/restore/mysql/mysql.goindex 8b7ae37a91..8babe6ff80 100644--- a/plugin/restore/mysql/mysql.go+++ b/plugin/restore/mysql/mysql.go@@ -21,7 +21,12 @@ const (MaxDatabaseNameLength = 64)-// Restore implements recovery functions for MySQL+// Restore implements recovery functions for MySQL.+// For example, the original database is `dbfoo`. The suffixTs, derived from the PITR issue's CreateTs, is 1653018005.+// Bytebase will do the following:+// 1. Create a database called `dbfoo_pitr_1653018005`, and do PITR restore to it.+// 2. Create a database called `dbfoo_pitr_1653018005_old`, and move tables+// from `dbfoo` to `dbfoo_pitr_1653018005_old`, and tables from `dbfoo_pitr_1653018005` to `dbfoo`.type Restore struct {driver *mysql.Drivermysqlbinlog *mysqlbinlog.Instance@@ -40,7 +45,8 @@ func (r *Restore) RestoreBinlog(ctx context.Context, config mysql.BinlogInfo) erreturn fmt.Errorf("Unimplemented")}-// RestorePITR is a wrapper for restore a full backup and a range of incremental backup+// RestorePITR is a wrapper for restore a full backup and a range of incremental backup.+// It performs the step 1 of the restore process.func (r *Restore) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner, binlog mysql.BinlogInfo, database string, suffixTs int64) error {pitrDatabaseName := getPITRDatabaseName(database, suffixTs)query := fmt.Sprintf(""+@@ -78,45 +84,46 @@ func (r *Restore) RestorePITR(ctx context.Context, fullBackup *bufio.Scanner, bi}// SwapPITRDatabase renames the pitr database to the target, and the original to the old database-func (r *Restore) SwapPITRDatabase(ctx context.Context, database string, timestamp int64) error {- db, err := r.driver.GetDbConnection(ctx, "")- if err != nil {- return err- }+// It returns the pitr and old database names after swap.+// It performs the step 2 of the restore process.+func (r *Restore) SwapPITRDatabase(ctx context.Context, database string, suffixTs int64) (string, string, error) {+ pitrDatabaseName := getPITRDatabaseName(database, suffixTs)+ pitrOldDatabase := getPITROldDatabaseName(database, suffixTs)- // TODO(dragonly): Clean up the transactions, they do not have a clear semantic / are not necessary.- txn, err := db.BeginTx(ctx, nil)+ db, err := r.driver.GetDbConnection(ctx, "")if err != nil {- return err- }- defer txn.Rollback()-- pitrOldDatabase := getSafeName(database, "old")- pitrDatabaseName := getPITRDatabaseName(database, timestamp)-- if _, err := txn.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", pitrOldDatabase)); err != nil {- return err+ return pitrDatabaseName, pitrOldDatabase, err}// Handle the case that the original database does not exist, because user could drop a database and want to restore it.dbExists, err := r.databaseExists(ctx, database)if err != nil {- return fmt.Errorf("failed to check whether database %q exists, error[%w]", database, err)+ return pitrDatabaseName, pitrOldDatabase, fmt.Errorf("failed to check whether database %q exists, error[%w]", database, err)}if !dbExists {- if _, err := txn.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", database)); err != nil {- return fmt.Errorf("failed to create non-exist database %q", database)+ if _, err := db.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", database)); err != nil {+ return pitrDatabaseName, pitrOldDatabase, fmt.Errorf("failed to create non-exist database %q, error[%w]", database, err)}}- var tables []*mysql.TableSchema- tables, err = mysql.GetTables(txn, database)+ // TODO(dragonly): Remove the transactions, because they do not have a clear semantic / are not necessary.+ txn, err := db.BeginTx(ctx, nil)+ if err != nil {+ return pitrDatabaseName, pitrOldDatabase, err+ }+ defer txn.Rollback()++ tables, err := mysql.GetTables(txn, database)if err != nil {- return fmt.Errorf("failed to get tables of database %q, error[%w]", database, err)+ return pitrDatabaseName, pitrOldDatabase, fmt.Errorf("failed to get tables of database %q, error[%w]", database, err)}tablesPITR, err := mysql.GetTables(txn, pitrDatabaseName)if err != nil {- return fmt.Errorf("failed to get tables of database %q, error[%w]", pitrDatabaseName, err)+ return pitrDatabaseName, pitrOldDatabase, fmt.Errorf("failed to get tables of database %q, error[%w]", pitrDatabaseName, err)+ }++ if _, err := txn.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE `%s`", pitrOldDatabase)); err != nil {+ return pitrDatabaseName, pitrOldDatabase, err}var tableRenames []string@@ -129,14 +136,14 @@ func (r *Restore) SwapPITRDatabase(ctx context.Context, database string, timestarenameStmt := fmt.Sprintf("RENAME TABLE %s;", strings.Join(tableRenames, ", "))if _, err := txn.ExecContext(ctx, renameStmt); err != nil {- return err+ return pitrDatabaseName, pitrOldDatabase, err}if err := txn.Commit(); err != nil {- return err+ return pitrDatabaseName, pitrOldDatabase, err}- return nil+ return pitrDatabaseName, pitrOldDatabase, nil}func (r *Restore) databaseExists(ctx context.Context, database string) (bool, error) {@@ -155,28 +162,15 @@ func (r *Restore) databaseExists(ctx context.Context, database string) (bool, erreturn false, nil}-// DeleteOldDatabase deletes the old database after the PITR swap task.-func (r *Restore) DeleteOldDatabase(ctx context.Context, database string, suffixTs int64) error {- db, err := r.driver.GetDbConnection(ctx, "")- if err != nil {- return err- }-- pitrOldDatabase := getPITROldDatabaseName(database, suffixTs)- if _, err := db.ExecContext(ctx, fmt.Sprintf("DROP DATABASE `%s`;", pitrOldDatabase)); err != nil {- return err- }-- return nil-}--// getPITRDatabaseName composes a pitr database name+// Composes a pitr database name that we use as the target database for full backup recovery and binlog recovery.+// For example, getPITRDatabaseName("dbfoo", 1653018005) -> "dbfoo_pitr_1653018005"func getPITRDatabaseName(database string, suffixTs int64) string {suffix := fmt.Sprintf("pitr_%d", suffixTs)return getSafeName(database, suffix)}-// getPITROldDatabaseName composes a pitr database name+// Composes a database name that we use as the target database for swapping out the original database.+// For example, getPITROldDatabaseName("dbfoo", 1653018005) -> "dbfoo_pitr_1653018005_old"func getPITROldDatabaseName(database string, suffixTs int64) string {suffix := fmt.Sprintf("pitr_%d_old", suffixTs)return getSafeName(database, suffix)diff --git a/server/issue.go b/server/issue.goindex 1f2ac0e861..547af679ea 100644--- a/server/issue.go+++ b/server/issue.go@@ -939,25 +939,8 @@ func createPITRTaskList(database *api.Database, projectID int, taskStatus api.TaPayload: string(bytesCutover),})- // task: delete the original database- payloadDelete := api.TaskDatabasePITRDeletePayload{}- BytesDelete, err := json.Marshal(payloadDelete)- if err != nil {- return nil, nil, fmt.Errorf("failed to create PITR delete task, unable to marshal payload, error[%w]", err)- }-- taskCreateList = append(taskCreateList, api.TaskCreate{- Name: fmt.Sprintf("Delete the original database %s", database.Name),- InstanceID: database.InstanceID,- DatabaseID: &database.ID,- Status: taskStatus,- Type: api.TaskDatabasePITRDelete,- Payload: string(BytesDelete),- })-taskIndexDAGList := []api.TaskIndexDAG{{FromIndex: 0, ToIndex: 1},- {FromIndex: 1, ToIndex: 2},}return taskCreateList, taskIndexDAGList, nildiff --git a/server/server.go b/server/server.goindex a422b7a1e5..e9fbd28ff5 100644--- a/server/server.go+++ b/server/server.go@@ -192,6 +192,9 @@ func NewServer(ctx context.Context, prof Profile, logger *zap.Logger, loggerLevepitrRestoreExecutor := NewPITRRestoreTaskExecutor(logger, s.mysqlbinlog)taskScheduler.Register(string(api.TaskDatabasePITRRestore), pitrRestoreExecutor)+ pitrCutoverExecutor := NewPITRCutoverTaskExecutor(logger, s.mysqlbinlog)+ taskScheduler.Register(string(api.TaskDatabasePITRCutover), pitrCutoverExecutor)+s.TaskScheduler = taskScheduler// Task check schedulerdiff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.gonew file mode 100644index 0000000000..6fcea97324--- /dev/null+++ b/server/task_executor_pitr_cutover.go@@ -0,0 +1,77 @@+package server++import (+ "context"+ "fmt"++ "github.com/bytebase/bytebase/api"+ pluginmysql "github.com/bytebase/bytebase/plugin/db/mysql"+ restoremysql "github.com/bytebase/bytebase/plugin/restore/mysql"+ "github.com/bytebase/bytebase/resources/mysqlbinlog"+ "go.uber.org/zap"+)++// NewPITRCutoverTaskExecutor creates a PITR cutover task executor.+func NewPITRCutoverTaskExecutor(logger *zap.Logger, instance *mysqlbinlog.Instance) TaskExecutor {+ return &PITRCutoverTaskExecutor{+ l: logger,+ mysqlbinlog: instance,+ }+}++// PITRCutoverTaskExecutor is the PITR cutover task executor.+type PITRCutoverTaskExecutor struct {+ l *zap.Logger+ mysqlbinlog *mysqlbinlog.Instance+}++// RunOnce will run the PITR cutover task executor once.+func (exec *PITRCutoverTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {+ exec.l.Info("Run PITR cutover task", zap.String("task", task.Name))++ // Currently api.TaskDatabasePITRCutoverPayload is empty, so we do not need to unmarshal from task.Payload.++ return exec.pitrCutover(ctx, task, server)+}++func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, task *api.Task, server *Server) (terminated bool, result *api.TaskRunResultPayload, err error) {+ driver, err := getAdminDatabaseDriver(ctx, task.Instance, "", exec.l)+ if err != nil {+ return true, nil, err+ }+ defer driver.Close(ctx)++ issue, err := getIssueByPipelineID(ctx, server.store, exec.l, task.PipelineID)+ if err != nil {+ return true, nil, err+ }++ mysqlDriver, ok := driver.(*pluginmysql.Driver)+ if !ok {+ exec.l.Error("failed to cast driver to mysql.Driver", zap.Stack("stack"))+ return true, nil, fmt.Errorf("[internal] cast driver to mysql.Driver failed")+ }+ mysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlbinlog)++ exec.l.Info("Start swapping the original and PITR database",+ zap.String("instance", task.Instance.Name),+ zap.String("original_database", task.Database.Name),+ )+ pitrDatabaseName, pitrOldDatabaseName, err := mysqlRestore.SwapPITRDatabase(ctx, task.Database.Name, issue.CreatedTs)+ if err != nil {+ exec.l.Error("failed to swap the original and PITR database",+ zap.Int("issueID", issue.ID),+ zap.String("database", task.Database.Name),+ zap.Stack("stack"),+ zap.Error(err))+ return true, nil, fmt.Errorf("failed to swap the original and PITR database, error[%w]", err)+ }++ exec.l.Info("Finish swapping the original and PITR database",+ zap.String("original_database", task.Database.Name),+ zap.String("pitr_database", pitrDatabaseName),+ zap.String("old_database", pitrOldDatabaseName))+ return true, &api.TaskRunResultPayload{+ Detail: fmt.Sprintf("Swapped PITR database for target database %q", task.Database.Name),+ }, nil+}diff --git a/server/task_executor_pitr_delete.go b/server/task_executor_pitr_delete.godeleted file mode 100644index 213c1c2aff..0000000000--- a/server/task_executor_pitr_delete.go+++ /dev/null@@ -1,65 +0,0 @@-package server--import (- "context"- "fmt"-- "github.com/bytebase/bytebase/api"- pluginmysql "github.com/bytebase/bytebase/plugin/db/mysql"- restoremysql "github.com/bytebase/bytebase/plugin/restore/mysql"- "github.com/bytebase/bytebase/resources/mysqlbinlog"- "go.uber.org/zap"-)--// NewPITRDeleteTaskExecutor creates a PITR delete task executor.-func NewPITRDeleteTaskExecutor(logger *zap.Logger, instance *mysqlbinlog.Instance) TaskExecutor {- return &PITRDeleteTaskExecutor{- l: logger,- mysqlbinlogIns: instance,- }-}--// PITRDeleteTaskExecutor is the PITR delete task executor.-type PITRDeleteTaskExecutor struct {- l *zap.Logger- mysqlbinlogIns *mysqlbinlog.Instance-}--// RunOnce will run the PITR delete task executor once.-func (exec *PITRDeleteTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {- exec.l.Info("Run PITR delete task", zap.String("task", task.Name))-- // api.TaskDatabasePITRDeletePayload is empty, do not need to unmarshal json-- driver, err := getAdminDatabaseDriver(ctx, task.Instance, "", exec.l)- if err != nil {- return true, nil, err- }- defer driver.Close(ctx)- mysqlDriver, ok := driver.(*pluginmysql.Driver)- if !ok {- exec.l.Error("failed to cast driver to mysql.Driver", zap.Stack("stack"))- return true, nil, fmt.Errorf("[internal] cast driver to mysql.Driver failed")- }-- issue, err := server.store.GetIssueByPipelineID(ctx, task.PipelineID)- if err != nil || issue == nil {- exec.l.Error("failed to get issue by PipelineID",- zap.Int("PipelineID", task.PipelineID),- zap.Error(err))- return true, nil, fmt.Errorf("failed to get issue by PipelineID[%d], error[%w]", task.PipelineID, err)- }-- mysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlbinlogIns)- if err := mysqlRestore.DeleteOldDatabase(ctx, task.Database.Name, issue.CreatedTs); err != nil {- exec.l.Error("failed to delete the original database after PITR swap",- zap.String("instance", task.Instance.Name),- zap.String("original database", task.Database.Name))- return true, nil, fmt.Errorf("failed to delete the original database after PITR swap, error[%w]", err)- }-- exec.l.Info("delete original PITR database", zap.String("target database", task.Database.Name))- return true, &api.TaskRunResultPayload{- Detail: fmt.Sprintf("Delete original PITR database for target database %q", task.Database.Name),- }, nil-}diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex 37e8be6812..d2c0c25553 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -19,15 +19,15 @@ import (// NewPITRRestoreTaskExecutor creates a PITR restore task executor.func NewPITRRestoreTaskExecutor(logger *zap.Logger, instance *mysqlbinlog.Instance) TaskExecutor {return &PITRRestoreTaskExecutor{- l: logger,- mysqlbinlogIns: instance,+ l: logger,+ mysqlbinlog: instance,}}// PITRRestoreTaskExecutor is the PITR restore task executor.type PITRRestoreTaskExecutor struct {- l *zap.Logger- mysqlbinlogIns *mysqlbinlog.Instance+ l *zap.Logger+ mysqlbinlog *mysqlbinlog.Instance}// RunOnce will run the PITR restore task executor once.@@ -66,12 +66,9 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apinstance := task.Instancedatabase := task.Database- issue, err := store.GetIssueByPipelineID(ctx, task.PipelineID)- if err != nil || issue == nil {- exec.l.Error("failed to get issue by PipelineID",- zap.Int("PipelineID", task.PipelineID),- zap.Error(err))- return fmt.Errorf("failed to get issue by PipelineID[%d], error[%w]", task.PipelineID, err)+ issue, err := getIssueByPipelineID(ctx, store, exec.l, task.PipelineID)+ if err != nil {+ return err}mysqlDriver, ok := driver.(*pluginmysql.Driver)@@ -80,7 +77,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apreturn fmt.Errorf("[internal] cast driver to mysql.Driver failed")}- mysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlbinlogIns)+ mysqlRestore := restoremysql.New(mysqlDriver, exec.mysqlbinlog)config := pluginmysql.BinlogInfo{}// TODO(dragonly): Search and put the file io of the logical backup file here.// Currently, let's just use the empty backup dump as a placeholder.@@ -106,3 +103,16 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *apreturn nil}++func getIssueByPipelineID(ctx context.Context, store *store.Store, l *zap.Logger, pid int) (*api.Issue, error) {+ issue, err := store.GetIssueByPipelineID(ctx, pid)+ if err != nil {+ l.Error("failed to get issue by PipelineID", zap.Int("PipelineID", pid), zap.Error(err))+ return nil, fmt.Errorf("failed to get issue by PipelineID[%d], error[%w]", pid, err)+ }+ if issue == nil {+ l.Error("issue not found with PipelineID", zap.Int("PipelineID", pid))+ return nil, fmt.Errorf("issue not found with PipelineID[%d]", pid)+ }+ return issue, nil+}diff --git a/tests/backup_restore_test.go b/tests/backup_restore_test.goindex d7882679be..90a638f399 100644--- a/tests/backup_restore_test.go+++ b/tests/backup_restore_test.go@@ -179,7 +179,7 @@ func TestPITR(t *testing.T) {// We mimics the situation where the user waits for the target database idle before doing the cutover.time.Sleep(time.Second)- err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)+ _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)a.NoError(err)t.Log("validate table tbl0")@@ -251,9 +251,8 @@ func TestPITR(t *testing.T) {a.NoError(err)t.Log("cutover stage")- // TODO(zp): Recheck here when SwapPITRDatabase can handle the case that the original database does not exist- err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)- a.Error(err)+ _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)+ a.NoError(err)})t.Run("Schema Migration Failure", func(t *testing.T) {@@ -309,7 +308,7 @@ func TestPITR(t *testing.T) {// We mimics the situation where the user waits for the target database idle before doing the cutover.time.Sleep(time.Second)- err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)+ _, _, err = mysqlRestore.SwapPITRDatabase(ctx, database, createPITRIssueTimestamp)a.NoError(err)t.Log("validate table tbl0")