Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
Revert "feat: improve task scheduling by avoiding to load all open pipelines (#3812)" (#3935)
Tianzhou (天舟)6d1bc99230f1
diff --git a/server/runner/taskrun/scheduler.go b/server/runner/taskrun/scheduler.goindex f02eb6839e..28e01e37eb 100644--- a/server/runner/taskrun/scheduler.go+++ b/server/runner/taskrun/scheduler.go@@ -6,6 +6,7 @@ import ("encoding/json""fmt""net/http"+ "sort""strconv""sync""time"@@ -111,19 +112,59 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {return}- taskList, err := s.schedulePendingTasksToRunning(ctx)- if err != nil {- log.Error("Failed to schedule pending tasks to running",+ if err := s.scheduleActiveStageToRunning(ctx); err != nil {+ log.Error("Failed to schedule tasks in the active stage",zap.Error(err),)return}+ // Inspect all running tasks+ taskStatusList := []api.TaskStatus{api.TaskRunning}+ taskFind := &api.TaskFind{+ StatusList: &taskStatusList,+ }+ // This fetches quite a bit info and may cause performance issue if we have many ongoing tasks+ // We may optimize this in the future since only some relationship info is needed by the executor+ taskList, err := s.store.FindTask(ctx, taskFind, false)+ if err != nil {+ log.Error("Failed to retrieve running tasks", zap.Error(err))+ return+ }++ // For each database, we will only execute the earliest running task (minimal task ID) and hold up the rest of the running tasks.+ // Sort the taskList by ID first.+ // databaseRunningTasks is the mapping from database ID to the earliest task of this database.+ sort.Slice(taskList, func(i, j int) bool {+ return taskList[i].ID < taskList[j].ID+ })+ databaseRunningTasks := make(map[int]int)+ for _, task := range taskList {+ if task.DatabaseID == nil {+ continue+ }+ if _, ok := databaseRunningTasks[*task.DatabaseID]; ok {+ continue+ }+ databaseRunningTasks[*task.DatabaseID] = task.ID+ }+for _, task := range taskList {+ // Skip task belongs to archived instances+ if i := task.Instance; i == nil || i.RowStatus == api.Archived {+ continue+ }// Skip the task that is already being executed.if _, ok := s.stateCfg.RunningTasks.Load(task.ID); ok {continue}+ // Skip the task that is not the earliest task of the database.+ // earliestTaskID is the one that should be executed.+ if task.DatabaseID != nil {+ if earliestTaskID, ok := databaseRunningTasks[*task.DatabaseID]; ok && earliestTaskID != task.ID {+ continue+ }+ }executor, ok := s.executorMap[task.Type]if !ok {@@ -135,6 +176,14 @@ func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {continue}+ s.stateCfg.Lock()+ if s.stateCfg.InstanceOutstandingConnections[task.InstanceID] >= state.InstanceMaximumConnectionNumber {+ s.stateCfg.Unlock()+ continue+ }+ s.stateCfg.InstanceOutstandingConnections[task.InstanceID]+++ s.stateCfg.Unlock()+s.stateCfg.RunningTasks.Store(task.ID, true)go func(ctx context.Context, task *api.Task, executor Executor) {defer func() {@@ -781,6 +830,30 @@ func (s *Scheduler) canSchedule(ctx context.Context, task *api.Task) (bool, erroreturn s.passAllCheck(ctx, task, api.TaskCheckStatusWarn)}+// scheduleIfNeeded schedules the task if+// 1. its required check does not contain error in the latest run.+// 2. it has no blocking tasks.+// 3. it has passed the earliest allowed time.+func (s *Scheduler) scheduleIfNeeded(ctx context.Context, task *api.Task) error {+ schedule, err := s.canSchedule(ctx, task)+ if err != nil {+ return err+ }+ if !schedule {+ return nil+ }++ if _, err := s.PatchTaskStatus(ctx, task, &api.TaskStatusPatch{+ IDList: []int{task.ID},+ UpdaterID: api.SystemBotID,+ Status: api.TaskRunning,+ }); err != nil {+ return err+ }++ return nil+}+func (s *Scheduler) isTaskBlocked(ctx context.Context, task *api.Task) (bool, error) {for _, blockingTaskIDString := range task.BlockedBy {blockingTaskID, err := strconv.Atoi(blockingTaskIDString)@@ -835,53 +908,32 @@ func (s *Scheduler) scheduleAutoApprovedTasks(ctx context.Context) error {return nil}-// schedulePendingTasks tries to schedule the pending tasks to running.-func (s *Scheduler) schedulePendingTasksToRunning(ctx context.Context) ([]*api.Task, error) {- taskStatusList := []api.TaskStatus{api.TaskPending}- taskFind := &api.TaskFind{- StatusList: &taskStatusList,+// scheduleActiveStageToRunning tries to schedule the tasks in the active stage.+func (s *Scheduler) scheduleActiveStageToRunning(ctx context.Context) error {+ pipelineStatus := api.PipelineOpen+ pipelineFind := &api.PipelineFind{+ Status: &pipelineStatus,}- taskList, err := s.store.FindTask(ctx, taskFind, false)+ pipelineList, err := s.store.FindPipeline(ctx, pipelineFind, false)if err != nil {- return nil, err+ return errors.Wrap(err, "failed to retrieve open pipelines")}- var runningTasks []*api.Task- for _, task := range taskList {- // Skip task belongs to archived instances- if i := task.Instance; i == nil || i.RowStatus == api.Archived {+ for _, pipeline := range pipelineList {+ stage := utils.GetActiveStage(pipeline)+ if stage == nil {continue}- schedule, err := s.canSchedule(ctx, task)- if err != nil {- log.Error("failed to check task schedulable", zap.Int("taskID", task.ID), zap.Error(err))- continue- }- if !schedule {- continue- }-- // Increment the maximum outstanding tasks per instance.- s.stateCfg.Lock()- if s.stateCfg.InstanceOutstandingConnections[task.InstanceID] >= state.InstanceMaximumConnectionNumber {- s.stateCfg.Unlock()- continue- }- s.stateCfg.InstanceOutstandingConnections[task.InstanceID]++- s.stateCfg.Unlock()+ for _, task := range stage.TaskList {+ if task.Status != api.TaskPending {+ continue+ }- updatedTask, err := s.PatchTaskStatus(ctx, task, &api.TaskStatusPatch{- IDList: []int{task.ID},- UpdaterID: api.SystemBotID,- Status: api.TaskRunning,- })- if err != nil {- log.Error("failed to patch task to running", zap.Int("taskID", task.ID), zap.Error(err))- continue+ if err := s.scheduleIfNeeded(ctx, task); err != nil {+ return errors.Wrap(err, "failed to schedule task")+ }}-- runningTasks = append(runningTasks, updatedTask)}- return runningTasks, nil+ return nil}// PatchTaskStatus patches a single task.diff --git a/store/task.go b/store/task.goindex f05a79ca94..8fbd128097 100644--- a/store/task.go+++ b/store/task.go@@ -422,7 +422,10 @@ func (s *Store) patchTaskRaw(ctx context.Context, patch *api.TaskPatch) (*taskRa// patchTaskRawStatus updates existing task statuses and the corresponding task run statuses atomically.// Returns ENOTFOUND if tasks do not exist.func (s *Store) patchTaskRawStatus(ctx context.Context, patch *api.TaskStatusPatch) ([]*taskRaw, error) {- tx, err := s.db.BeginTx(ctx, nil)+ // Without using serializable isolation transaction, we will get race condition and have multiple task runs inserted because+ // we do a read and write on task, without guaranteed consistency on task runs.+ // Once we have multiple task runs, the task will get to unrecoverable state because find task run will fail with two active runs.+ tx, err := s.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})if err != nil {return nil, FormatError(err)}