Skip to content

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

refactor: task scheduler (#1956)

p0ny74ed6e69614f
diff --git a/server/server.go b/server/server.go
index af5545507f..5119f4e281 100644
--- a/server/server.go
+++ b/server/server.go
@@ -200,35 +200,25 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {
// Task scheduler
taskScheduler := NewTaskScheduler(s)
- defaultExecutor := NewDefaultTaskExecutor()
- taskScheduler.Register(api.TaskGeneral, defaultExecutor)
+ taskScheduler.Register(api.TaskGeneral, NewDefaultTaskExecutor)
- createDBExecutor := NewDatabaseCreateTaskExecutor()
- taskScheduler.Register(api.TaskDatabaseCreate, createDBExecutor)
+ taskScheduler.Register(api.TaskDatabaseCreate, NewDatabaseCreateTaskExecutor)
- schemaUpdateExecutor := NewSchemaUpdateTaskExecutor()
- taskScheduler.Register(api.TaskDatabaseSchemaUpdate, schemaUpdateExecutor)
+ taskScheduler.Register(api.TaskDatabaseSchemaUpdate, NewSchemaUpdateTaskExecutor)
- dataUpdateExecutor := NewDataUpdateTaskExecutor()
- taskScheduler.Register(api.TaskDatabaseDataUpdate, dataUpdateExecutor)
+ taskScheduler.Register(api.TaskDatabaseDataUpdate, NewDataUpdateTaskExecutor)
- backupDBExecutor := NewDatabaseBackupTaskExecutor()
- taskScheduler.Register(api.TaskDatabaseBackup, backupDBExecutor)
+ taskScheduler.Register(api.TaskDatabaseBackup, NewDatabaseBackupTaskExecutor)
- restoreDBExecutor := NewDatabaseRestoreTaskExecutor()
- taskScheduler.Register(api.TaskDatabaseRestore, restoreDBExecutor)
+ taskScheduler.Register(api.TaskDatabaseRestore, NewDatabaseRestoreTaskExecutor)
- schemaUpdateGhostSyncExecutor := NewSchemaUpdateGhostSyncTaskExecutor()
- taskScheduler.Register(api.TaskDatabaseSchemaUpdateGhostSync, schemaUpdateGhostSyncExecutor)
+ taskScheduler.Register(api.TaskDatabaseSchemaUpdateGhostSync, NewSchemaUpdateGhostSyncTaskExecutor)
- schemaUpdateGhostCutoverExecutor := NewSchemaUpdateGhostCutoverTaskExecutor()
- taskScheduler.Register(api.TaskDatabaseSchemaUpdateGhostCutover, schemaUpdateGhostCutoverExecutor)
+ taskScheduler.Register(api.TaskDatabaseSchemaUpdateGhostCutover, NewSchemaUpdateGhostCutoverTaskExecutor)
- pitrRestoreExecutor := NewPITRRestoreTaskExecutor(s.mysqlutil)
- taskScheduler.Register(api.TaskDatabasePITRRestore, pitrRestoreExecutor)
+ taskScheduler.Register(api.TaskDatabasePITRRestore, func() TaskExecutor { return NewPITRRestoreTaskExecutor(s.mysqlutil) })
- pitrCutoverExecutor := NewPITRCutoverTaskExecutor(s.mysqlutil)
- taskScheduler.Register(api.TaskDatabasePITRCutover, pitrCutoverExecutor)
+ taskScheduler.Register(api.TaskDatabasePITRCutover, func() TaskExecutor { return NewPITRCutoverTaskExecutor(s.mysqlutil) })
s.TaskScheduler = taskScheduler
diff --git a/server/task_executor.go b/server/task_executor.go
index 6044e333bc..745b293719 100644
--- a/server/task_executor.go
+++ b/server/task_executor.go
@@ -27,6 +27,8 @@ type TaskExecutor interface {
// usually indicates a transient error and will make scheduler retry later.
// 2. If err is non-nil, then the detail field will be ignored since info is provided in the err.
RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error)
+ // IsCompleted tells the scheduler if the task execution has completed
+ IsCompleted() bool
}
// RunTaskExecutorOnce wraps a TaskExecutor.RunOnce call with panic recovery
diff --git a/server/task_executor_database_backup.go b/server/task_executor_database_backup.go
index f550085830..1f93dd6d62 100644
--- a/server/task_executor_database_backup.go
+++ b/server/task_executor_database_backup.go
@@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "sync/atomic"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common/log"
@@ -19,10 +20,17 @@ func NewDatabaseBackupTaskExecutor() TaskExecutor {
// DatabaseBackupTaskExecutor is the task executor for database backup.
type DatabaseBackupTaskExecutor struct {
+ completed int32
+}
+
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *DatabaseBackupTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
}
// RunOnce will run database backup once.
func (exec *DatabaseBackupTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
+ defer atomic.StoreInt32(&exec.completed, 1)
payload := &api.TaskDatabaseBackupPayload{}
if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
return true, nil, fmt.Errorf("invalid database backup payload: %w", err)
diff --git a/server/task_executor_database_create.go b/server/task_executor_database_create.go
index 6fd57d84ab..22d6c365d2 100644
--- a/server/task_executor_database_create.go
+++ b/server/task_executor_database_create.go
@@ -6,6 +6,7 @@ import (
"fmt"
"strconv"
"strings"
+ "sync/atomic"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common/log"
@@ -20,10 +21,17 @@ func NewDatabaseCreateTaskExecutor() TaskExecutor {
// DatabaseCreateTaskExecutor is the database create task executor.
type DatabaseCreateTaskExecutor struct {
+ completed int32
+}
+
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *DatabaseCreateTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
}
// RunOnce will run the database create task executor once.
func (exec *DatabaseCreateTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
+ defer atomic.StoreInt32(&exec.completed, 1)
payload := &api.TaskDatabaseCreatePayload{}
if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
return true, nil, fmt.Errorf("invalid create database payload: %w", err)
diff --git a/server/task_executor_database_restore.go b/server/task_executor_database_restore.go
index f5ce004812..a767464f8d 100644
--- a/server/task_executor_database_restore.go
+++ b/server/task_executor_database_restore.go
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"strconv"
+ "sync/atomic"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
@@ -24,10 +25,17 @@ func NewDatabaseRestoreTaskExecutor() TaskExecutor {
// DatabaseRestoreTaskExecutor is the task executor for database restore.
type DatabaseRestoreTaskExecutor struct {
+ completed int32
+}
+
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *DatabaseRestoreTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
}
// RunOnce will run database restore once.
func (exec *DatabaseRestoreTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
+ defer atomic.StoreInt32(&exec.completed, 1)
payload := &api.TaskDatabaseRestorePayload{}
if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
return true, nil, fmt.Errorf("invalid database backup payload: %w", err)
diff --git a/server/task_executor_default.go b/server/task_executor_default.go
index 97775d10c7..daabebaa55 100644
--- a/server/task_executor_default.go
+++ b/server/task_executor_default.go
@@ -3,6 +3,7 @@ package server
import (
"context"
"fmt"
+ "sync/atomic"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common/log"
@@ -16,11 +17,18 @@ func NewDefaultTaskExecutor() TaskExecutor {
// DefaultTaskExecutor is the default task executor.
type DefaultTaskExecutor struct {
+ completed int32
}
// RunOnce will run the default task executor once.
func (exec *DefaultTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
log.Info("Run default task type", zap.String("task", task.Name))
+ defer atomic.StoreInt32(&exec.completed, 1)
return true, &api.TaskRunResultPayload{Detail: fmt.Sprintf("No-op task %s", task.Name)}, nil
}
+
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *DefaultTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
+}
diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.go
index 8cb5402128..f447ba9ab8 100644
--- a/server/task_executor_pitr_cutover.go
+++ b/server/task_executor_pitr_cutover.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"strconv"
+ "sync/atomic"
"github.com/bytebase/bytebase/api"
"github.com/bytebase/bytebase/common"
@@ -24,12 +25,14 @@ func NewPITRCutoverTaskExecutor(instance mysqlutil.Instance) TaskExecutor {
// PITRCutoverTaskExecutor is the PITR cutover task executor.
type PITRCutoverTaskExecutor struct {
+ completed int32
mysqlutil mysqlutil.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) {
log.Info("Run PITR cutover task", zap.String("task", task.Name))
+ defer atomic.StoreInt32(&exec.completed, 1)
issue, err := getIssueByPipelineID(ctx, server.store, task.PipelineID)
if err != nil {
@@ -73,6 +76,11 @@ func (exec *PITRCutoverTaskExecutor) RunOnce(ctx context.Context, server *Server
return terminated, result, nil
}
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *PITRCutoverTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
+}
+
// pitrCutover performs the PITR cutover algorithm:
// 1. Swap the current and PITR database.
// 2. Create a backup with type PITR. The backup is scheduled asynchronously.
diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.go
index 62e45b67e2..8948a1c5f7 100644
--- a/server/task_executor_pitr_restore.go
+++ b/server/task_executor_pitr_restore.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"os"
+ "sync/atomic"
"time"
"github.com/bytebase/bytebase/api"
@@ -27,12 +28,14 @@ func NewPITRRestoreTaskExecutor(instance mysqlutil.Instance) TaskExecutor {
// PITRRestoreTaskExecutor is the PITR restore task executor.
type PITRRestoreTaskExecutor struct {
+ completed int32
mysqlutil mysqlutil.Instance
}
// RunOnce will run the PITR restore task executor once.
func (exec *PITRRestoreTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
log.Info("Run PITR restore task", zap.String("task", task.Name))
+ defer atomic.StoreInt32(&exec.completed, 1)
payload := api.TaskDatabasePITRRestorePayload{}
if err := json.Unmarshal([]byte(task.Payload), &payload); err != nil {
@@ -57,6 +60,11 @@ func (exec *PITRRestoreTaskExecutor) RunOnce(ctx context.Context, server *Server
}, nil
}
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *PITRRestoreTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
+}
+
func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, task *api.Task, store *store.Store, driver db.Driver, dataDir string, targetTs int64, mode common.ReleaseMode) error {
instance := task.Instance
database := task.Database
diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.go
index c8505e467a..09f48d7dbe 100644
--- a/server/task_executor_schema_update.go
+++ b/server/task_executor_schema_update.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "sync/atomic"
"github.com/bytebase/bytebase/api"
)
@@ -15,10 +16,12 @@ func NewSchemaUpdateTaskExecutor() TaskExecutor {
// SchemaUpdateTaskExecutor is the schema update (DDL) task executor.
type SchemaUpdateTaskExecutor struct {
+ completed int32
}
// RunOnce will run the schema update (DDL) task executor once.
func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Server, task *api.Task) (terminated bool, result *api.TaskRunResultPayload, err error) {
+ defer atomic.StoreInt32(&exec.completed, 1)
payload := &api.TaskDatabaseSchemaUpdatePayload{}
if err := json.Unmarshal([]byte(task.Payload), payload); err != nil {
return true, nil, fmt.Errorf("invalid database schema update payload: %w", err)
@@ -26,3 +29,8 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, server *Serve
return runMigration(ctx, server, task, payload.MigrationType, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)
}
+
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *SchemaUpdateTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
+}
diff --git a/server/task_executor_schema_update_ghost_cutover.go b/server/task_executor_schema_update_ghost_cutover.go
index 65a807cc4e..5333070374 100644
--- a/server/task_executor_schema_update_ghost_cutover.go
+++ b/server/task_executor_schema_update_ghost_cutover.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"os"
+ "sync/atomic"
"time"
"github.com/bytebase/bytebase/api"
@@ -17,10 +18,12 @@ func NewSchemaUpdateGhostCutoverTaskExecutor() TaskExecutor {
// SchemaUpdateGhostCutoverTaskExecutor is the schema update (gh-ost) cutover task executor.
type SchemaUpdateGhostCutoverTaskExecutor struct {
+ completed int32
}
// 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) {
+ defer atomic.StoreInt32(&exec.completed, 1)
taskDAG, err := server.store.GetTaskDAGByToTaskID(ctx, task.ID)
if err != nil {
@@ -59,3 +62,8 @@ func (exec *SchemaUpdateGhostCutoverTaskExecutor) RunOnce(ctx context.Context, s
return true, &api.TaskRunResultPayload{Detail: "cutover done"}, nil
}
+
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *SchemaUpdateGhostCutoverTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
+}
diff --git a/server/task_executor_schema_update_ghost_sync.go b/server/task_executor_schema_update_ghost_sync.go
index 82bbcea055..e3d75bca53 100644
--- a/server/task_executor_schema_update_ghost_sync.go
+++ b/server/task_executor_schema_update_ghost_sync.go
@@ -29,10 +29,12 @@ func NewSchemaUpdateGhostSyncTaskExecutor() TaskExecutor {
// SchemaUpdateGhostSyncTaskExecutor is the schema update (gh-ost) sync task executor.
type SchemaUpdateGhostSyncTaskExecutor struct {
+ completed int32
}
// 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) {
+ defer atomic.StoreInt32(&exec.completed, 1)
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)
@@ -40,6 +42,11 @@ func (exec *SchemaUpdateGhostSyncTaskExecutor) RunOnce(ctx context.Context, serv
return runGhostMigration(ctx, server, task, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)
}
+// IsCompleted tells the scheduler if the task execution has completed
+func (exec *SchemaUpdateGhostSyncTaskExecutor) IsCompleted() bool {
+ return atomic.LoadInt32(&exec.completed) == 1
+}
+
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)
}
diff --git a/server/task_scheduler.go b/server/task_scheduler.go
index 2b25035d3f..4c06b18bae 100644
--- a/server/task_scheduler.go
+++ b/server/task_scheduler.go
@@ -22,16 +22,17 @@ const (
// NewTaskScheduler creates a new task scheduler.
func NewTaskScheduler(server *Server) *TaskScheduler {
return &TaskScheduler{
- executors: make(map[api.TaskType]TaskExecutor),
- server: server,
+ executorGetters: make(map[api.TaskType]func() TaskExecutor),
+ runningExecutors: make(map[int]TaskExecutor),
+ server: server,
}
}
// TaskScheduler is the task scheduler.
type TaskScheduler struct {
- executors map[api.TaskType]TaskExecutor
-
- server *Server
+ executorGetters map[api.TaskType]func() TaskExecutor
+ runningExecutors map[int]TaskExecutor
+ server *Server
}
// Run will run the task scheduler.
@@ -40,13 +41,6 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
defer ticker.Stop()
defer wg.Done()
log.Debug(fmt.Sprintf("Task scheduler started and will run every %v", taskSchedulerInterval))
- tasks := struct {
- running map[int]bool // task id set
- mu sync.RWMutex
- }{
- running: make(map[int]bool),
- mu: sync.RWMutex{},
- }
for {
select {
case <-ticker.C:
@@ -63,6 +57,13 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
ctx := context.Background()
+ // Collect completed tasks
+ for i, executor := range s.runningExecutors {
+ if executor.IsCompleted() {
+ delete(s.runningExecutors, i)
+ }
+ }
+
// Inspect all open pipelines and schedule the next PENDING task if applicable
pipelineStatus := api.PipelineOpen
pipelineFind := &api.PipelineFind{
@@ -109,7 +110,7 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
continue
}
- executor, ok := s.executors[task.Type]
+ executorGetter, ok := s.executorGetters[task.Type]
if !ok {
log.Error("Skip running task with unknown type",
zap.Int("id", task.ID),
@@ -119,20 +120,12 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
continue
}
- tasks.mu.Lock()
- if _, ok := tasks.running[task.ID]; ok {
- tasks.mu.Unlock()
+ if _, ok := s.runningExecutors[task.ID]; ok {
continue
}
- tasks.running[task.ID] = true
- tasks.mu.Unlock()
+ s.runningExecutors[task.ID] = executorGetter()
- go func(task *api.Task) {
- defer func() {
- tasks.mu.Lock()
- delete(tasks.running, task.ID)
- tasks.mu.Unlock()
- }()
+ go func(task *api.Task, executor TaskExecutor) {
done, result, err := RunTaskExecutorOnce(ctx, executor, s.server, task)
if done {
if err == nil {
@@ -206,7 +199,7 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
zap.Error(err),
)
}
- }(task)
+ }(task, s.runningExecutors[task.ID])
}
}()
case <-ctx.Done(): // if cancel() execute
@@ -215,15 +208,15 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
}
}
-// Register will register a task executor.
-func (s *TaskScheduler) Register(taskType api.TaskType, executor TaskExecutor) {
- if executor == nil {
+// Register will register a task executor factory.
+func (s *TaskScheduler) Register(taskType api.TaskType, executorGetter func() TaskExecutor) {
+ if executorGetter == nil {
panic("scheduler: Register executor is nil for task type: " + taskType)
}
- if _, dup := s.executors[taskType]; dup {
+ if _, dup := s.executorGetters[taskType]; dup {
panic("scheduler: Register called twice for task type: " + taskType)
}
- s.executors[taskType] = executor
+ s.executorGetters[taskType] = executorGetter
}
// canScheduleTask checks if the task can be scheduled, i.e. change the task status from PENDING to RUNNING