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(backend): gh-ost sync task check (#1687)
p0ny5a0ddfb46a01
diff --git a/api/task_check_run.go b/api/task_check_run.goindex 55c1ef9c8f..9d55c5d765 100644--- a/api/task_check_run.go+++ b/api/task_check_run.go@@ -79,6 +79,8 @@ const (TaskCheckDatabaseConnect TaskCheckType = "bb.task-check.database.connect"// TaskCheckInstanceMigrationSchema is the task check type for migrating schemas.TaskCheckInstanceMigrationSchema TaskCheckType = "bb.task-check.instance.migration-schema"+ // TaskCheckGhostSync is the task check type for the gh-ost sync task.+ TaskCheckGhostSync TaskCheckType = "bb.task-check.database.ghost.sync"// TaskCheckGeneralEarliestAllowedTime is the task check type for earliest allowed time.TaskCheckGeneralEarliestAllowedTime TaskCheckType = "bb.task-check.general.earliest-allowed-time")diff --git a/server/server.go b/server/server.goindex 409696b33d..ddb675ded2 100644--- a/server/server.go+++ b/server/server.go@@ -228,6 +228,9 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {migrationSchemaExecutor := NewTaskCheckMigrationSchemaExecutor()taskCheckScheduler.Register(api.TaskCheckInstanceMigrationSchema, migrationSchemaExecutor)+ ghostSyncExecutor := NewTaskCheckGhostSyncExecutor()+ taskCheckScheduler.Register(api.TaskCheckGhostSync, ghostSyncExecutor)+timingExecutor := NewTaskCheckTimingExecutor()taskCheckScheduler.Register(api.TaskCheckGeneralEarliestAllowedTime, timingExecutor)diff --git a/server/task.go b/server/task.goindex 8149ce4943..1e9c8bd231 100644--- a/server/task.go+++ b/server/task.go@@ -194,6 +194,23 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to create activity after updating task statement: %v", taskPatched.Name)).SetInternal(err)}+ if taskPatched.Type == api.TaskDatabaseSchemaUpdateGhostSync {+ _, err = s.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{+ CreatorID: taskPatched.CreatorID,+ TaskID: task.ID,+ Type: api.TaskCheckGhostSync,+ SkipIfAlreadyTerminated: false,+ })+ if err != nil {+ // It's OK if we failed to trigger a check, just emit an error log+ log.Error("Failed to trigger gh-ost dry run after changing the task statement",+ zap.Int("task_id", task.ID),+ zap.String("task_name", task.Name),+ zap.Error(err),+ )+ }+ }+if api.IsSyntaxCheckSupported(task.Database.Instance.Engine) {payload, err := json.Marshal(api.TaskCheckDatabaseStatementAdvisePayload{Statement: *taskPatch.Statement,@@ -213,7 +230,7 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {})if err != nil {// It's OK if we failed to trigger a check, just emit an error log- log.Error("Failed to trigger syntax check after changing task statement",+ log.Error("Failed to trigger syntax check after changing the task statement",zap.Int("task_id", task.ID),zap.String("task_name", task.Name),zap.Error(err),diff --git a/server/task_check_executor_ghost_sync.go b/server/task_check_executor_ghost_sync.gonew file mode 100644index 0000000000..81403e94a4--- /dev/null+++ b/server/task_check_executor_ghost_sync.go@@ -0,0 +1,130 @@+package server++import (+ "context"+ "encoding/json"+ "fmt"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "github.com/github/gh-ost/go/logic"+)++// NewTaskCheckGhostSyncExecutor creates a task check gh-ost sync executor.+func NewTaskCheckGhostSyncExecutor() TaskCheckExecutor {+ return &TaskCheckGhostSyncExecutor{}+}++// TaskCheckGhostSyncExecutor is the task check gh-ost sync executor.+type TaskCheckGhostSyncExecutor struct {+}++// Run will run the task check database connector executor once.+func (exec *TaskCheckGhostSyncExecutor) Run(ctx context.Context, server *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {+ // gh-ost dry run could panic.+ // It may be bytebase who panicked, but that's rare. So+ // capture the error and send it into the result list.+ defer func() {+ if r := recover(); r != nil {+ panicErr, ok := r.(error)+ if !ok {+ panicErr = fmt.Errorf("%v", r)+ }+ result = []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.BBNamespace,+ Code: common.Internal.Int(),+ Title: "gh-ost dry run failed",+ Content: panicErr.Error(),+ },+ }+ err = nil+ }+ }()+ task, err := server.store.GetTaskByID(ctx, taskCheckRun.TaskID)+ if err != nil {+ return []api.TaskCheckResult{}, common.Errorf(common.Internal, err)+ }+ if task == nil {+ return []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.BBNamespace,+ Code: common.Internal.Int(),+ Title: fmt.Sprintf("Failed to find task %v", taskCheckRun.TaskID),+ Content: err.Error(),+ },+ }, nil+ }++ instance := task.Instance+ if instance == nil {+ return []api.TaskCheckResult{}, common.Errorf(common.Internal, fmt.Errorf("instance ID not found %v", task.InstanceID))+ }++ database := task.Database+ if database == nil {+ return []api.TaskCheckResult{}, common.Errorf(common.Internal, fmt.Errorf("database ID not found %v", task.DatabaseID))+ }++ adminDataSource := api.DataSourceFromInstanceWithType(instance, api.Admin)+ if adminDataSource == nil {+ return []api.TaskCheckResult{}, common.Errorf(common.Internal, fmt.Errorf("admin data source not found for instance %d", instance.ID))+ }++ payload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {+ return []api.TaskCheckResult{}, common.Errorf(common.Internal, fmt.Errorf("invalid database schema update gh-ost sync payload: %w", err))+ }++ databaseName := database.Name+ tableName, err := getTableNameFromStatement(payload.Statement)+ if err != nil {+ return []api.TaskCheckResult{}, common.Errorf(common.Internal, fmt.Errorf("failed to parse table name from statement, statement: %v, error: %w", payload.Statement, err))+ }++ migrationContext, err := newMigrationContext(ghostConfig{+ host: instance.Host,+ port: instance.Port,+ user: adminDataSource.Username,+ password: adminDataSource.Password,+ database: databaseName,+ table: tableName,+ alterStatement: payload.Statement,+ socketFilename: getSocketFilename(taskCheckRun.ID, task.Database.ID, databaseName, tableName),+ postponeFlagFilename: getPostponeFlagFilename(taskCheckRun.ID, task.Database.ID, databaseName, tableName),+ noop: true,+ // On the source and each replica, you must set the server_id system variable to establish a unique replication ID. For each server, you should pick a unique positive integer in the range from 1 to 2^32 − 1, and each ID must be different from every other ID in use by any other source or replica in the replication topology. Example: server-id=3.+ // https://dev.mysql.com/doc/refman/5.7/en/replication-options-source.html+ // Here we use serverID = offset + task.ID to avoid potential conflicts.+ serverID: 20000000 + uint(taskCheckRun.ID),+ })+ if err != nil {+ return []api.TaskCheckResult{}, common.Errorf(common.Internal, fmt.Errorf("failed to create migration context, error: %w", err))+ }++ migrator := logic.NewMigrator(migrationContext)++ if err := migrator.Migrate(); err != nil {+ return []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusError,+ Namespace: api.BBNamespace,+ Code: common.Internal.Int(),+ Title: "gh-ost dry run failed",+ Content: err.Error(),+ },+ }, nil+ }++ return []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusSuccess,+ Namespace: api.BBNamespace,+ Code: common.Ok.Int(),+ Title: "OK",+ Content: "gh-ost dry run succeeded",+ },+ }, nil+}diff --git a/server/task_check_scheduler.go b/server/task_check_scheduler.goindex e540a24ca6..70fb836e4b 100644--- a/server/task_check_scheduler.go+++ b/server/task_check_scheduler.go@@ -247,21 +247,28 @@ func (s *TaskCheckScheduler) ScheduleCheckIfNeeded(ctx context.Context, task *ap}}- if task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseDataUpdate {+ if task.Type == api.TaskDatabaseSchemaUpdate || task.Type == api.TaskDatabaseDataUpdate || task.Type == api.TaskDatabaseSchemaUpdateGhostSync {statement := ""- if task.Type == api.TaskDatabaseSchemaUpdate {+ switch task.Type {+ case api.TaskDatabaseSchemaUpdate:taskPayload := &api.TaskDatabaseSchemaUpdatePayload{}if err := json.Unmarshal([]byte(task.Payload), taskPayload); err != nil {return nil, fmt.Errorf("invalid database schema update payload: %w", err)}statement = taskPayload.Statement- } else {+ case api.TaskDatabaseDataUpdate:taskPayload := &api.TaskDatabaseDataUpdatePayload{}if err := json.Unmarshal([]byte(task.Payload), taskPayload); err != nil {return nil, fmt.Errorf("invalid database data update payload: %w", err)}statement = taskPayload.Statement+ case api.TaskDatabaseSchemaUpdateGhostSync:+ taskPayload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}+ if err := json.Unmarshal([]byte(task.Payload), taskPayload); err != nil {+ return nil, fmt.Errorf("invalid database data update payload: %w", err)+ }+ statement = taskPayload.Statement}database, err := s.server.store.GetDatabase(ctx, &api.DatabaseFind{ID: task.DatabaseID})@@ -292,6 +299,18 @@ func (s *TaskCheckScheduler) ScheduleCheckIfNeeded(ctx context.Context, task *apreturn nil, err}+ if task.Type == api.TaskDatabaseSchemaUpdateGhostSync {+ _, err = s.server.store.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{+ CreatorID: creatorID,+ TaskID: task.ID,+ Type: api.TaskCheckGhostSync,+ SkipIfAlreadyTerminated: skipIfAlreadyTerminated,+ })+ if err != nil {+ return nil, err+ }+ }+if api.IsSyntaxCheckSupported(database.Instance.Engine) {payload, err := json.Marshal(api.TaskCheckDatabaseStatementAdvisePayload{Statement: statement,