Skip to content

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

refactor: delete code part 1 (#7975)

Danny Xu1d2c1af72a4f
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.go
index 44322814d9..4d5d1abf7c 100644
--- a/backend/api/v1/issue_service.go
+++ b/backend/api/v1/issue_service.go
@@ -1236,7 +1236,7 @@ func (s *IssueService) onIssueApproved(ctx context.Context, issue *store.IssueMe
return errors.Wrap(err, "failed to check if the approval is approved")
}
if approved {
- if err := s.taskScheduler.ChangeIssueStatus(ctx, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
+ if err := utils.ChangeIssueStatus(ctx, s.store, s.activityManager, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
return errors.Wrap(err, "failed to update issue status")
}
}
diff --git a/backend/runner/approval/runner.go b/backend/runner/approval/runner.go
index 5f2660c27e..de4fa47d7c 100644
--- a/backend/runner/approval/runner.go
+++ b/backend/runner/approval/runner.go
@@ -196,7 +196,7 @@ func (r *Runner) findApprovalTemplateForIssue(ctx context.Context, issue *store.
}, &activity.Metadata{}); err != nil {
log.Warn("Failed to create project activity", zap.Error(err))
}
- if err := r.taskScheduler.ChangeIssueStatus(ctx, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
+ if err := utils.ChangeIssueStatus(ctx, r.store, r.activityManager, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
return false, errors.Wrap(err, "failed to update issue status")
}
}
diff --git a/backend/runner/relay/runner.go b/backend/runner/relay/runner.go
index be290c9d24..f7334eb151 100644
--- a/backend/runner/relay/runner.go
+++ b/backend/runner/relay/runner.go
@@ -434,7 +434,7 @@ func (r *Runner) approveExternalApprovalNode(ctx context.Context, issueUID int)
return errors.Wrap(err, "failed to check if the approval is approved")
}
if approved {
- if err := r.taskScheduler.ChangeIssueStatus(ctx, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
+ if err := utils.ChangeIssueStatus(ctx, r.store, r.activityManager, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
return errors.Wrap(err, "failed to update issue status")
}
}
diff --git a/backend/runner/taskrun/scheduler.go b/backend/runner/taskrun/scheduler.go
index 8bdc20cd07..48c38dfe28 100644
--- a/backend/runner/taskrun/scheduler.go
+++ b/backend/runner/taskrun/scheduler.go
@@ -6,8 +6,6 @@ import (
"encoding/json"
"fmt"
"net/http"
- "sort"
- "sync"
"time"
"github.com/labstack/echo/v4"
@@ -101,219 +99,6 @@ func (s *Scheduler) Register(taskType api.TaskType, executorGetter Executor) {
s.executorMap[taskType] = executorGetter
}
-// Run will run the task scheduler.
-func (s *Scheduler) Run(ctx context.Context, wg *sync.WaitGroup) {
- ticker := time.NewTicker(taskSchedulerInterval)
- defer ticker.Stop()
- defer wg.Done()
- log.Debug(fmt.Sprintf("Task scheduler started and will run every %v", taskSchedulerInterval))
- for {
- select {
- case <-ticker.C:
- func() {
- defer func() {
- if r := recover(); r != nil {
- err, ok := r.(error)
- if !ok {
- err = errors.Errorf("%v", r)
- }
- log.Error("Task scheduler PANIC RECOVER", zap.Error(err), zap.Stack("panic-stack"))
- }
- }()
-
- ctx := context.Background()
-
- if err := s.scheduleAutoApprovedTasks(ctx); err != nil {
- log.Error("Failed to schedule auto approved tasks", zap.Error(err))
- return
- }
-
- if err := s.schedulePendingTasks(ctx); err != nil {
- log.Error("Failed to schedule tasks in the active stage",
- zap.Error(err),
- )
- return
- }
-
- // Inspect all running tasks
- // 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
- taskStatusList := []api.TaskStatus{api.TaskRunning}
- tasks, err := s.store.ListTasks(ctx, &api.TaskFind{
- StatusList: &taskStatusList,
- })
- 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(tasks, func(i, j int) bool {
- return tasks[i].ID < tasks[j].ID
- })
- databaseRunningTasks := make(map[int]int)
- for _, task := range tasks {
- if task.DatabaseID == nil {
- continue
- }
- if _, ok := databaseRunningTasks[*task.DatabaseID]; ok {
- continue
- }
- databaseRunningTasks[*task.DatabaseID] = task.ID
- }
-
- for _, task := range tasks {
- // Skip task belongs to archived instances
- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})
- if err != nil {
- continue
- }
- if instance.Deleted {
- 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 {
- log.Error("Skip running task with unknown type",
- zap.Int("id", task.ID),
- zap.String("name", task.Name),
- zap.String("type", string(task.Type)),
- )
- 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 *store.TaskMessage, executor Executor) {
- defer func() {
- s.stateCfg.RunningTasks.Delete(task.ID)
- s.stateCfg.RunningTasksCancel.Delete(task.ID)
- s.stateCfg.TaskProgress.Delete(task.ID)
- s.stateCfg.Lock()
- s.stateCfg.InstanceOutstandingConnections[task.InstanceID]--
- s.stateCfg.Unlock()
- }()
-
- driverCtx, cancel := context.WithCancel(ctx)
- s.stateCfg.RunningTasksCancel.Store(task.ID, cancel)
-
- done, result, err := RunExecutorOnce(ctx, driverCtx, executor, task)
-
- select {
- case <-driverCtx.Done():
- // task cancelled
- log.Debug("Task canceled",
- zap.Int("id", task.ID),
- zap.String("name", task.Name),
- zap.String("type", string(task.Type)),
- )
- return
- default:
- }
-
- if !done && err != nil {
- log.Debug("Encountered transient error running task, will retry",
- zap.Int("id", task.ID),
- zap.String("name", task.Name),
- zap.String("type", string(task.Type)),
- zap.Error(err),
- )
- return
- }
- if done && err != nil {
- log.Warn("Failed to run task",
- zap.Int("id", task.ID),
- zap.String("name", task.Name),
- zap.String("type", string(task.Type)),
- zap.Error(err),
- )
- bytes, marshalErr := json.Marshal(api.TaskRunResultPayload{
- Detail: err.Error(),
- })
- if marshalErr != nil {
- log.Error("Failed to marshal task run result",
- zap.Int("task_id", task.ID),
- zap.String("type", string(task.Type)),
- zap.Error(marshalErr),
- )
- return
- }
- code := common.ErrorCode(err)
- result := string(bytes)
- taskStatusPatch := &api.TaskStatusPatch{
- ID: task.ID,
- UpdaterID: api.SystemBotID,
- Status: api.TaskFailed,
- Code: &code,
- Result: &result,
- }
- if err := s.PatchTaskStatus(ctx, task, taskStatusPatch); err != nil {
- log.Error("Failed to mark task as FAILED",
- zap.Int("id", task.ID),
- zap.String("name", task.Name),
- zap.Error(err),
- )
- }
- return
- }
- if done && err == nil {
- bytes, err := json.Marshal(*result)
- if err != nil {
- log.Error("Failed to marshal task run result",
- zap.Int("task_id", task.ID),
- zap.String("type", string(task.Type)),
- zap.Error(err),
- )
- return
- }
- code := common.Ok
- result := string(bytes)
- taskStatusPatch := &api.TaskStatusPatch{
- ID: task.ID,
- UpdaterID: api.SystemBotID,
- Status: api.TaskDone,
- Code: &code,
- Result: &result,
- }
- if err := s.PatchTaskStatus(ctx, task, taskStatusPatch); err != nil {
- log.Error("Failed to mark task as DONE",
- zap.Int("id", task.ID),
- zap.String("name", task.Name),
- zap.Error(err),
- )
- return
- }
- return
- }
- }(ctx, task, executor)
- }
- }()
- case <-ctx.Done(): // if cancel() execute
- return
- }
- }
-}
-
// PatchTask patches the statement, earliest allowed time and rollbackEnabled for a task.
func (s *Scheduler) PatchTask(ctx context.Context, task *store.TaskMessage, taskPatch *api.TaskPatch, issue *store.IssueMessage) error {
if taskPatch.SheetID != nil {
@@ -602,68 +387,6 @@ func (s *Scheduler) getGroupValueForTask(ctx context.Context, issue *store.Issue
return nil, nil
}
-// ClearRunningTasks changes all RUNNING tasks and taskRuns to CANCELED.
-// When there are running tasks and Bytebase server is shutdown, these task executors are stopped, but the tasks' status are still RUNNING.
-// When Bytebase is restarted, the task scheduler will re-schedule those RUNNING tasks, which should be CANCELED instead.
-// So we change their status to CANCELED before starting the scheduler.
-// And corresponding taskRuns are also changed to CANCELED.
-func (s *Scheduler) ClearRunningTasks(ctx context.Context) error {
- taskFind := &api.TaskFind{StatusList: &[]api.TaskStatus{api.TaskRunning}}
- runningTasks, err := s.store.ListTasks(ctx, taskFind)
- if err != nil {
- return errors.Wrap(err, "failed to get running tasks")
- }
- if len(runningTasks) > 0 {
- var taskIDs []int
- for _, task := range runningTasks {
- taskIDs = append(taskIDs, task.ID)
- }
- if err := s.store.BatchPatchTaskStatus(ctx, taskIDs, api.TaskCanceled, api.SystemBotID); err != nil {
- return errors.Wrapf(err, "failed to change task %v's status to %s", taskIDs, api.TaskCanceled)
- }
- }
-
- runningTaskRuns, err := s.store.ListTaskRun(ctx, &store.TaskRunFind{StatusList: &[]api.TaskRunStatus{api.TaskRunRunning}})
- if err != nil {
- return errors.Wrap(err, "failed to get running task runs")
- }
- if len(runningTaskRuns) > 0 {
- var taskRunIDs []int
- for _, taskRun := range runningTaskRuns {
- taskRunIDs = append(taskRunIDs, taskRun.ID)
- }
- if err := s.store.BatchPatchTaskRunStatus(ctx, taskRunIDs, api.TaskRunCanceled, api.SystemBotID); err != nil {
- return errors.Wrapf(err, "failed to change task run %v's status to %s", taskRunIDs, api.TaskRunCanceled)
- }
- }
-
- for _, task := range runningTasks {
- // If it's a backup task, we also change the corresponding backup's status to FAILED, because the task is canceled just now.
- if task.Type != api.TaskDatabaseBackup {
- continue
- }
- // TODO(d): batch patching backup status.
- var payload api.TaskDatabaseBackupPayload
- if err := json.Unmarshal([]byte(task.Payload), &payload); err != nil {
- return errors.Wrapf(err, "failed to parse the payload of backup task %d", task.ID)
- }
- statusFailed := string(api.BackupStatusFailed)
- backup, err := s.store.UpdateBackupV2(ctx, &store.UpdateBackupMessage{
- UID: payload.BackupID,
- UpdaterID: api.SystemBotID,
- Status: &statusFailed,
- })
- if err != nil {
- return errors.Wrapf(err, "failed to patch backup %d's status from %s to %s", payload.BackupID, api.BackupStatusPendingCreate, api.BackupStatusFailed)
- }
- log.Debug(fmt.Sprintf("Changed backup %d's status from %s to %s", payload.BackupID, api.BackupStatusPendingCreate, api.BackupStatusFailed))
- if err := removeLocalBackupFile(s.profile.DataDir, backup); err != nil {
- log.Warn(err.Error())
- }
- }
- return nil
-}
-
var (
allowedStatementUpdateTaskTypes = map[api.TaskType]bool{
api.TaskDatabaseCreate: true,
@@ -691,139 +414,6 @@ func canUpdateTaskStatement(task *store.TaskMessage) *echo.HTTPError {
return nil
}
-// scheduleIfNeeded schedules the task if
-// 2. it has no blocking tasks.
-// 3. it has passed the earliest allowed time.
-func (s *Scheduler) scheduleIfNeeded(ctx context.Context, task *store.TaskMessage) error {
- blocked, err := s.isTaskBlocked(ctx, task)
- if err != nil {
- return errors.Wrap(err, "failed to check if task is blocked")
- }
- if blocked {
- return nil
- }
- if task.EarliestAllowedTs != 0 && time.Now().Before(time.Unix(task.EarliestAllowedTs, 0)) {
- return nil
- }
-
- return s.PatchTaskStatus(ctx, task, &api.TaskStatusPatch{
- ID: task.ID,
- UpdaterID: api.SystemBotID,
- Status: api.TaskRunning,
- })
-}
-
-func (s *Scheduler) isTaskBlocked(ctx context.Context, task *store.TaskMessage) (bool, error) {
- for _, block := range task.BlockedBy {
- blockingTask, err := s.store.GetTaskV2ByID(ctx, block)
- if err != nil {
- return true, errors.Wrapf(err, "failed to fetch the blocking task, id: %d", block)
- }
- if blockingTask.Status != api.TaskDone {
- return true, nil
- }
- }
- return false, nil
-}
-
-// scheduleAutoApprovedTasks schedules tasks that are approved automatically.
-func (s *Scheduler) scheduleAutoApprovedTasks(ctx context.Context) error {
- taskStatusList := []api.TaskStatus{api.TaskPendingApproval}
- taskList, err := s.store.ListTasks(ctx, &api.TaskFind{
- StatusList: &taskStatusList,
- NoBlockingStage: true,
- NonRollbackTask: true,
- })
- if err != nil {
- return err
- }
-
- for _, task := range taskList {
- instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{UID: &task.InstanceID})
- if err != nil {
- return err
- }
- if instance.Deleted {
- continue
- }
- environmentID := instance.EnvironmentID
- // TODO(d): support creating database with environment override.
- if task.DatabaseID != nil {
- database, err := s.store.GetDatabaseV2(ctx, &store.FindDatabaseMessage{UID: task.DatabaseID})
- if err != nil {
- return err
- }
- if database != nil {
- environmentID = database.EffectiveEnvironmentID
- }
- }
- environment, err := s.store.GetEnvironmentV2(ctx, &store.FindEnvironmentMessage{ResourceID: &environmentID})
- if err != nil {
- return err
- }
-
- policy, err := s.store.GetPipelineApprovalPolicy(ctx, environment.UID)
- if err != nil {
- return errors.Wrapf(err, "failed to get approval policy for environment ID %d", environment.UID)
- }
- if policy.Value != api.PipelineApprovalValueManualNever {
- continue
- }
-
- issue, err := s.store.GetIssueV2(ctx, &store.FindIssueMessage{PipelineID: &task.PipelineID})
- if err != nil {
- return err
- }
- if issue != nil {
- if issue.Status != api.IssueOpen {
- continue
- }
- approved, err := utils.CheckIssueApproved(issue)
- if err != nil {
- log.Warn("taskrun scheduler: failed to check if the issue is approved when scheduling auto-deployed tasks", zap.Int("taskID", task.ID), zap.Int("issueID", issue.UID), zap.Error(err))
- continue
- }
- if !approved {
- continue
- }
- }
-
- taskCheckRuns, err := s.store.ListTaskCheckRuns(ctx, &store.TaskCheckRunFind{TaskID: &task.ID})
- if err != nil {
- return err
- }
- ok, err := utils.PassAllCheck(task, api.TaskCheckStatusSuccess, taskCheckRuns, instance.Engine)
- if err != nil {
- return errors.Wrap(err, "failed to check if can auto-approve")
- }
- if ok {
- if err := s.PatchTaskStatus(ctx, task, &api.TaskStatusPatch{
- ID: task.ID,
- UpdaterID: api.SystemBotID,
- Status: api.TaskPending,
- }); err != nil {
- return errors.Wrap(err, "failed to change task status")
- }
- }
- }
- return nil
-}
-
-// schedulePendingTasks tries to schedule pending tasks.
-func (s *Scheduler) schedulePendingTasks(ctx context.Context) error {
- taskStatus := []api.TaskStatus{api.TaskPending}
- tasks, err := s.store.ListTasks(ctx, &api.TaskFind{StatusList: &taskStatus})
- if err != nil {
- return err
- }
- for _, task := range tasks {
- if err := s.scheduleIfNeeded(ctx, task); err != nil {
- return errors.Wrap(err, "failed to schedule task")
- }
- }
- return nil
-}
-
// PatchTaskStatus patches a single task.
func (s *Scheduler) PatchTaskStatus(ctx context.Context, task *store.TaskMessage, taskStatusPatch *api.TaskStatusPatch) (err error) {
defer func() {
@@ -1114,38 +704,6 @@ func (s *Scheduler) CanPrincipalBeAssignee(ctx context.Context, principalID int,
return false, nil
}
-// ChangeIssueStatus changes the status of an issue.
-func (s *Scheduler) ChangeIssueStatus(ctx context.Context, issue *store.IssueMessage, newStatus api.IssueStatus, updaterID int, comment string) error {
- updateIssueMessage := &store.UpdateIssueMessage{Status: &newStatus}
- updatedIssue, err := s.store.UpdateIssueV2(ctx, issue.UID, updateIssueMessage, updaterID)
- if err != nil {
- return errors.Wrapf(err, "failed to update issue %q's status", issue.Title)
- }
-
- payload, err := json.Marshal(api.ActivityIssueStatusUpdatePayload{
- OldStatus: issue.Status,
- NewStatus: newStatus,
- IssueName: updatedIssue.Title,
- })
- if err != nil {
- return errors.Wrapf(err, "failed to marshal activity after changing the issue status: %v", updatedIssue.Title)
- }
- activityCreate := &store.ActivityMessage{
- CreatorUID: updaterID,
- ContainerUID: issue.UID,
- Type: api.ActivityIssueStatusUpdate,
- Level: api.ActivityInfo,
- Comment: comment,
- Payload: string(payload),
- }
- if _, err := s.activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{
- Issue: updatedIssue,
- }); err != nil {
- return errors.Wrapf(err, "failed to create activity after changing the issue status: %v", updatedIssue.Title)
- }
- return nil
-}
-
func (s *Scheduler) onTaskStatusPatched(ctx context.Context, issue *store.IssueMessage, taskPatched *store.TaskMessage) error {
s.metricReporter.Report(ctx, &metric.Metric{
Name: metricAPI.TaskStatusMetricName,
@@ -1201,7 +759,7 @@ func (s *Scheduler) onTaskStatusPatched(ctx context.Context, issue *store.IssueM
if !taskStage.Active && nextStage == nil {
// Every task in the pipeline has finished.
// Resolve the issue automatically for the user.
- if err := s.ChangeIssueStatus(ctx, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
+ if err := utils.ChangeIssueStatus(ctx, s.store, s.activityManager, issue, api.IssueDone, api.SystemBotID, ""); err != nil {
log.Error("failed to change the issue status to done automatically after completing every task", zap.Error(err))
}
}
diff --git a/backend/server/issue.go b/backend/server/issue.go
index b97a672435..8b6c998a34 100644
--- a/backend/server/issue.go
+++ b/backend/server/issue.go
@@ -370,7 +370,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Issue ID not found: %d", id))
}
- if err := s.TaskScheduler.ChangeIssueStatus(ctx, issue, issueStatusPatch.Status, issueStatusPatch.UpdaterID, issueStatusPatch.Comment); err != nil {
+ if err := utils.ChangeIssueStatus(ctx, s.store, s.ActivityManager, issue, issueStatusPatch.Status, issueStatusPatch.UpdaterID, issueStatusPatch.Comment); err != nil {
if common.ErrorCode(err) == common.NotFound {
return echo.NewHTTPError(http.StatusNotFound).SetInternal(err)
} else if common.ErrorCode(err) == common.Conflict {
diff --git a/backend/utils/utils.go b/backend/utils/utils.go
index 3faf5c5a96..c895d2d146 100644
--- a/backend/utils/utils.go
+++ b/backend/utils/utils.go
@@ -23,6 +23,7 @@ import (
"github.com/bytebase/bytebase/backend/common"
"github.com/bytebase/bytebase/backend/common/log"
+ "github.com/bytebase/bytebase/backend/component/activity"
api "github.com/bytebase/bytebase/backend/legacyapi"
"github.com/bytebase/bytebase/backend/plugin/app/relay"
"github.com/bytebase/bytebase/backend/plugin/db"
@@ -1029,3 +1030,35 @@ func GetMatchedAndUnmatchedTablesInSchemaGroup(ctx context.Context, dbSchema *st
}
return matched, unmatched, nil
}
+
+// ChangeIssueStatus changes the status of an issue.
+func ChangeIssueStatus(ctx context.Context, stores *store.Store, activityManager *activity.Manager, issue *store.IssueMessage, newStatus api.IssueStatus, updaterID int, comment string) error {
+ updateIssueMessage := &store.UpdateIssueMessage{Status: &newStatus}
+ updatedIssue, err := stores.UpdateIssueV2(ctx, issue.UID, updateIssueMessage, updaterID)
+ if err != nil {
+ return errors.Wrapf(err, "failed to update issue %q's status", issue.Title)
+ }
+
+ payload, err := json.Marshal(api.ActivityIssueStatusUpdatePayload{
+ OldStatus: issue.Status,
+ NewStatus: newStatus,
+ IssueName: updatedIssue.Title,
+ })
+ if err != nil {
+ return errors.Wrapf(err, "failed to marshal activity after changing the issue status: %v", updatedIssue.Title)
+ }
+ activityCreate := &store.ActivityMessage{
+ CreatorUID: updaterID,
+ ContainerUID: issue.UID,
+ Type: api.ActivityIssueStatusUpdate,
+ Level: api.ActivityInfo,
+ Comment: comment,
+ Payload: string(payload),
+ }
+ if _, err := activityManager.CreateActivity(ctx, activityCreate, &activity.Metadata{
+ Issue: updatedIssue,
+ }); err != nil {
+ return errors.Wrapf(err, "failed to create activity after changing the issue status: %v", updatedIssue.Title)
+ }
+ return nil
+}