Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(gh-ost): gh-ost task executor implementation (phase 2) (#1315)

p0ny2eb4762c44de
diff --git a/docs/design/gh-ost-integration.md b/docs/design/gh-ost-integration.md
index da15408085..987cb521c9 100644
--- a/docs/design/gh-ost-integration.md
+++ b/docs/design/gh-ost-integration.md
@@ -319,7 +319,7 @@ We will have two tasks for the actual migration. The first task runs gh-ost and
These two tasks need to access the same `Migrator`. Unfortunately, the way we schedule tasks now is not capable of it. Fortunately, we can leverage the Unix socket file that the gh-ost migrator listens on. When the ghost table catches up with the original table, the "run" task will switch to `DONE`, and the "cut-over" task will be `PENDING_APPROVAL`. The "cut-over" task sends `"cut-over"` to the socket file to execute cut-over.
-The socket file is in `/tmp` directory, so the operating system will clean it up and we won't bother removing it. The socket file name will be `./tmp/gh-ost.{{ISSUE_ID}}.{{TASK_ID}}.{{DATABASE_ID}}.{{DATABASE_NAME}}.{{TABLE_NAME}}.{{TIMESTAMP}}.sock`.
+The socket file is in `/tmp` directory, so the operating system will clean it up and we won't bother removing it. The socket file name will be `./tmp/gh-ost.{{TASK_ID}}.{{DATABASE_ID}}.{{DATABASE_NAME}}.{{TABLE_NAME}}.sock`.
We will have task checks for both tasks. For the "run" task, we have `TaskCheckDatabaseSchemaUpdateGhost` mentioned above. For the "cut-over" task, we will have a task check to check whether it is good to cut-over now (in sync, network lags good, etc.)
diff --git a/server/issue.go b/server/issue.go
index c3017bee4a..4d9341622d 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -9,7 +9,6 @@ import (
"strconv"
"strings"
- ghostsql "github.com/github/gh-ost/go/sql"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
@@ -970,11 +969,12 @@ func createGhostTaskList(database *api.Database, vcsPushEvent *vcs.PushEvent, de
})
// task "drop original table"
- parser := ghostsql.NewParserFromAlterStatement(detail.Statement)
- tableName := ""
- if parser.HasExplicitTable() {
- tableName = fmt.Sprintf("_%v_del", parser.GetExplicitTable())
+ tableName, err := getTableNameFromStatement(detail.Statement)
+ if err != nil {
+ return nil, nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("failed to parse table name, error: %v", err))
}
+ tableName = fmt.Sprintf("_%v_del", tableName)
+
payloadDrop := api.TaskDatabaseSchemaUpdateGhostDropOriginalTablePayload{
DatabaseName: database.Name,
TableName: tableName,
diff --git a/server/task_check_scheduler.go b/server/task_check_scheduler.go
index a246352ce9..141d44d699 100644
--- a/server/task_check_scheduler.go
+++ b/server/task_check_scheduler.go
@@ -404,7 +404,7 @@ func (s *Server) passCheck(ctx context.Context, server *Server, task *api.Task,
return false, err
}
for _, result := range checkResult.ResultList {
- if result.Status == api.TaskCheckStatusError || result.Status == api.TaskCheckStatusWarn {
+ if result.Status == api.TaskCheckStatusError {
server.l.Debug("Task is waiting for check to pass",
zap.Int("task_id", task.ID),
zap.String("task_name", task.Name),
diff --git a/server/task_executor_schema_update_ghost_cutover.go b/server/task_executor_schema_update_ghost_cutover.go
index f50857cd86..a715898c10 100644
--- a/server/task_executor_schema_update_ghost_cutover.go
+++ b/server/task_executor_schema_update_ghost_cutover.go
@@ -2,6 +2,11 @@ package server
import (
"context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "strings"
+ "time"
"github.com/bytebase/bytebase/api"
"go.uber.org/zap"
@@ -16,10 +21,46 @@ func NewSchemaUpdateGhostCutoverTaskExecutor(logger *zap.Logger) TaskExecutor {
// SchemaUpdateGhostCutoverTaskExecutor is the schema update (gh-ost) cutover task executor.
type SchemaUpdateGhostCutoverTaskExecutor struct {
- l *zap.Logger //nolint
+ l *zap.Logger
}
// RunOnce will run SchemaUpdateGhostCutover task once.
func (exec *SchemaUpdateGhostCutoverTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
- return true, &api.TaskRunResultPayload{Detail: "not implemented yet"}, nil
+
+ taskDAG, err := server.store.GetTaskDAGByToTaskID(ctx, task.ID)
+ if err != nil {
+ return true, nil, fmt.Errorf("failed to get a single taskDAG for schema update gh-ost cutover task, id: %v, error: %w", task.ID, err)
+ }
+ syncTaskID := taskDAG.FromTaskID
+ syncTask, err := server.store.GetTaskByID(ctx, syncTaskID)
+ if err != nil {
+ return true, nil, fmt.Errorf("failed to get schema update gh-ost sync task for cutover task, error: %w", err)
+ }
+ payload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}
+ if err := json.Unmarshal([]byte(syncTask.Payload), payload); err != nil {
+ return true, nil, fmt.Errorf("invalid database schema update gh-ost sync payload: %w", err)
+ }
+
+ statement := strings.TrimSpace(payload.Statement)
+ tableName, err := getTableNameFromStatement(statement)
+ if err != nil {
+ return true, nil, fmt.Errorf("failed to parse table name from statement, error: %w", err)
+ }
+
+ socketFilename := getSocketFilename(syncTaskID, task.Database.ID, task.Database.Name, tableName)
+ postponeFilename := getPostponeFlagFilename(syncTaskID, task.Database.ID, task.Database.Name, tableName)
+
+ if err := os.Remove(postponeFilename); err != nil {
+ return true, nil, fmt.Errorf("failed to remove postpone flag file, error: %w", err)
+ }
+
+ ticker := time.NewTicker(time.Second * 1)
+
+ for range ticker.C {
+ if _, err := os.Stat(socketFilename); err != nil {
+ break
+ }
+ }
+
+ return true, &api.TaskRunResultPayload{Detail: "cutover done"}, nil
}
diff --git a/server/task_executor_schema_update_ghost_sync.go b/server/task_executor_schema_update_ghost_sync.go
index 75d678f464..ceac76c062 100644
--- a/server/task_executor_schema_update_ghost_sync.go
+++ b/server/task_executor_schema_update_ghost_sync.go
@@ -7,6 +7,8 @@ import (
"fmt"
"strconv"
"strings"
+ "sync"
+ "sync/atomic"
"time"
"github.com/bytebase/bytebase/api"
@@ -32,15 +34,45 @@ type SchemaUpdateGhostSyncTaskExecutor struct {
l *zap.Logger
}
+// RunOnce will run SchemaUpdateGhostSync task once.
+func (exec *SchemaUpdateGhostSyncTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
+ payload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}
+ if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
+ return true, nil, fmt.Errorf("invalid database schema update gh-ost sync payload: %w", err)
+ }
+ return runGhostMigration(ctx, exec.l, server, task, db.Migrate, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)
+}
+
+func getSocketFilename(taskID int, databaseID int, databaseName string, tableName string) string {
+ return fmt.Sprintf("/tmp/gh-ost.%v.%v.%v.%v.sock", taskID, databaseID, databaseName, tableName)
+}
+
+func getPostponeFlagFilename(taskID int, databaseID int, databaseName string, tableName string) string {
+ return fmt.Sprintf("/tmp/gh-ost.%v.%v.%v.%v.postponeFlag", taskID, databaseID, databaseName, tableName)
+}
+
+func getTableNameFromStatement(statement string) (string, error) {
+ statement = strings.TrimSpace(statement)
+ parser := ghostsql.NewParserFromAlterStatement(statement)
+ if !parser.HasExplicitTable() {
+ return "", fmt.Errorf("failed to parse table name from statement, statement: %v", statement)
+ }
+ return parser.GetExplicitTable(), nil
+}
+
type ghostConfig struct {
- host string
- port string
- user string
- password string
- database string
- table string
- alterStatement string
- noop bool
+ // serverID should be unique
+ serverID uint
+ host string
+ port string
+ user string
+ password string
+ database string
+ table string
+ alterStatement string
+ socketFilename string
+ postponeFlagFilename string
+ noop bool
}
func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {
@@ -75,6 +107,7 @@ func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {
migrationContext.OriginalTableName = config.table
migrationContext.AlterStatement = config.alterStatement
migrationContext.Noop = config.noop
+ migrationContext.ReplicaServerId = config.serverID
// set defaults
migrationContext.AllowedRunningOnMaster = allowedRunningOnMaster
migrationContext.ConcurrentCountTableRows = concurrentCountTableRows
@@ -100,8 +133,8 @@ func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {
}
migrationContext.OriginalTableName = parser.GetExplicitTable()
}
- // TODO(p0ny): change file name according to design doc.
- migrationContext.ServeSocketFile = fmt.Sprintf("/tmp/gh-ost.%s.%s.sock", migrationContext.DatabaseName, migrationContext.OriginalTableName)
+ migrationContext.ServeSocketFile = config.socketFilename
+ migrationContext.PostponeCutOverFlagFile = config.postponeFlagFilename
// TODO(p0ny): set OkToDropTable to false and drop table in dropOriginalTable Task.
migrationContext.OkToDropTable = true
migrationContext.SetHeartbeatIntervalMilliseconds(heartbeatIntervalMilliseconds)
@@ -120,28 +153,33 @@ func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {
return migrationContext, nil
}
-// RunOnce will run SchemaUpdateGhostSync task once.
-func (exec *SchemaUpdateGhostSyncTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
- payload := &api.TaskDatabaseSchemaUpdateGhostSyncPayload{}
- if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
- return true, nil, fmt.Errorf("invalid database schema update gh-ost sync payload: %w", err)
- }
- return runGhostMigration(ctx, exec.l, server, task, db.Migrate, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)
-}
-
func runGhostMigration(ctx context.Context, l *zap.Logger, server *Server, task *api.Task, migrationType db.MigrationType, statement, schemaVersion string, vcsPushEvent *vcsPlugin.PushEvent) (terminated bool, result *api.TaskRunResultPayload, err error) {
mi, err := preMigration(ctx, l, server, task, migrationType, statement, schemaVersion, vcsPushEvent)
if err != nil {
return true, nil, err
}
- migrationID, schema, err := executeSync(ctx, l, task, mi, statement)
- if err != nil {
- return true, nil, err
- }
- return postMigration(ctx, l, server, task, vcsPushEvent, mi, migrationID, schema)
+
+ waitSync := &sync.WaitGroup{}
+ waitSync.Add(1)
+
+ go func(waitSync *sync.WaitGroup) {
+ migrationID, schema, err := executeSync(ctx, l, task, mi, statement, waitSync)
+ if err != nil {
+ l.Error("failed to execute schema update gh-ost sync executeSync", zap.Error(err))
+ return
+ }
+ _, _, err = postMigration(ctx, l, server, task, vcsPushEvent, mi, migrationID, schema)
+ if err != nil {
+ l.Error("failed to execute schema update gh-ost sync postMigration", zap.Error(err))
+ }
+ }(waitSync)
+
+ waitSync.Wait()
+
+ return true, &api.TaskRunResultPayload{Detail: "sync done"}, nil
}
-func executeSync(ctx context.Context, l *zap.Logger, task *api.Task, mi *db.MigrationInfo, statement string) (migrationHistoryID int64, updatedSchema string, resErr error) {
+func executeSync(ctx context.Context, l *zap.Logger, task *api.Task, mi *db.MigrationInfo, statement string, waitSync *sync.WaitGroup) (migrationHistoryID int64, updatedSchema string, resErr error) {
statement = strings.TrimSpace(statement)
driver, err := getAdminDatabaseDriver(ctx, task.Instance, task.Database.Name, l)
@@ -178,8 +216,7 @@ func executeSync(ctx context.Context, l *zap.Logger, task *api.Task, mi *db.Migr
)
}
}()
-
- if err := executeGhost(task.Instance, task.Database.Name, statement); err != nil {
+ if err = executeGhost(l, task, startedNs, statement, waitSync); err != nil {
return -1, "", err
}
@@ -191,26 +228,60 @@ func executeSync(ctx context.Context, l *zap.Logger, task *api.Task, mi *db.Migr
return insertedID, afterSchemaBuf.String(), nil
}
-func executeGhost(instance *api.Instance, databaseName string, statement string) error {
+func executeGhost(l *zap.Logger, task *api.Task, startedNs int64, statement string, waitSync *sync.WaitGroup) error {
+ instance := task.Instance
+ databaseName := task.Database.Name
+
+ tableName, err := getTableNameFromStatement(statement)
+ if err != nil {
+ return err
+ }
+
adminDataSource := api.DataSourceFromInstanceWithType(instance, api.Admin)
if adminDataSource == nil {
return common.Errorf(common.Internal, fmt.Errorf("admin data source not found for instance %d", instance.ID))
}
migrationContext, err := newMigrationContext(ghostConfig{
- host: instance.Host,
- port: instance.Port,
- user: adminDataSource.Username,
- password: adminDataSource.Password,
- database: databaseName,
- alterStatement: statement,
- noop: false,
+ host: instance.Host,
+ port: instance.Port,
+ user: adminDataSource.Username,
+ password: adminDataSource.Password,
+ database: databaseName,
+ table: tableName,
+ alterStatement: statement,
+ socketFilename: getSocketFilename(task.ID, task.Database.ID, databaseName, tableName),
+ postponeFlagFilename: getPostponeFlagFilename(task.ID, task.Database.ID, databaseName, tableName),
+ noop: false,
+ // 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: 10000000 + uint(task.ID),
})
if err != nil {
return fmt.Errorf("failed to init migrationContext for gh-ost, error: %w", err)
}
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
migrator := logic.NewMigrator(migrationContext)
+
+ go func(ctx context.Context, migrationContext *base.MigrationContext, l *zap.Logger, waitSync *sync.WaitGroup) {
+ ticker := time.NewTicker(1 * time.Second)
+ defer waitSync.Done()
+ for {
+ select {
+ case <-ticker.C:
+ // Since we are using postpone flag file to postpone cutover, it's gh-ost mechanism to set migrationContext.IsPostponingCutOver to 1 after synced and before postpone flag file is removed. We utilize this mechanism here to check if synced.
+ if atomic.LoadInt64(&migrationContext.IsPostponingCutOver) > 0 {
+ return
+ }
+ case <-ctx.Done():
+ return
+ }
+ }
+ }(ctx, migrationContext, l, waitSync)
+
if err = migrator.Migrate(); err != nil {
return fmt.Errorf("failed to run gh-ost, error: %w", err)
}
diff --git a/store/task_dag.go b/store/task_dag.go
index 3eb7de9e12..fc195b322c 100644
--- a/store/task_dag.go
+++ b/store/task_dag.go
@@ -43,7 +43,7 @@ func (s *Store) CreateTaskDAG(ctx context.Context, create *api.TaskDAGCreate) (*
return taskDAG, nil
}
-// FindTaskDAGList finds TaskDAG list by FromTaskID.
+// FindTaskDAGList finds a TaskDAG list by ToTaskID.
func (s *Store) FindTaskDAGList(ctx context.Context, find *api.TaskDAGFind) ([]*api.TaskDAG, error) {
// TODO(xz): remove this release guard once the gh-ost feature is ready to release.
if s.db.mode != common.ReleaseModeDev {
@@ -60,6 +60,18 @@ func (s *Store) FindTaskDAGList(ctx context.Context, find *api.TaskDAGFind) ([]*
return taskDAGList, nil
}
+// GetTaskDAGByToTaskID gets a single TaskDAG by ToTaskID
+func (s *Store) GetTaskDAGByToTaskID(ctx context.Context, id int) (*api.TaskDAG, error) {
+ taskDAGList, err := s.FindTaskDAGList(ctx, &api.TaskDAGFind{ToTaskID: id})
+ if err != nil {
+ return nil, err
+ }
+ if len(taskDAGList) != 1 {
+ return nil, &common.Error{Code: common.Conflict, Err: fmt.Errorf("found %d tasks with ToTaskID %v, expect 1", len(taskDAGList), id)}
+ }
+ return taskDAGList[0], nil
+}
+
func (s *Store) createTaskDAGRaw(ctx context.Context, create *api.TaskDAGCreate) (*taskDAGRaw, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
diff --git a/tests/ghost_test.go b/tests/ghost_test.go
index b333ff410b..fc0332dee6 100644
--- a/tests/ghost_test.go
+++ b/tests/ghost_test.go
@@ -164,7 +164,7 @@ func TestGhostSchemaUpdate(t *testing.T) {
CreateContext: string(createContext),
})
a.NoError(err)
- // Status will be FAILED because not implemented
+
status, err = ctl.waitIssuePipeline(issue.ID)
a.NoError(err)
a.Equal(api.TaskDone, status)