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: ghost task executor (#15203)
p0ny78f3d83193a9
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.goindex 5cf2394f86..cfa90b7b02 100644--- a/backend/api/v1/plan_service.go+++ b/backend/api/v1/plan_service.go@@ -438,9 +438,13 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *v1pb.UpdatePlanRe// Flags for gh-ost.if err := func() error {- if task.Type != api.TaskDatabaseSchemaUpdateGhostSync {+ switch task.Type {+ case api.TaskDatabaseSchemaUpdateGhost:+ case api.TaskDatabaseSchemaUpdateGhostSync:+ default:return nil}+payload := &storepb.TaskDatabaseUpdatePayload{}if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(task.Payload), payload); err != nil {return status.Errorf(codes.Internal, "failed to unmarshal task payload: %v", err)diff --git a/backend/api/v1/rollout_service_converter.go b/backend/api/v1/rollout_service_converter.goindex 8fa7dfe224..bb81a39cca 100644--- a/backend/api/v1/rollout_service_converter.go+++ b/backend/api/v1/rollout_service_converter.go@@ -704,7 +704,7 @@ func convertToTask(ctx context.Context, s *store.Store, project *store.ProjectMereturn convertToTaskFromDatabaseCreate(ctx, s, project, task)case api.TaskDatabaseSchemaBaseline:return convertToTaskFromSchemaBaseline(ctx, s, project, task)- case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateSDL, api.TaskDatabaseSchemaUpdateGhostSync:+ case api.TaskDatabaseSchemaUpdate, api.TaskDatabaseSchemaUpdateSDL, api.TaskDatabaseSchemaUpdateGhost, api.TaskDatabaseSchemaUpdateGhostSync:return convertToTaskFromSchemaUpdate(ctx, s, project, task)case api.TaskDatabaseSchemaUpdateGhostCutover:return convertToTaskFromSchemaUpdateGhostCutover(ctx, s, project, task)diff --git a/backend/api/v1/rollout_service_task.go b/backend/api/v1/rollout_service_task.goindex fea3066e76..e8a5824fa8 100644--- a/backend/api/v1/rollout_service_task.go+++ b/backend/api/v1/rollout_service_task.go@@ -471,6 +471,40 @@ func getTaskCreatesFromChangeDatabaseConfigDatabaseTarget(ctx context.Context, sreturn []*store.TaskMessage{taskCreate}, nil, nilcase storepb.PlanConfig_ChangeDatabaseConfig_MIGRATE_GHOST:+ if common.IsDev() {+ _, sheetUID, err := common.GetProjectResourceIDSheetUID(c.Sheet)+ if err != nil {+ return nil, nil, errors.Wrapf(err, "failed to get sheet id from sheet %q", c.Sheet)+ }+ if _, err := ghost.GetUserFlags(c.GhostFlags); err != nil {+ return nil, nil, errors.Wrapf(err, "invalid ghost flags %q", c.GhostFlags)+ }+ payload := &storepb.TaskDatabaseUpdatePayload{+ SpecId: spec.Id,+ SheetId: int32(sheetUID),+ SchemaVersion: c.SchemaVersion,+ Flags: c.GhostFlags,+ TaskReleaseSource: &storepb.TaskReleaseSource{+ File: spec.SpecReleaseSource.GetFile(),+ },+ }+ bytes, err := protojson.Marshal(payload)+ if err != nil {+ return nil, nil, errors.Wrapf(err, "failed to marshal database schema update ghost payload")+ }+ taskCreate := &store.TaskMessage{+ Name: fmt.Sprintf("DDL(gh-ost) for database %q", database.DatabaseName),+ InstanceID: database.InstanceID,+ DatabaseName: &database.DatabaseName,+ Type: api.TaskDatabaseSchemaUpdateGhost,+ Payload: string(bytes),+ }+ if spec.EarliestAllowedTime.GetSeconds() > 0 {+ t := spec.EarliestAllowedTime.AsTime()+ taskCreate.EarliestAllowedAt = &t+ }+ return []*store.TaskMessage{taskCreate}, nil, nil+ }_, sheetUID, err := common.GetProjectResourceIDSheetUID(c.Sheet)if err != nil {return nil, nil, errors.Wrapf(err, "failed to get sheet id from sheet %q", c.Sheet)diff --git a/backend/legacyapi/task.go b/backend/legacyapi/task.goindex b0a79f7330..c0665c0a34 100644--- a/backend/legacyapi/task.go+++ b/backend/legacyapi/task.go@@ -40,9 +40,13 @@ const (TaskDatabaseSchemaUpdate TaskType = "bb.task.database.schema.update"// TaskDatabaseSchemaUpdateSDL is the task type for updating database schemas via state-based migration.TaskDatabaseSchemaUpdateSDL TaskType = "bb.task.database.schema.update-sdl"+ // TaskDatabaseSchemaUpdateGhost is the task type for updating database schemas using gh-ost.+ TaskDatabaseSchemaUpdateGhost TaskType = "bb.task.database.schema.update-ghost"// TaskDatabaseSchemaUpdateGhostSync is the task type for gh-ost syncing ghost table.+ // TODO(p0ny): deprecated by TaskDatabaseSchemaUpdateGhost.TaskDatabaseSchemaUpdateGhostSync TaskType = "bb.task.database.schema.update.ghost.sync"// TaskDatabaseSchemaUpdateGhostCutover is the task type for gh-ost switching the original table and the ghost table.+ // TODO(p0ny): deprecated by TaskDatabaseSchemaUpdateGhost.TaskDatabaseSchemaUpdateGhostCutover TaskType = "bb.task.database.schema.update.ghost.cutover"// TaskDatabaseDataUpdate is the task type for updating database data.TaskDatabaseDataUpdate TaskType = "bb.task.database.data.update"diff --git a/backend/runner/taskrun/database_create_executor.go b/backend/runner/taskrun/database_create_executor.goindex c32133d23b..d04bf7cae1 100644--- a/backend/runner/taskrun/database_create_executor.go+++ b/backend/runner/taskrun/database_create_executor.go@@ -388,7 +388,14 @@ func (exec *DatabaseCreateExecutor) createInitialSchema(ctx context.Context, drimc.issueName = common.FormatIssue(issue.Project.ResourceID, issue.UID)}- if _, err := executeMigrationDefault(ctx, driverCtx, exec.store, exec.stateCfg, driver, mc, schema, db.ExecuteOptions{}); err != nil {+ opts := db.ExecuteOptions{}+ execFunc := func(ctx context.Context, execStatement string) error {+ if _, err := driver.Execute(ctx, execStatement, opts); err != nil {+ return err+ }+ return nil+ }+ if _, err := executeMigrationWithFunc(ctx, driverCtx, exec.store, mc, schema, execFunc, opts); err != nil {return nil, "", "", err}return peerDatabase, schemaVersion, schema, nildiff --git a/backend/runner/taskrun/executor.go b/backend/runner/taskrun/executor.goindex f025dd264f..cb70c43f08 100644--- a/backend/runner/taskrun/executor.go+++ b/backend/runner/taskrun/executor.go@@ -36,6 +36,8 @@ type Executor interface {RunOnce(ctx context.Context, driverCtx context.Context, task *store.TaskMessage, taskRunUID int) (terminated bool, result *storepb.TaskRunResult, err error)}+type execFuncType func(context.Context, string) error+// RunExecutorOnce wraps a TaskExecutor.RunOnce call with panic recovery.func RunExecutorOnce(ctx context.Context, driverCtx context.Context, exec Executor, task *store.TaskMessage, taskRunUID int) (terminated bool, result *storepb.TaskRunResult, err error) {defer func() {@@ -242,7 +244,7 @@ func getUseDatabaseOwner(ctx context.Context, stores *store.Store, instance *storeturn project.Setting.PostgresDatabaseTenantMode, nil}-func doMigration(+func doMigrationWithFunc(ctx context.Context,driverCtx context.Context,stores *store.Store,@@ -250,6 +252,7 @@ func doMigration(profile *config.Profile,statement string,mc *migrateContext,+ execFunc execFuncType,) (bool, error) {instance := mc.instancedatabase := mc.database@@ -299,7 +302,15 @@ func doMigration(}}- return executeMigrationDefault(ctx, driverCtx, stores, stateCfg, driver, mc, statement, opts)+ if execFunc == nil {+ execFunc = func(ctx context.Context, execStatement string) error {+ if _, err := driver.Execute(ctx, execStatement, opts); err != nil {+ return err+ }+ return nil+ }+ }+ return executeMigrationWithFunc(ctx, driverCtx, stores, mc, statement, execFunc, opts)}func postMigration(ctx context.Context, stores *store.Store, mc *migrateContext, skipped bool) (bool, *storepb.TaskRunResult, error) {@@ -342,28 +353,21 @@ func postMigration(ctx context.Context, stores *store.Store, mc *migrateContext,}, nil}-func runMigration(ctx context.Context, driverCtx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, syncer *schemasync.Syncer, profile *config.Profile, task *store.TaskMessage, taskRunUID int, migrationType db.MigrationType, statement string, schemaVersion string, sheetID *int) (terminated bool, result *storepb.TaskRunResult, err error) {+func runMigrationWithFunc(ctx context.Context, driverCtx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, syncer *schemasync.Syncer, profile *config.Profile, task *store.TaskMessage, taskRunUID int, migrationType db.MigrationType, statement string, schemaVersion string, sheetID *int, execFunc execFuncType) (terminated bool, result *storepb.TaskRunResult, err error) {mc, err := getMigrationInfo(ctx, store, profile, syncer, task, migrationType, schemaVersion, sheetID, taskRunUID, dbFactory)if err != nil {return true, nil, err}- skipped, err := doMigration(ctx, driverCtx, store, stateCfg, profile, statement, mc)+ skipped, err := doMigrationWithFunc(ctx, driverCtx, store, stateCfg, profile, statement, mc, execFunc)if err != nil {return true, nil, err}return postMigration(ctx, store, mc, skipped)}-// executeMigrationDefault executes migration.-func executeMigrationDefault(ctx context.Context, driverCtx context.Context, store *store.Store, _ *state.State, driver db.Driver, mc *migrateContext, statement string, opts db.ExecuteOptions) (skipped bool, resErr error) {- execFunc := func(ctx context.Context, execStatement string) error {- if _, err := driver.Execute(ctx, execStatement, opts); err != nil {- return err- }- return nil- }- return executeMigrationWithFunc(ctx, driverCtx, store, mc, statement, execFunc, opts)+func runMigration(ctx context.Context, driverCtx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, stateCfg *state.State, syncer *schemasync.Syncer, profile *config.Profile, task *store.TaskMessage, taskRunUID int, migrationType db.MigrationType, statement string, schemaVersion string, sheetID *int) (terminated bool, result *storepb.TaskRunResult, err error) {+ return runMigrationWithFunc(ctx, driverCtx, store, dbFactory, stateCfg, syncer, profile, task, taskRunUID, migrationType, statement, schemaVersion, sheetID, nil /* default */)}// executeMigrationWithFunc executes the migration with custom migration function.diff --git a/backend/runner/taskrun/schema_update_ghost_executor.go b/backend/runner/taskrun/schema_update_ghost_executor.gonew file mode 100644index 0000000000..31c72dbe61--- /dev/null+++ b/backend/runner/taskrun/schema_update_ghost_executor.go@@ -0,0 +1,159 @@+package taskrun++import (+ "context"+ "log/slog"+ "strings"+ "time"++ "github.com/github/gh-ost/go/logic"+ gomysql "github.com/go-sql-driver/mysql"+ "github.com/pkg/errors"++ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/common/log"+ "github.com/bytebase/bytebase/backend/component/config"+ "github.com/bytebase/bytebase/backend/component/dbfactory"+ "github.com/bytebase/bytebase/backend/component/ghost"+ "github.com/bytebase/bytebase/backend/component/state"+ enterprise "github.com/bytebase/bytebase/backend/enterprise/api"+ api "github.com/bytebase/bytebase/backend/legacyapi"+ "github.com/bytebase/bytebase/backend/plugin/db"+ "github.com/bytebase/bytebase/backend/runner/schemasync"+ "github.com/bytebase/bytebase/backend/store"+ "github.com/bytebase/bytebase/backend/utils"+ storepb "github.com/bytebase/bytebase/proto/generated-go/store"+)++// NewSchemaUpdateGhostExecutor creates a schema update (gh-ost) task executor.+func NewSchemaUpdateGhostExecutor(s *store.Store, secret string, dbFactory *dbfactory.DBFactory, license enterprise.LicenseService, stateCfg *state.State, schemaSyncer *schemasync.Syncer, profile *config.Profile) Executor {+ return &SchemaUpdateGhostExecutor{+ s: s,+ secret: secret,+ dbFactory: dbFactory,+ license: license,+ stateCfg: stateCfg,+ schemaSyncer: schemaSyncer,+ profile: profile,+ }+}++// SchemaUpdateGhostExecutor is the schema update (gh-ost) task executor.+type SchemaUpdateGhostExecutor struct {+ s *store.Store+ secret string+ dbFactory *dbfactory.DBFactory+ license enterprise.LicenseService+ stateCfg *state.State+ schemaSyncer *schemasync.Syncer+ profile *config.Profile+}++func (exec *SchemaUpdateGhostExecutor) RunOnce(ctx context.Context, driverCtx context.Context, task *store.TaskMessage, taskRunUID int) (bool, *storepb.TaskRunResult, error) {+ payload := &storepb.TaskDatabaseUpdatePayload{}+ if err := common.ProtojsonUnmarshaler.Unmarshal([]byte(task.Payload), payload); err != nil {+ return true, nil, errors.Wrap(err, "invalid database schema update gh-ost sync payload")+ }+ sheetID := int(payload.SheetId)+ statement, err := exec.s.GetSheetStatementByID(ctx, int(payload.SheetId))+ if err != nil {+ return true, nil, err+ }+ flags := payload.Flags++ instance, err := exec.s.GetInstanceV2(ctx, &store.FindInstanceMessage{ResourceID: &task.InstanceID})+ if err != nil {+ return true, nil, err+ }+ if instance == nil {+ return true, nil, errors.Errorf("instance %s not found", task.InstanceID)+ }+ database, err := exec.s.GetDatabaseV2(ctx, &store.FindDatabaseMessage{InstanceID: &task.InstanceID, DatabaseName: task.DatabaseName})+ if err != nil {+ return true, nil, err+ }+ if database == nil {+ return true, nil, errors.Errorf("database not found")+ }++ execFunc := func(execCtx context.Context, execStatement string) error {+ // set buffer size to 1 to unblock the sender because there is no listener if the task is canceled.+ migrationError := make(chan error, 1)++ statement := strings.TrimSpace(execStatement)++ tableName, err := ghost.GetTableNameFromStatement(statement)+ if err != nil {+ return err+ }++ adminDataSource := utils.DataSourceFromInstanceWithType(instance, api.Admin)+ if adminDataSource == nil {+ return common.Errorf(common.Internal, "admin data source not found for instance %s", instance.ResourceID)+ }++ migrationContext, err := ghost.NewMigrationContext(ctx, task.ID, database, adminDataSource, exec.secret, tableName, "", execStatement, false, flags, 10000000)+ if err != nil {+ return errors.Wrap(err, "failed to init migrationContext for gh-ost")+ }+ defer func() {+ // Use migrationContext.Uuid as the tls_config_key by convention.+ // We need to deregister it when gh-ost exits.+ // https://github.com/bytebase/gh-ost2/pull/4+ gomysql.DeregisterTLSConfig(migrationContext.Uuid)+ }()+ // TODO(p0ny): unset in NewMigrationContext.+ migrationContext.PostponeCutOverFlagFile = ""++ migrator := logic.NewMigrator(migrationContext, "bb")++ go func() {+ if err := migrator.Migrate(); err != nil {+ slog.Error("failed to run gh-ost migration", log.BBError(err))+ migrationError <- err+ return+ }+ migrationError <- nil+ }()++ select {+ case err := <-migrationError:+ if err != nil {+ return err+ }+ return nil+ case <-execCtx.Done():+ migrationContext.PanicAbort <- errors.New("task canceled")+ return errors.New("task canceled")+ }+ }++ terminated, result, err := runMigrationWithFunc(ctx, driverCtx, exec.s, exec.dbFactory, exec.stateCfg, exec.schemaSyncer, exec.profile, task, taskRunUID, db.Migrate, statement, payload.SchemaVersion, &sheetID, execFunc)+ // sync database schema anyways+ exec.s.CreateTaskRunLogS(ctx, taskRunUID, time.Now(), exec.profile.DeployID, &storepb.TaskRunLog{+ Type: storepb.TaskRunLog_DATABASE_SYNC_START,+ DatabaseSyncStart: &storepb.TaskRunLog_DatabaseSyncStart{},+ })+ if err := exec.schemaSyncer.SyncDatabaseSchema(ctx, database, false /* force */); err != nil {+ exec.s.CreateTaskRunLogS(ctx, taskRunUID, time.Now(), exec.profile.DeployID, &storepb.TaskRunLog{+ Type: storepb.TaskRunLog_DATABASE_SYNC_END,+ DatabaseSyncEnd: &storepb.TaskRunLog_DatabaseSyncEnd{+ Error: err.Error(),+ },+ })+ slog.Error("failed to sync database schema",+ slog.String("instanceName", instance.ResourceID),+ slog.String("databaseName", database.DatabaseName),+ log.BBError(err),+ )+ } else {+ exec.s.CreateTaskRunLogS(ctx, taskRunUID, time.Now(), exec.profile.DeployID, &storepb.TaskRunLog{+ Type: storepb.TaskRunLog_DATABASE_SYNC_END,+ DatabaseSyncEnd: &storepb.TaskRunLog_DatabaseSyncEnd{+ Error: "",+ },+ })+ }++ return terminated, result, err+}diff --git a/backend/server/server.go b/backend/server/server.goindex 065b938186..f1e0e7d770 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -289,6 +289,7 @@ func NewServer(ctx context.Context, profile *config.Profile) (*Server, error) {s.taskSchedulerV2.Register(api.TaskDatabaseSchemaUpdateSDL, taskrun.NewSchemaUpdateSDLExecutor(storeInstance, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, profile))s.taskSchedulerV2.Register(api.TaskDatabaseDataUpdate, taskrun.NewDataUpdateExecutor(storeInstance, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, profile))s.taskSchedulerV2.Register(api.TaskDatabaseDataExport, taskrun.NewDataExportExecutor(storeInstance, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, profile))+ s.taskSchedulerV2.Register(api.TaskDatabaseSchemaUpdateGhost, taskrun.NewSchemaUpdateGhostExecutor(storeInstance, s.secret, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, s.profile))s.taskSchedulerV2.Register(api.TaskDatabaseSchemaUpdateGhostSync, taskrun.NewSchemaUpdateGhostSyncExecutor(storeInstance, s.stateCfg, s.secret))s.taskSchedulerV2.Register(api.TaskDatabaseSchemaUpdateGhostCutover, taskrun.NewSchemaUpdateGhostCutoverExecutor(storeInstance, s.dbFactory, s.licenseService, s.stateCfg, s.schemaSyncer, profile))