Skip to content

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

refactor: move task check executor and scheduler to a package (#3721)

Danny Xuf11e95011bfa
diff --git a/server/issue.go b/server/issue.go
index 1080c3e750..e28e6d83b3 100644
--- a/server/issue.go
+++ b/server/issue.go
@@ -393,7 +393,7 @@ func (s *Server) createIssue(ctx context.Context, issueCreate *api.IssueCreate)
}
}
- if err := s.schedulePipelineTaskCheck(ctx, issue.Pipeline); err != nil {
+ if err := s.TaskCheckScheduler.SchedulePipelineTaskCheck(ctx, issue.Pipeline); err != nil {
return nil, errors.Wrapf(err, "failed to schedule task check after creating the issue: %v", issue.Name)
}
diff --git a/server/pipeline.go b/server/pipeline.go
deleted file mode 100644
index aea0c6151a..0000000000
--- a/server/pipeline.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package server
-
-import (
- "context"
-
- "github.com/pkg/errors"
-
- "github.com/bytebase/bytebase/api"
-)
-
-func (s *Server) schedulePipelineTaskCheck(ctx context.Context, pipeline *api.Pipeline) error {
- var createList []*api.TaskCheckRunCreate
- for _, stage := range pipeline.StageList {
- for _, task := range stage.TaskList {
- create, err := s.TaskCheckScheduler.getTaskCheck(ctx, task, api.SystemBotID)
- if err != nil {
- return errors.Wrapf(err, "failed to get task check for task %d", task.ID)
- }
- createList = append(createList, create...)
- }
- }
- if _, err := s.store.BatchCreateTaskCheckRun(ctx, createList); err != nil {
- return errors.Wrap(err, "failed to batch insert TaskCheckRunCreate")
- }
- return nil
-}
diff --git a/server/task_check_executor_database_connect.go b/server/runner/taskcheck/database_connect_executor.go
similarity index 82%
rename from server/task_check_executor_database_connect.go
rename to server/runner/taskcheck/database_connect_executor.go
index 12b26d0e92..63de779190 100644
--- a/server/task_check_executor_database_connect.go
+++ b/server/runner/taskcheck/database_connect_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -10,22 +10,22 @@ import (
"github.com/bytebase/bytebase/store"
)
-// NewTaskCheckDatabaseConnectExecutor creates a task check database connect executor.
-func NewTaskCheckDatabaseConnectExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) TaskCheckExecutor {
- return &TaskCheckDatabaseConnectExecutor{
+// newTaskCheckDatabaseConnectExecutor creates a task check database connect executor.
+func newTaskCheckDatabaseConnectExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) taskCheckExecutor {
+ return &taskCheckDatabaseConnectExecutor{
store: store,
dbFactory: dbFactory,
}
}
-// TaskCheckDatabaseConnectExecutor is the task check database connect executor.
-type TaskCheckDatabaseConnectExecutor struct {
+// taskCheckDatabaseConnectExecutor is the task check database connect executor.
+type taskCheckDatabaseConnectExecutor struct {
store *store.Store
dbFactory *dbfactory.DBFactory
}
// Run will run the task check database connector executor once.
-func (e *TaskCheckDatabaseConnectExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+func (e *taskCheckDatabaseConnectExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
task, err := e.store.GetTaskByID(ctx, taskCheckRun.TaskID)
if err != nil {
return []api.TaskCheckResult{}, common.Wrap(err, common.Internal)
diff --git a/server/task_check_executor_ghost_sync.go b/server/runner/taskcheck/ghost_sync_executor.go
similarity index 82%
rename from server/task_check_executor_ghost_sync.go
rename to server/runner/taskcheck/ghost_sync_executor.go
index 39addb6855..bcaea69d4f 100644
--- a/server/task_check_executor_ghost_sync.go
+++ b/server/runner/taskcheck/ghost_sync_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -9,23 +9,24 @@ import (
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
+ "github.com/bytebase/bytebase/server/utils"
"github.com/bytebase/bytebase/store"
)
-// NewTaskCheckGhostSyncExecutor creates a task check gh-ost sync executor.
-func NewTaskCheckGhostSyncExecutor(store *store.Store) TaskCheckExecutor {
- return &TaskCheckGhostSyncExecutor{
+// newTaskCheckGhostSyncExecutor creates a task check gh-ost sync executor.
+func newTaskCheckGhostSyncExecutor(store *store.Store) taskCheckExecutor {
+ return &taskCheckGhostSyncExecutor{
store: store,
}
}
-// TaskCheckGhostSyncExecutor is the task check gh-ost sync executor.
-type TaskCheckGhostSyncExecutor struct {
+// taskCheckGhostSyncExecutor is the task check gh-ost sync executor.
+type taskCheckGhostSyncExecutor struct {
store *store.Store
}
// Run will run the task check database connector executor once.
-func (e *TaskCheckGhostSyncExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+func (e *taskCheckGhostSyncExecutor) Run(ctx context.Context, 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.
@@ -78,14 +79,14 @@ func (e *TaskCheckGhostSyncExecutor) Run(ctx context.Context, taskCheckRun *api.
return nil, common.Wrapf(err, common.Internal, "invalid database schema update gh-ost sync payload")
}
- tableName, err := getTableNameFromStatement(payload.Statement)
+ tableName, err := utils.GetTableNameFromStatement(payload.Statement)
if err != nil {
return nil, common.Wrapf(err, common.Internal, "failed to parse table name from statement, statement: %v", payload.Statement)
}
- config := getGhostConfig(task, adminDataSource, instanceUserList, tableName, payload.Statement, true, 20000000)
+ config := utils.GetGhostConfig(task, adminDataSource, instanceUserList, tableName, payload.Statement, true, 20000000)
- migrationContext, err := newMigrationContext(config)
+ migrationContext, err := utils.NewMigrationContext(config)
if err != nil {
return nil, common.Wrapf(err, common.Internal, "failed to create migration context")
}
diff --git a/server/task_check_executor_lgtm.go b/server/runner/taskcheck/lgtm_executor.go
similarity index 90%
rename from server/task_check_executor_lgtm.go
rename to server/runner/taskcheck/lgtm_executor.go
index 46f98d2165..39d6e5b540 100644
--- a/server/task_check_executor_lgtm.go
+++ b/server/runner/taskcheck/lgtm_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -11,20 +11,20 @@ import (
"github.com/bytebase/bytebase/store"
)
-// NewTaskCheckLGTMExecutor creates a task check LGTM executor.
-func NewTaskCheckLGTMExecutor(store *store.Store) TaskCheckExecutor {
- return &TaskCheckLGTMExecutor{
+// newTaskCheckLGTMExecutor creates a task check LGTM executor.
+func newTaskCheckLGTMExecutor(store *store.Store) taskCheckExecutor {
+ return &taskCheckLGTMExecutor{
store: store,
}
}
-// TaskCheckLGTMExecutor is the task check LGTM executor. It checks if "LGTM" comments are present.
-type TaskCheckLGTMExecutor struct {
+// taskCheckLGTMExecutor is the task check LGTM executor. It checks if "LGTM" comments are present.
+type taskCheckLGTMExecutor struct {
store *store.Store
}
// Run will run the task check LGTM executor once.
-func (e *TaskCheckLGTMExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+func (e *taskCheckLGTMExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
task, err := e.store.GetTaskByID(ctx, taskCheckRun.TaskID)
if err != nil {
return nil, common.Wrap(err, common.Internal)
diff --git a/server/task_check_executor_migration_schema.go b/server/runner/taskcheck/migration_schema_executor.go
similarity index 82%
rename from server/task_check_executor_migration_schema.go
rename to server/runner/taskcheck/migration_schema_executor.go
index fecf1715cc..8777beffd6 100644
--- a/server/task_check_executor_migration_schema.go
+++ b/server/runner/taskcheck/migration_schema_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -10,22 +10,22 @@ import (
"github.com/bytebase/bytebase/store"
)
-// NewTaskCheckMigrationSchemaExecutor creates a task check migration schema executor.
-func NewTaskCheckMigrationSchemaExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) TaskCheckExecutor {
- return &TaskCheckMigrationSchemaExecutor{
+// newTaskCheckMigrationSchemaExecutor creates a task check migration schema executor.
+func newTaskCheckMigrationSchemaExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) taskCheckExecutor {
+ return &taskCheckMigrationSchemaExecutor{
store: store,
dbFactory: dbFactory,
}
}
-// TaskCheckMigrationSchemaExecutor is the task check migration schema executor.
-type TaskCheckMigrationSchemaExecutor struct {
+// taskCheckMigrationSchemaExecutor is the task check migration schema executor.
+type taskCheckMigrationSchemaExecutor struct {
store *store.Store
dbFactory *dbfactory.DBFactory
}
// Run will run the task check migration schema executor once.
-func (e *TaskCheckMigrationSchemaExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+func (e *taskCheckMigrationSchemaExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
task, err := e.store.GetTaskByID(ctx, taskCheckRun.TaskID)
if err != nil {
return []api.TaskCheckResult{}, common.Wrap(err, common.Internal)
diff --git a/server/task_check_executor_pitr_mysql.go b/server/runner/taskcheck/pitr_mysql_executor.go
similarity index 87%
rename from server/task_check_executor_pitr_mysql.go
rename to server/runner/taskcheck/pitr_mysql_executor.go
index 01e4812ffd..5117026d4c 100644
--- a/server/task_check_executor_pitr_mysql.go
+++ b/server/runner/taskcheck/pitr_mysql_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -13,22 +13,22 @@ import (
"github.com/bytebase/bytebase/store"
)
-// NewTaskCheckPITRMySQLExecutor creates a task check migration schema executor.
-func NewTaskCheckPITRMySQLExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) TaskCheckExecutor {
- return &TaskCheckPITRMySQLExecutor{
+// newTaskCheckPITRMySQLExecutor creates a task check migration schema executor.
+func newTaskCheckPITRMySQLExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) taskCheckExecutor {
+ return &taskCheckPITRMySQLExecutor{
store: store,
dbFactory: dbFactory,
}
}
-// TaskCheckPITRMySQLExecutor is the task check migration schema executor.
-type TaskCheckPITRMySQLExecutor struct {
+// taskCheckPITRMySQLExecutor is the task check migration schema executor.
+type taskCheckPITRMySQLExecutor struct {
store *store.Store
dbFactory *dbfactory.DBFactory
}
// Run will run the task check migration schema executor once.
-func (e *TaskCheckPITRMySQLExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+func (e *taskCheckPITRMySQLExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
task, err := e.store.GetTaskByID(ctx, taskCheckRun.TaskID)
if err != nil {
return nil, errors.Wrapf(err, "failed to get task by ID %d", taskCheckRun.TaskID)
diff --git a/server/task_check_executor_statement_advisor_composite.go b/server/runner/taskcheck/statement_advisor_composite_executor.go
similarity index 89%
rename from server/task_check_executor_statement_advisor_composite.go
rename to server/runner/taskcheck/statement_advisor_composite_executor.go
index 25467225fc..bb8722a1be 100644
--- a/server/task_check_executor_statement_advisor_composite.go
+++ b/server/runner/taskcheck/statement_advisor_composite_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -18,22 +18,22 @@ import (
// 2. Each SQL review rule type maps an advisor.Type.
// 3. Each [db.Type][AdvisorType] maps an advisor.
-// NewTaskCheckStatementAdvisorCompositeExecutor creates a task check statement advisor composite executor.
-func NewTaskCheckStatementAdvisorCompositeExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) TaskCheckExecutor {
- return &TaskCheckStatementAdvisorCompositeExecutor{
+// newTaskCheckStatementAdvisorCompositeExecutor creates a task check statement advisor composite executor.
+func newTaskCheckStatementAdvisorCompositeExecutor(store *store.Store, dbFactory *dbfactory.DBFactory) taskCheckExecutor {
+ return &taskCheckStatementAdvisorCompositeExecutor{
store: store,
dbFactory: dbFactory,
}
}
-// TaskCheckStatementAdvisorCompositeExecutor is the task check statement advisor composite executor with has sub-advisor.
-type TaskCheckStatementAdvisorCompositeExecutor struct {
+// taskCheckStatementAdvisorCompositeExecutor is the task check statement advisor composite executor with has sub-advisor.
+type taskCheckStatementAdvisorCompositeExecutor struct {
store *store.Store
dbFactory *dbfactory.DBFactory
}
// Run will run the task check statement advisor composite executor once, and run its sub-advisor one-by-one.
-func (e *TaskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+func (e *taskCheckStatementAdvisorCompositeExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
if taskCheckRun.Type != api.TaskCheckDatabaseStatementAdvise {
return nil, common.Errorf(common.Invalid, "invalid check statement advisor composite type: %v", taskCheckRun.Type)
}
diff --git a/server/task_check_executor_statement_advisor_simple.go b/server/runner/taskcheck/statement_advisor_simple_executor.go
similarity index 84%
rename from server/task_check_executor_statement_advisor_simple.go
rename to server/runner/taskcheck/statement_advisor_simple_executor.go
index 9e64410f7d..21d620bdef 100644
--- a/server/task_check_executor_statement_advisor_simple.go
+++ b/server/runner/taskcheck/statement_advisor_simple_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -11,17 +11,17 @@ import (
"github.com/bytebase/bytebase/plugin/db"
)
-// NewTaskCheckStatementAdvisorSimpleExecutor creates a task check statement simple advisor executor.
-func NewTaskCheckStatementAdvisorSimpleExecutor() TaskCheckExecutor {
- return &TaskCheckStatementAdvisorSimpleExecutor{}
+// newTaskCheckStatementAdvisorSimpleExecutor creates a task check statement simple advisor executor.
+func newTaskCheckStatementAdvisorSimpleExecutor() taskCheckExecutor {
+ return &taskCheckStatementAdvisorSimpleExecutor{}
}
-// TaskCheckStatementAdvisorSimpleExecutor is the task check statement advisor simple executor.
-type TaskCheckStatementAdvisorSimpleExecutor struct {
+// taskCheckStatementAdvisorSimpleExecutor is the task check statement advisor simple executor.
+type taskCheckStatementAdvisorSimpleExecutor struct {
}
// Run will run the task check statement advisor executor once.
-func (*TaskCheckStatementAdvisorSimpleExecutor) Run(_ context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+func (*taskCheckStatementAdvisorSimpleExecutor) Run(_ context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
payload := &api.TaskCheckDatabaseStatementAdvisePayload{}
if err := json.Unmarshal([]byte(taskCheckRun.Payload), payload); err != nil {
return nil, common.Wrapf(err, common.Invalid, "invalid check statement advise payload")
diff --git a/server/task_check_executor_statement_type.go b/server/runner/taskcheck/statement_type_executor.go
similarity index 94%
rename from server/task_check_executor_statement_type.go
rename to server/runner/taskcheck/statement_type_executor.go
index 0ae1a5e36b..4db97036dd 100644
--- a/server/task_check_executor_statement_type.go
+++ b/server/runner/taskcheck/statement_type_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -17,20 +17,20 @@ import (
"github.com/bytebase/bytebase/store"
)
-// NewTaskCheckStatementTypeExecutor creates a task check DML executor.
-func NewTaskCheckStatementTypeExecutor(store *store.Store) TaskCheckExecutor {
- return &TaskCheckStatementTypeExecutor{
+// newTaskCheckStatementTypeExecutor creates a task check DML executor.
+func newTaskCheckStatementTypeExecutor(store *store.Store) taskCheckExecutor {
+ return &taskCheckStatementTypeExecutor{
store: store,
}
}
-// TaskCheckStatementTypeExecutor is the task check DML executor.
-type TaskCheckStatementTypeExecutor struct {
+// taskCheckStatementTypeExecutor is the task check DML executor.
+type taskCheckStatementTypeExecutor struct {
store *store.Store
}
// Run will run the task check database connector executor once.
-func (e *TaskCheckStatementTypeExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
+func (e *taskCheckStatementTypeExecutor) Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {
task, err := e.store.GetTaskByID(ctx, taskCheckRun.TaskID)
if err != nil {
return []api.TaskCheckResult{}, common.Wrap(err, common.Internal)
diff --git a/server/task_check_executor_statement_type_test.go b/server/runner/taskcheck/statement_type_executor_test.go
similarity index 99%
rename from server/task_check_executor_statement_type_test.go
rename to server/runner/taskcheck/statement_type_executor_test.go
index 1f9419d251..07cfcac516 100644
--- a/server/task_check_executor_statement_type_test.go
+++ b/server/runner/taskcheck/statement_type_executor_test.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"testing"
diff --git a/server/task_check_executor.go b/server/runner/taskcheck/task_check_executor.go
similarity index 68%
rename from server/task_check_executor.go
rename to server/runner/taskcheck/task_check_executor.go
index be44bb0ba2..31bf8c523e 100644
--- a/server/task_check_executor.go
+++ b/server/runner/taskcheck/task_check_executor.go
@@ -1,4 +1,4 @@
-package server
+package taskcheck
import (
"context"
@@ -6,8 +6,8 @@ import (
"github.com/bytebase/bytebase/api"
)
-// TaskCheckExecutor is the task check executor.
-type TaskCheckExecutor interface {
+// taskCheckExecutor is the task check executor.
+type taskCheckExecutor interface {
// Run will be called periodically by the task check scheduler
Run(ctx context.Context, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error)
}
diff --git a/server/task_check_scheduler.go b/server/runner/taskcheck/task_check_scheduler.go
similarity index 75%
rename from server/task_check_scheduler.go
rename to server/runner/taskcheck/task_check_scheduler.go
index 6ca5cec12b..57d1222cc5 100644
--- a/server/task_check_scheduler.go
+++ b/server/runner/taskcheck/task_check_scheduler.go
@@ -1,4 +1,5 @@
-package server
+// Package taskcheck is a runner for task checks.
+package taskcheck
import (
"context"
@@ -14,33 +15,63 @@ import (
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
enterpriseAPI "github.com/bytebase/bytebase/enterprise/api"
+ "github.com/bytebase/bytebase/server/component/dbfactory"
"github.com/bytebase/bytebase/store"
)
+const (
+ taskCheckSchedulerInterval = time.Duration(1) * time.Second
+)
+
// NewTaskCheckScheduler creates a task check scheduler.
-func NewTaskCheckScheduler(server *Server, store *store.Store, licenseService enterpriseAPI.LicenseService) *TaskCheckScheduler {
- return &TaskCheckScheduler{
- server: server,
+func NewTaskCheckScheduler(store *store.Store, dbFactory *dbfactory.DBFactory, licenseService enterpriseAPI.LicenseService) *Scheduler {
+ taskCheckScheduler := &Scheduler{
store: store,
licenseService: licenseService,
- executors: make(map[api.TaskCheckType]TaskCheckExecutor),
+ executors: make(map[api.TaskCheckType]taskCheckExecutor),
}
+
+ statementSimpleExecutor := newTaskCheckStatementAdvisorSimpleExecutor()
+ taskCheckScheduler.Register(api.TaskCheckDatabaseStatementFakeAdvise, statementSimpleExecutor)
+ taskCheckScheduler.Register(api.TaskCheckDatabaseStatementSyntax, statementSimpleExecutor)
+
+ statementCompositeExecutor := newTaskCheckStatementAdvisorCompositeExecutor(store, dbFactory)
+ taskCheckScheduler.Register(api.TaskCheckDatabaseStatementAdvise, statementCompositeExecutor)
+
+ statementTypeExecutor := newTaskCheckStatementTypeExecutor(store)
+ taskCheckScheduler.Register(api.TaskCheckDatabaseStatementType, statementTypeExecutor)
+
+ databaseConnectExecutor := newTaskCheckDatabaseConnectExecutor(store, dbFactory)
+ taskCheckScheduler.Register(api.TaskCheckDatabaseConnect, databaseConnectExecutor)
+
+ migrationSchemaExecutor := newTaskCheckMigrationSchemaExecutor(store, dbFactory)
+ taskCheckScheduler.Register(api.TaskCheckInstanceMigrationSchema, migrationSchemaExecutor)
+
+ ghostSyncExecutor := newTaskCheckGhostSyncExecutor(store)
+ taskCheckScheduler.Register(api.TaskCheckGhostSync, ghostSyncExecutor)
+
+ checkLGTMExecutor := newTaskCheckLGTMExecutor(store)
+ taskCheckScheduler.Register(api.TaskCheckIssueLGTM, checkLGTMExecutor)
+
+ pitrMySQLExecutor := newTaskCheckPITRMySQLExecutor(store, dbFactory)
+ taskCheckScheduler.Register(api.TaskCheckPITRMySQL, pitrMySQLExecutor)
+
+ return taskCheckScheduler
}
-// TaskCheckScheduler is the task check scheduler.
-type TaskCheckScheduler struct {
- server *Server
+// Scheduler is the task check scheduler.
+type Scheduler struct {
store *store.Store
licenseService enterpriseAPI.LicenseService
- executors map[api.TaskCheckType]TaskCheckExecutor
+ executors map[api.TaskCheckType]taskCheckExecutor
}
// Run will run the task check scheduler once.
-func (s *TaskCheckScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
- ticker := time.NewTicker(taskSchedulerInterval)
+func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
+ ticker := time.NewTicker(taskCheckSchedulerInterval)
defer ticker.Stop()
defer wg.Done()
- log.Debug(fmt.Sprintf("Task check scheduler started and will run every %v", taskSchedulerInterval))
+ log.Debug(fmt.Sprintf("Task check scheduler started and will run every %v", taskCheckSchedulerInterval))
runningTaskChecks := make(map[int]bool)
mu := sync.RWMutex{}
for {
@@ -173,7 +204,7 @@ func (s *TaskCheckScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
}
// Register will register the task check executor.
-func (s *TaskCheckScheduler) Register(taskType api.TaskCheckType, executor TaskCheckExecutor) {
+func (s *Scheduler) Register(taskType api.TaskCheckType, executor taskCheckExecutor) {
if executor == nil {
panic("scheduler: Register executor is nil for task type: " + taskType)
}
@@ -183,7 +214,7 @@ func (s *TaskCheckScheduler) Register(taskType api.TaskCheckType, executor TaskC
s.executors[taskType] = executor
}
-func (s *TaskCheckScheduler) getTaskCheck(ctx context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
+func (s *Scheduler) getTaskCheck(ctx context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
var createList []*api.TaskCheckRunCreate
create, err := s.getLGTMTaskCheck(ctx, task, creatorID)
@@ -248,7 +279,7 @@ func (s *TaskCheckScheduler) getTaskCheck(ctx context.Context, task *api.Task, c
}
// ScheduleCheck schedules variouse task checks depending on the task type.
-func (s *TaskCheckScheduler) ScheduleCheck(ctx context.Context, task *api.Task, creatorID int) (*api.Task, error) {
+func (s *Scheduler) ScheduleCheck(ctx context.Context, task *api.Task, creatorID int) (*api.Task, error) {
createList, err := s.getTaskCheck(ctx, task, creatorID)
if err != nil {
return nil, errors.Wrap(err, "failed to getTaskCheck")
@@ -261,7 +292,7 @@ func (s *TaskCheckScheduler) ScheduleCheck(ctx context.Context, task *api.Task,
return task, err
}
-func (*TaskCheckScheduler) getStatement(task *api.Task) (string, error) {
+func (*Scheduler) getStatement(task *api.Task) (string, error) {
switch task.Type {
case api.TaskDatabaseSchemaUpdate:
taskPayload := &api.TaskDatabaseSchemaUpdatePayload{}
@@ -292,7 +323,7 @@ func (*TaskCheckScheduler) getStatement(task *api.Task) (string, error) {
}
}
-func (*TaskCheckScheduler) getStmtTypeTaskCheck(_ context.Context, task *api.Task, creatorID int, database *api.Database, statement string) ([]*api.TaskCheckRunCreate, error) {
+func (*Scheduler) getStmtTypeTaskCheck(_ context.Context, task *api.Task, creatorID int, database *api.Database, statement string) ([]*api.TaskCheckRunCreate, error) {
if !api.IsStatementTypeCheckSupported(database.Instance.Engine) {
return nil, nil
}
@@ -315,7 +346,7 @@ func (*TaskCheckScheduler) getStmtTypeTaskCheck(_ context.Context, task *api.Tas
}, nil
}
-func (s *TaskCheckScheduler) getSQLReviewTaskCheck(ctx context.Context, task *api.Task, creatorID int, database *api.Database, statement string) ([]*api.TaskCheckRunCreate, error) {
+func (s *Scheduler) getSQLReviewTaskCheck(ctx context.Context, task *api.Task, creatorID int, database *api.Database, statement string) ([]*api.TaskCheckRunCreate, error) {
if !api.IsSQLReviewSupported(database.Instance.Engine) {
return nil, nil
}
@@ -366,7 +397,7 @@ func getSyntaxCheckTaskCheck(_ context.Context, task *api.Task, creatorID int, d
}, nil
}
-func (*TaskCheckScheduler) getGeneralTaskCheck(_ context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
+func (*Scheduler) getGeneralTaskCheck(_ context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
return []*api.TaskCheckRunCreate{
{
CreatorID: creatorID,
@@ -381,7 +412,7 @@ func (*TaskCheckScheduler) getGeneralTaskCheck(_ context.Context, task *api.Task
}, nil
}
-func (*TaskCheckScheduler) getGhostTaskCheck(_ context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
+func (*Scheduler) getGhostTaskCheck(_ context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
if task.Type != api.TaskDatabaseSchemaUpdateGhostSync {
return nil, nil
}
@@ -394,7 +425,7 @@ func (*TaskCheckScheduler) getGhostTaskCheck(_ context.Context, task *api.Task,
}, nil
}
-func (*TaskCheckScheduler) getPITRTaskCheck(_ context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
+func (*Scheduler) getPITRTaskCheck(_ context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
if task.Type != api.TaskDatabaseRestorePITRRestore {
return nil, nil
}
@@ -407,7 +438,7 @@ func (*TaskCheckScheduler) getPITRTaskCheck(_ context.Context, task *api.Task, c
}, nil
}
-func (s *TaskCheckScheduler) getLGTMTaskCheck(ctx context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
+func (s *Scheduler) getLGTMTaskCheck(ctx context.Context, task *api.Task, creatorID int) ([]*api.TaskCheckRunCreate, error) {
if !s.licenseService.IsFeatureEnabled(api.FeatureLGTM) {
return nil, nil
}
@@ -442,3 +473,21 @@ func (s *TaskCheckScheduler) getLGTMTaskCheck(ctx context.Context, task *api.Tas
},
}, nil
}
+
+// SchedulePipelineTaskCheck schedules the task checks for a pipeline.
+func (s *Scheduler) SchedulePipelineTaskCheck(ctx context.Context, pipeline *api.Pipeline) error {
+ var createList []*api.TaskCheckRunCreate
+ for _, stage := range pipeline.StageList {
+ for _, task := range stage.TaskList {
+ create, err := s.getTaskCheck(ctx, task, api.SystemBotID)
+ if err != nil {
+ return errors.Wrapf(err, "failed to get task check for task %d", task.ID)
+ }
+ createList = append(createList, create...)
+ }
+ }
+ if _, err := s.store.BatchCreateTaskCheckRun(ctx, createList); err != nil {
+ return errors.Wrap(err, "failed to batch insert TaskCheckRunCreate")
+ }
+ return nil
+}
diff --git a/server/server.go b/server/server.go
index 396f73e1e2..fc39dcd133 100644
--- a/server/server.go
+++ b/server/server.go
@@ -41,6 +41,7 @@ import (
"github.com/bytebase/bytebase/server/component/dbfactory"
"github.com/bytebase/bytebase/server/runner/anomaly"
"github.com/bytebase/bytebase/server/runner/schemasync"
+ "github.com/bytebase/bytebase/server/runner/taskcheck"
"github.com/bytebase/bytebase/store"
// Register clickhouse driver.
@@ -88,7 +89,7 @@ const (
type Server struct {
// Asynchronous runners.
TaskScheduler *TaskScheduler
- TaskCheckScheduler *TaskCheckScheduler
+ TaskCheckScheduler *taskcheck.Scheduler
MetricReporter *MetricReporter
SchemaSyncer *schemasync.Syncer
BackupRunner *BackupRunner
@@ -303,35 +304,7 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {
taskScheduler.Register(api.TaskDatabaseRestorePITRCutover, NewPITRCutoverTaskExecutor(storeInstance, s.dbFactory, s.SchemaSyncer, s.BackupRunner, s.ActivityManager, profile))
s.TaskScheduler = taskScheduler
- // Task check scheduler
- taskCheckScheduler := NewTaskCheckScheduler(s, storeInstance, s.licenseService)
-
- statementSimpleExecutor := NewTaskCheckStatementAdvisorSimpleExecutor()
- taskCheckScheduler.Register(api.TaskCheckDatabaseStatementFakeAdvise, statementSimpleExecutor)
- taskCheckScheduler.Register(api.TaskCheckDatabaseStatementSyntax, statementSimpleExecutor)
-
- statementCompositeExecutor := NewTaskCheckStatementAdvisorCompositeExecutor(storeInstance, s.dbFactory)
- taskCheckScheduler.Register(api.TaskCheckDatabaseStatementAdvise, statementCompositeExecutor)
-
- statementTypeExecutor := NewTaskCheckStatementTypeExecutor(storeInstance)
- taskCheckScheduler.Register(api.TaskCheckDatabaseStatementType, statementTypeExecutor)
-
- databaseConnectExecutor := NewTaskCheckDatabaseConnectExecutor(storeInstance, s.dbFactory)
- taskCheckScheduler.Register(api.TaskCheckDatabaseConnect, databaseConnectExecutor)
-
- migrationSchemaExecutor := NewTaskCheckMigrationSchemaExecutor(storeInstance, s.dbFactory)
- taskCheckScheduler.Register(api.TaskCheckInstanceMigrationSchema, migrationSchemaExecutor)
-
- ghostSyncExecutor := NewTaskCheckGhostSyncExecutor(storeInstance)
- taskCheckScheduler.Register(api.TaskCheckGhostSync, ghostSyncExecutor)
-
- checkLGTMExecutor := NewTaskCheckLGTMExecutor(storeInstance)
- taskCheckScheduler.Register(api.TaskCheckIssueLGTM, checkLGTMExecutor)
-
- pitrMySQLExecutor := NewTaskCheckPITRMySQLExecutor(storeInstance, s.dbFactory)
- taskCheckScheduler.Register(api.TaskCheckPITRMySQL, pitrMySQLExecutor)
-
- s.TaskCheckScheduler = taskCheckScheduler
+ s.TaskCheckScheduler = taskcheck.NewTaskCheckScheduler(storeInstance, s.dbFactory, s.licenseService)
// Anomaly scanner
s.AnomalyScanner = anomaly.NewScanner(storeInstance, s.dbFactory, s.licenseService)
diff --git a/server/task_executor_schema_update_ghost_cutover.go b/server/task_executor_schema_update_ghost_cutover.go
index 8155684d83..74688b94e7 100644
--- a/server/task_executor_schema_update_ghost_cutover.go
+++ b/server/task_executor_schema_update_ghost_cutover.go
@@ -22,6 +22,7 @@ import (
"github.com/bytebase/bytebase/server/component/activity"
"github.com/bytebase/bytebase/server/component/config"
"github.com/bytebase/bytebase/server/component/dbfactory"
+ "github.com/bytebase/bytebase/server/utils"
"github.com/bytebase/bytebase/store"
)
@@ -64,12 +65,12 @@ func (exec *SchemaUpdateGhostCutoverTaskExecutor) RunOnce(ctx context.Context, t
return true, nil, errors.Wrap(err, "invalid database schema update gh-ost sync payload")
}
- tableName, err := getTableNameFromStatement(payload.Statement)
+ tableName, err := utils.GetTableNameFromStatement(payload.Statement)
if err != nil {
return true, nil, errors.Wrap(err, "failed to parse table name from statement")
}
- postponeFilename := getPostponeFlagFilename(syncTaskID, task.Database.ID, task.Database.Name, tableName)
+ postponeFilename := utils.GetPostponeFlagFilename(syncTaskID, task.Database.ID, task.Database.Name, tableName)
value, ok := exec.taskScheduler.sharedTaskState.Load(syncTaskID)
if !ok {
diff --git a/server/task_executor_schema_update_ghost_sync.go b/server/task_executor_schema_update_ghost_sync.go
index 7685d7063c..931080835d 100644
--- a/server/task_executor_schema_update_ghost_sync.go
+++ b/server/task_executor_schema_update_ghost_sync.go
@@ -3,21 +3,19 @@ package server
import (
"context"
"encoding/json"
- "fmt"
- "strconv"
"strings"
"sync/atomic"
"time"
"github.com/github/gh-ost/go/base"
"github.com/github/gh-ost/go/logic"
- ghostsql "github.com/github/gh-ost/go/sql"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
"github.com/bytebase/bytebase/common/log"
+ "github.com/bytebase/bytebase/server/utils"
"github.com/bytebase/bytebase/store"
)
@@ -44,160 +42,11 @@ func (exec *SchemaUpdateGhostSyncTaskExecutor) RunOnce(ctx context.Context, task
return exec.runGhostMigration(ctx, exec.store, exec.taskScheduler, task, payload.Statement)
}
-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) {
- // Trim the statement for the parser.
- // This in effect removes all leading and trailing spaces, substitute multiple spaces with one.
- statement = strings.Join(strings.Fields(statement), " ")
- parser := ghostsql.NewParserFromAlterStatement(statement)
- if !parser.HasExplicitTable() {
- return "", errors.Errorf("failed to parse table name from statement, statement: %v", statement)
- }
- return parser.GetExplicitTable(), nil
-}
-
type sharedGhostState struct {
migrationContext *base.MigrationContext
errCh <-chan error
}
-type ghostConfig struct {
- // 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
-
- // vendor related
- isAWS bool
-}
-
-func newMigrationContext(config ghostConfig) (*base.MigrationContext, error) {
- const (
- allowedRunningOnMaster = true
- concurrentCountTableRows = true
- timestampAllTable = true
- hooksStatusIntervalSec = 60
- heartbeatIntervalMilliseconds = 100
- niceRatio = 0
- chunkSize = 1000
- dmlBatchSize = 10
- maxLagMillisecondsThrottleThreshold = 1500
- defaultNumRetries = 60
- cutoverLockTimeoutSeconds = 3
- exponentialBackoffMaxInterval = 64
- throttleHTTPIntervalMillis = 100
- throttleHTTPTimeoutMillis = 1000
- )
- statement := strings.Join(strings.Fields(config.alterStatement), " ")
- migrationContext := base.NewMigrationContext()
- migrationContext.InspectorConnectionConfig.Key.Hostname = config.host
- port := 3306
- if config.port != "" {
- configPort, err := strconv.Atoi(config.port)
- if err != nil {
- return nil, errors.Wrap(err, "failed to convert port from string to int")
- }
- port = configPort
- }
- migrationContext.InspectorConnectionConfig.Key.Port = port
- migrationContext.CliUser = config.user
- migrationContext.CliPassword = config.password
- migrationContext.DatabaseName = config.database
- migrationContext.OriginalTableName = config.table
- migrationContext.AlterStatement = statement
- migrationContext.Noop = config.noop
- migrationContext.ReplicaServerId = config.serverID
- if config.isAWS {
- migrationContext.AssumeRBR = true
- }
- // set defaults
- migrationContext.AllowedRunningOnMaster = allowedRunningOnMaster
- migrationContext.ConcurrentCountTableRows = concurrentCountTableRows
- migrationContext.HooksStatusIntervalSec = hooksStatusIntervalSec
- migrationContext.CutOverType = base.CutOverAtomic
- migrationContext.ThrottleHTTPIntervalMillis = throttleHTTPIntervalMillis
- migrationContext.ThrottleHTTPTimeoutMillis = throttleHTTPTimeoutMillis
-
- if migrationContext.AlterStatement == "" {
- return nil, errors.Errorf("alterStatement must be provided and must not be empty")
- }
- parser := ghostsql.NewParserFromAlterStatement(migrationContext.AlterStatement)
- migrationContext.AlterStatementOptions = parser.GetAlterStatementOptions()
-
- if migrationContext.DatabaseName == "" {
- if !parser.HasExplicitSchema() {
- return nil, errors.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")
- }
- migrationContext.DatabaseName = parser.GetExplicitSchema()
- }
- if migrationContext.OriginalTableName == "" {
- if !parser.HasExplicitTable() {
- return nil, errors.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")
- }
- migrationContext.OriginalTableName = parser.GetExplicitTable()
- }
- migrationContext.ServeSocketFile = config.socketFilename
- migrationContext.PostponeCutOverFlagFile = config.postponeFlagFilename
- migrationContext.TimestampAllTable = timestampAllTable
- migrationContext.SetHeartbeatIntervalMilliseconds(heartbeatIntervalMilliseconds)
- migrationContext.SetNiceRatio(niceRatio)
- migrationContext.SetChunkSize(chunkSize)
- migrationContext.SetDMLBatchSize(dmlBatchSize)
- migrationContext.SetMaxLagMillisecondsThrottleThreshold(maxLagMillisecondsThrottleThreshold)
- migrationContext.SetDefaultNumRetries(defaultNumRetries)
- migrationContext.ApplyCredentials()
- if err := migrationContext.SetCutOverLockTimeoutSeconds(cutoverLockTimeoutSeconds); err != nil {
- return nil, err
- }
- if err := migrationContext.SetExponentialBackoffMaxInterval(exponentialBackoffMaxInterval); err != nil {
- return nil, err
- }
- return migrationContext, nil
-}
-
-func getGhostConfig(task *api.Task, dataSource *api.DataSource, userList []*api.InstanceUser, tableName string, statement string, noop bool, serverIDOffset uint) ghostConfig {
- var isAWS bool
- for _, user := range userList {
- if user.Name == "'rdsadmin'@'localhost'" && strings.Contains(user.Grant, "SUPER") {
- isAWS = true
- break
- }
- }
- return ghostConfig{
- host: task.Instance.Host,
- port: task.Instance.Port,
- user: dataSource.Username,
- password: dataSource.Password,
- database: task.Database.Name,
- table: tableName,
- alterStatement: statement,
- socketFilename: getSocketFilename(task.ID, task.Database.ID, task.Database.Name, tableName),
- postponeFlagFilename: getPostponeFlagFilename(task.ID, task.Database.ID, task.Database.Name, tableName),
- noop: noop,
- // 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: serverIDOffset + uint(task.ID),
- // https://github.com/github/gh-ost/blob/master/doc/rds.md
- isAWS: isAWS,
- }
-}
-
func (*SchemaUpdateGhostSyncTaskExecutor) runGhostMigration(ctx context.Context, store *store.Store, taskScheduler *TaskScheduler, task *api.Task, statement string) (terminated bool, result *api.TaskRunResultPayload, err error) {
syncDone := make(chan struct{})
// set buffer size to 1 to unblock the sender because there is no listner if the task is canceled.
@@ -206,7 +55,7 @@ func (*SchemaUpdateGhostSyncTaskExecutor) runGhostMigration(ctx context.Context,
statement = strings.TrimSpace(statement)
- tableName, err := getTableNameFromStatement(statement)
+ tableName, err := utils.GetTableNameFromStatement(statement)
if err != nil {
return true, nil, err
}
@@ -221,9 +70,9 @@ func (*SchemaUpdateGhostSyncTaskExecutor) runGhostMigration(ctx context.Context,
return true, nil, common.Errorf(common.Internal, "failed to find instance user by instanceID %d", task.InstanceID)
}
- config := getGhostConfig(task, adminDataSource, instanceUserList, tableName, statement, false, 10000000)
+ config := utils.GetGhostConfig(task, adminDataSource, instanceUserList, tableName, statement, false, 10000000)
- migrationContext, err := newMigrationContext(config)
+ migrationContext, err := utils.NewMigrationContext(config)
if err != nil {
return true, nil, errors.Wrap(err, "failed to init migrationContext for gh-ost")
}
diff --git a/server/utils/utils.go b/server/utils/utils.go
index 8e30710c29..c9535f7515 100644
--- a/server/utils/utils.go
+++ b/server/utils/utils.go
@@ -3,9 +3,15 @@ package utils
import (
"context"
+ "fmt"
+ "strconv"
+ "strings"
+ "github.com/github/gh-ost/go/base"
+ ghostsql "github.com/github/gh-ost/go/sql"
"github.com/pkg/errors"
+ "github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/plugin/db"
)
@@ -26,3 +32,157 @@ func GetLatestSchemaVersion(ctx context.Context, driver db.Driver, databaseName
}
return schemaVersion, nil
}
+
+// GetTableNameFromStatement gets the table name from statement for gh-ost.
+func GetTableNameFromStatement(statement string) (string, error) {
+ // Trim the statement for the parser.
+ // This in effect removes all leading and trailing spaces, substitute multiple spaces with one.
+ statement = strings.Join(strings.Fields(statement), " ")
+ parser := ghostsql.NewParserFromAlterStatement(statement)
+ if !parser.HasExplicitTable() {
+ return "", errors.Errorf("failed to parse table name from statement, statement: %v", statement)
+ }
+ return parser.GetExplicitTable(), nil
+}
+
+// GhostConfig is the configuration for gh-ost migration.
+type GhostConfig struct {
+ // 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
+
+ // vendor related
+ isAWS bool
+}
+
+// GetGhostConfig returns a gh-ost configuration for migration.
+func GetGhostConfig(task *api.Task, dataSource *api.DataSource, userList []*api.InstanceUser, tableName string, statement string, noop bool, serverIDOffset uint) GhostConfig {
+ var isAWS bool
+ for _, user := range userList {
+ if user.Name == "'rdsadmin'@'localhost'" && strings.Contains(user.Grant, "SUPER") {
+ isAWS = true
+ break
+ }
+ }
+ return GhostConfig{
+ host: task.Instance.Host,
+ port: task.Instance.Port,
+ user: dataSource.Username,
+ password: dataSource.Password,
+ database: task.Database.Name,
+ table: tableName,
+ alterStatement: statement,
+ socketFilename: getSocketFilename(task.ID, task.Database.ID, task.Database.Name, tableName),
+ postponeFlagFilename: GetPostponeFlagFilename(task.ID, task.Database.ID, task.Database.Name, tableName),
+ noop: noop,
+ // 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: serverIDOffset + uint(task.ID),
+ // https://github.com/github/gh-ost/blob/master/doc/rds.md
+ isAWS: isAWS,
+ }
+}
+
+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)
+}
+
+// GetPostponeFlagFilename gets the postpone flag filename for gh-ost.
+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)
+}
+
+// NewMigrationContext is the context for gh-ost migration.
+func NewMigrationContext(config GhostConfig) (*base.MigrationContext, error) {
+ const (
+ allowedRunningOnMaster = true
+ concurrentCountTableRows = true
+ timestampAllTable = true
+ hooksStatusIntervalSec = 60
+ heartbeatIntervalMilliseconds = 100
+ niceRatio = 0
+ chunkSize = 1000
+ dmlBatchSize = 10
+ maxLagMillisecondsThrottleThreshold = 1500
+ defaultNumRetries = 60
+ cutoverLockTimeoutSeconds = 3
+ exponentialBackoffMaxInterval = 64
+ throttleHTTPIntervalMillis = 100
+ throttleHTTPTimeoutMillis = 1000
+ )
+ statement := strings.Join(strings.Fields(config.alterStatement), " ")
+ migrationContext := base.NewMigrationContext()
+ migrationContext.InspectorConnectionConfig.Key.Hostname = config.host
+ port := 3306
+ if config.port != "" {
+ configPort, err := strconv.Atoi(config.port)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to convert port from string to int")
+ }
+ port = configPort
+ }
+ migrationContext.InspectorConnectionConfig.Key.Port = port
+ migrationContext.CliUser = config.user
+ migrationContext.CliPassword = config.password
+ migrationContext.DatabaseName = config.database
+ migrationContext.OriginalTableName = config.table
+ migrationContext.AlterStatement = statement
+ migrationContext.Noop = config.noop
+ migrationContext.ReplicaServerId = config.serverID
+ if config.isAWS {
+ migrationContext.AssumeRBR = true
+ }
+ // set defaults
+ migrationContext.AllowedRunningOnMaster = allowedRunningOnMaster
+ migrationContext.ConcurrentCountTableRows = concurrentCountTableRows
+ migrationContext.HooksStatusIntervalSec = hooksStatusIntervalSec
+ migrationContext.CutOverType = base.CutOverAtomic
+ migrationContext.ThrottleHTTPIntervalMillis = throttleHTTPIntervalMillis
+ migrationContext.ThrottleHTTPTimeoutMillis = throttleHTTPTimeoutMillis
+
+ if migrationContext.AlterStatement == "" {
+ return nil, errors.Errorf("alterStatement must be provided and must not be empty")
+ }
+ parser := ghostsql.NewParserFromAlterStatement(migrationContext.AlterStatement)
+ migrationContext.AlterStatementOptions = parser.GetAlterStatementOptions()
+
+ if migrationContext.DatabaseName == "" {
+ if !parser.HasExplicitSchema() {
+ return nil, errors.Errorf("database must be provided and database name must not be empty, or alterStatement must specify database name")
+ }
+ migrationContext.DatabaseName = parser.GetExplicitSchema()
+ }
+ if migrationContext.OriginalTableName == "" {
+ if !parser.HasExplicitTable() {
+ return nil, errors.Errorf("table must be provided and table name must not be empty, or alterStatement must specify table name")
+ }
+ migrationContext.OriginalTableName = parser.GetExplicitTable()
+ }
+ migrationContext.ServeSocketFile = config.socketFilename
+ migrationContext.PostponeCutOverFlagFile = config.postponeFlagFilename
+ migrationContext.TimestampAllTable = timestampAllTable
+ migrationContext.SetHeartbeatIntervalMilliseconds(heartbeatIntervalMilliseconds)
+ migrationContext.SetNiceRatio(niceRatio)
+ migrationContext.SetChunkSize(chunkSize)
+ migrationContext.SetDMLBatchSize(dmlBatchSize)
+ migrationContext.SetMaxLagMillisecondsThrottleThreshold(maxLagMillisecondsThrottleThreshold)
+ migrationContext.SetDefaultNumRetries(defaultNumRetries)
+ migrationContext.ApplyCredentials()
+ if err := migrationContext.SetCutOverLockTimeoutSeconds(cutoverLockTimeoutSeconds); err != nil {
+ return nil, err
+ }
+ if err := migrationContext.SetExponentialBackoffMaxInterval(exponentialBackoffMaxInterval); err != nil {
+ return nil, err
+ }
+ return migrationContext, nil
+}