Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: move application/rollback/backup runners to runner package (#3725)
Danny Xud73a20e6c4da
diff --git a/api/external_approval.go b/api/external_approval.goindex 5aa6730c7a..30d1f9b83e 100644--- a/api/external_approval.go+++ b/api/external_approval.go@@ -81,3 +81,16 @@ type ExternalApprovalEvent struct {Action ExternalApprovalEventActionType `json:"action"`StageName string `json:"stageName"`}++const (+ // ExternalApprovalCancelReasonGeneral is the general reason, used as a default.+ ExternalApprovalCancelReasonGeneral string = "Canceled because the assignee has been changed, or the SQL has been modified, or all tasks of the stage have been approved or the issue is no longer open."+ // ExternalApprovalCancelReasonIssueNotOpen is used if the issue is not open.+ ExternalApprovalCancelReasonIssueNotOpen string = "Canceled because the containing issue is no longer open."+ // ExternalApprovalCancelReasonReassigned is used if the assignee has been changed.+ ExternalApprovalCancelReasonReassigned string = "Canceled because the assignee has changed."+ // ExternalApprovalCancelReasonSQLModified is used if the task SQL statement has been modified.+ ExternalApprovalCancelReasonSQLModified string = "Canceled because the SQL has been modified."+ // ExternalApprovalCancelReasonNoTaskPendingApproval is used if there is no pending approval tasks.+ ExternalApprovalCancelReasonNoTaskPendingApproval string = "Canceled because all tasks have been approved."+)diff --git a/server/component/state/state.go b/server/component/state/state.goindex 94d588430f..749e670be4 100644--- a/server/component/state/state.go+++ b/server/component/state/state.go@@ -1,9 +1,15 @@// Package state contains the synchronization state shared within the server.package state-import "github.com/bytebase/bytebase/api"+import (+ "sync"++ "github.com/bytebase/bytebase/api"+)var (// InstanceDatabaseSyncChan is the channel for synchronizing schemas for instances.InstanceDatabaseSyncChan = make(chan *api.Instance, 100)+ // RollbackGenerateMap is the set of tasks for generating rollback statements.+ RollbackGenerateMap sync.Map)diff --git a/server/database.go b/server/database.goindex 3aeed559df..37c542c77e 100644--- a/server/database.go+++ b/server/database.go@@ -449,7 +449,7 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Backup %q already exists", backupCreate.Name))}- backup, err := s.BackupRunner.scheduleBackupTask(ctx, database, backupCreate.Name, backupCreate.Type, c.Get(getPrincipalIDContextKey()).(int))+ backup, err := s.BackupRunner.ScheduleBackupTask(ctx, database, backupCreate.Name, backupCreate.Type, c.Get(getPrincipalIDContextKey()).(int))if err != nil {if common.ErrorCode(err) == common.DbConnectionFailure {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Failed to connect to instance %q", database.Instance.Name)).SetInternal(err)diff --git a/server/issue.go b/server/issue.goindex e28e6d83b3..bceb62ff17 100644--- a/server/issue.go+++ b/server/issue.go@@ -23,6 +23,7 @@ import ("github.com/bytebase/bytebase/plugin/db/util""github.com/bytebase/bytebase/plugin/vcs""github.com/bytebase/bytebase/server/component/activity"+ "github.com/bytebase/bytebase/server/utils")func (s *Server) registerIssueRoutes(g *echo.Group) {@@ -197,7 +198,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {if *issuePatch.AssigneeID == issue.AssigneeID {return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Cannot set assignee with user id %d because it's already the case", *issuePatch.AssigneeID))}- stage := getActiveStage(issue.Pipeline.StageList)+ stage := utils.GetActiveStage(issue.Pipeline.StageList)if stage == nil {// all stages have finished, use the last stagestage = issue.Pipeline.StageList[len(issue.Pipeline.StageList)-1]@@ -224,7 +225,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {// cancel external approval on assignee changeif issuePatch.AssigneeID != nil {- if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonReassigned); err != nil {+ if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonReassigned); err != nil {log.Error("failed to cancel external approval on assignee change", zap.Int("issue_id", issue.ID), zap.Error(err))}}diff --git a/server/application_runner.go b/server/runner/apprun/runner.gosimilarity index 85%rename from server/application_runner.gorename to server/runner/apprun/runner.goindex 32ced28b53..47da3331e7 100644--- a/server/application_runner.go+++ b/server/runner/apprun/runner.go@@ -1,4 +1,5 @@-package server+// Package apprun is an application runner for scanning Feishu approval instances.+package apprunimport ("context"@@ -15,27 +16,17 @@ import ("github.com/bytebase/bytebase/plugin/app/feishu""github.com/bytebase/bytebase/server/component/activity""github.com/bytebase/bytebase/server/component/config"+ "github.com/bytebase/bytebase/server/utils""github.com/bytebase/bytebase/store")const (- applicationRunnerInterval = time.Duration(60) * time.Second-- // externalApprovalCancelReasonGeneral is the general reason, used as a default.- externalApprovalCancelReasonGeneral string = "Canceled because the assignee has been changed, or the SQL has been modified, or all tasks of the stage have been approved or the issue is no longer open."- // externalApprovalCancelReasonIssueNotOpen is used if the issue is not open.- externalApprovalCancelReasonIssueNotOpen string = "Canceled because the containing issue is no longer open."- // externalApprovalCancelReasonReassigned is used if the assignee has been changed.- externalApprovalCancelReasonReassigned string = "Canceled because the assignee has changed."- // externalApprovalCancelReasonSQLModified is used if the task SQL statement has been modified.- externalApprovalCancelReasonSQLModified string = "Canceled because the SQL has been modified."- // externalApprovalCancelReasonNoTaskPendingApproval is used if there is no pending approval tasks.- externalApprovalCancelReasonNoTaskPendingApproval string = "Canceled because all tasks have been approved."+ runnerInterval = time.Duration(60) * time.Second)-// NewApplicationRunner returns a ApplicationRunner.-func NewApplicationRunner(store *store.Store, activityManager *activity.Manager, feishuProvider *feishu.Provider, profile config.Profile) *ApplicationRunner {- return &ApplicationRunner{+// NewRunner returns a runner.+func NewRunner(store *store.Store, activityManager *activity.Manager, feishuProvider *feishu.Provider, profile config.Profile) *Runner {+ return &Runner{store: store,activityManager: activityManager,p: feishuProvider,@@ -43,8 +34,8 @@ func NewApplicationRunner(store *store.Store, activityManager *activity.Manager,}}-// ApplicationRunner is a runner which periodically checks external approval status and approve the correspoding stages.-type ApplicationRunner struct {+// Runner is a runner which periodically checks external approval status and approve the correspoding stages.+type Runner struct {store *store.StoreactivityManager *activity.Managerp *feishu.Provider@@ -52,11 +43,11 @@ type ApplicationRunner struct {}// Run runs the ApplicationRunner.-func (r *ApplicationRunner) Run(ctx context.Context, wg *sync.WaitGroup) {- ticker := time.NewTicker(applicationRunnerInterval)+func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {+ ticker := time.NewTicker(runnerInterval)defer ticker.Stop()defer wg.Done()- log.Debug(fmt.Sprintf("Application runner started and will run every %v", applicationRunnerInterval))+ log.Debug(fmt.Sprintf("Application runner started and will run every %v", runnerInterval))// Try to update approval definition if external approval is enabled, because our approval definition may have changed.if err := r.tryUpdateApprovalDefinition(ctx); err != nil {log.Error("failed to update approval definition on application runner start", zap.Error(err))@@ -130,12 +121,12 @@ func (r *ApplicationRunner) Run(ctx context.Context, wg *sync.WaitGroup) {log.Error("expect to have found issue in application runner", zap.Int("issue_id", externalApproval.IssueID))continue}- stage := getActiveStage(issue.Pipeline.StageList)+ stage := utils.GetActiveStage(issue.Pipeline.StageList)if stage == nil {stage = issue.Pipeline.StageList[len(issue.Pipeline.StageList)-1]}if issue.Status != api.IssueOpen {- if err := r.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonIssueNotOpen); err != nil {+ if err := r.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonIssueNotOpen); err != nil {log.Error("failed to cancel external approval", zap.Error(err))}continue@@ -257,7 +248,7 @@ func (r *ApplicationRunner) Run(ctx context.Context, wg *sync.WaitGroup) {}}-func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.Context, issue *api.Issue, stage *api.Stage, settingValue *api.SettingAppIMValue) (*api.ExternalApproval, error) {+func (r *Runner) cancelOldExternalApprovalIfNeeded(ctx context.Context, issue *api.Issue, stage *api.Stage, settingValue *api.SettingAppIMValue) (*api.ExternalApproval, error) {approval, err := r.store.GetExternalApprovalByIssueID(ctx, issue.ID)if err != nil {return nil, err@@ -270,14 +261,14 @@ func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.Contexreturn nil, err}- reason := externalApprovalCancelReasonGeneral+ reason := api.ExternalApprovalCancelReasonGeneralcancelOld := func() bool {if payload.StageID != stage.ID {- reason = externalApprovalCancelReasonNoTaskPendingApproval+ reason = api.ExternalApprovalCancelReasonNoTaskPendingApprovalreturn true}if payload.AssigneeID != issue.AssigneeID {- reason = externalApprovalCancelReasonReassigned+ reason = api.ExternalApprovalCancelReasonReassignedreturn true}pendingApprovalCount := 0@@ -287,7 +278,7 @@ func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.Contex}}if pendingApprovalCount == 0 {- reason = externalApprovalCancelReasonNoTaskPendingApproval+ reason = api.ExternalApprovalCancelReasonNoTaskPendingApprovalreturn true}return false@@ -332,7 +323,7 @@ func (r *ApplicationRunner) cancelOldExternalApprovalIfNeeded(ctx context.Contex}// CancelExternalApproval cancels the active external approval of an issue.-func (r *ApplicationRunner) CancelExternalApproval(ctx context.Context, issueID int, reason string) error {+func (r *Runner) CancelExternalApproval(ctx context.Context, issueID int, reason string) error {settingName := api.SettingAppIMsetting, err := r.store.GetSetting(ctx, &api.SettingFind{Name: &settingName})if err != nil {@@ -395,7 +386,7 @@ func (r *ApplicationRunner) CancelExternalApproval(ctx context.Context, issueID)}-func (r *ApplicationRunner) shouldCreateExternalApproval(ctx context.Context, issue *api.Issue, stage *api.Stage, oldApproval *api.ExternalApproval) (bool, error) {+func (r *Runner) shouldCreateExternalApproval(ctx context.Context, issue *api.Issue, stage *api.Stage, oldApproval *api.ExternalApproval) (bool, error) {policy, err := r.store.GetPipelineApprovalPolicy(ctx, stage.EnvironmentID)if err != nil {return false, err@@ -452,7 +443,7 @@ func (r *ApplicationRunner) shouldCreateExternalApproval(ctx context.Context, isreturn true, nil}-func (r *ApplicationRunner) createExternalApproval(ctx context.Context, issue *api.Issue, stage *api.Stage, settingValue *api.SettingAppIMValue) error {+func (r *Runner) createExternalApproval(ctx context.Context, issue *api.Issue, stage *api.Stage, settingValue *api.SettingAppIMValue) error {users, err := r.p.GetIDByEmail(ctx,feishu.TokenCtx{AppID: settingValue.AppID,@@ -548,7 +539,7 @@ func getTaskStatement(task *api.Task) (string, error) {}// scheduleApproval tries to cancel old external apporvals and create new external approvals if needed.-func (r *ApplicationRunner) scheduleApproval(ctx context.Context, issue *api.Issue, settingValue *api.SettingAppIMValue) {+func (r *Runner) scheduleApproval(ctx context.Context, issue *api.Issue, settingValue *api.SettingAppIMValue) {if !settingValue.ExternalApproval.Enabled {return}@@ -558,7 +549,7 @@ func (r *ApplicationRunner) scheduleApproval(ctx context.Context, issue *api.Issreturn}- stage := getActiveStage(issue.Pipeline.StageList)+ stage := utils.GetActiveStage(issue.Pipeline.StageList)if stage == nil {stage = issue.Pipeline.StageList[len(issue.Pipeline.StageList)-1]}@@ -591,7 +582,7 @@ func (r *ApplicationRunner) scheduleApproval(ctx context.Context, issue *api.Iss// tryUpdateApprovalDefinition is run on application runner start.// The approval definition may have changed so we make idempotent POST request to patch the definition.-func (r *ApplicationRunner) tryUpdateApprovalDefinition(ctx context.Context) error {+func (r *Runner) tryUpdateApprovalDefinition(ctx context.Context) error {settingName := api.SettingAppIMsetting, err := r.store.GetSetting(ctx, &api.SettingFind{Name: &settingName})if err != nil {diff --git a/server/backup_runner.go b/server/runner/backuprun/runner.gosimilarity index 86%rename from server/backup_runner.gorename to server/runner/backuprun/runner.goindex c38368d4ed..bff1c207a3 100644--- a/server/backup_runner.go+++ b/server/runner/backuprun/runner.go@@ -1,4 +1,5 @@-package server+// Package backuprun is the runner for backups.+package backuprunimport ("context"@@ -8,6 +9,7 @@ import ("net/http""os""path"+ "path/filepath""sync""time"@@ -26,9 +28,9 @@ import ("github.com/bytebase/bytebase/store")-// NewBackupRunner creates a new backup runner.-func NewBackupRunner(store *store.Store, dbFactory *dbfactory.DBFactory, s3Client *s3.Client, profile *config.Profile) *BackupRunner {- return &BackupRunner{+// NewRunner creates a new backup runner.+func NewRunner(store *store.Store, dbFactory *dbfactory.DBFactory, s3Client *s3.Client, profile *config.Profile) *Runner {+ return &Runner{store: store,dbFactory: dbFactory,s3Client: s3Client,@@ -37,8 +39,8 @@ func NewBackupRunner(store *store.Store, dbFactory *dbfactory.DBFactory, s3Clien}}-// BackupRunner is the backup runner scheduling automatic backups.-type BackupRunner struct {+// Runner is the backup runner scheduling automatic backups.+type Runner struct {store *store.StoredbFactory *dbfactory.DBFactorys3Client *s3.Client@@ -50,7 +52,7 @@ type BackupRunner struct {}// Run is the runner for backup runner.-func (r *BackupRunner) Run(ctx context.Context, wg *sync.WaitGroup) {+func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(r.profile.BackupRunnerInterval)defer ticker.Stop()defer wg.Done()@@ -84,7 +86,7 @@ func (r *BackupRunner) Run(ctx context.Context, wg *sync.WaitGroup) {// TODO(dragonly): Make best effort to assure that users could recover to at least RetentionPeriodTs ago.// This may require pending deleting expired backup files and binlog files.-func (r *BackupRunner) purgeExpiredBackupData(ctx context.Context) {+func (r *Runner) purgeExpiredBackupData(ctx context.Context) {backupSettingList, err := r.store.FindBackupSetting(ctx, api.BackupSettingFind{})if err != nil {log.Error("Failed to find all the backup settings.", zap.Error(err))@@ -140,7 +142,7 @@ func (r *BackupRunner) purgeExpiredBackupData(ctx context.Context) {}}-func (r *BackupRunner) getMaxRetentionPeriodTsForMySQLInstance(ctx context.Context, instance *api.Instance) (int, error) {+func (r *Runner) getMaxRetentionPeriodTsForMySQLInstance(ctx context.Context, instance *api.Instance) (int, error) {backupSettingList, err := r.store.FindBackupSetting(ctx, api.BackupSettingFind{InstanceID: &instance.ID})if err != nil {log.Error("Failed to find backup settings for instance.", zap.String("instance", instance.Name), zap.Error(err))@@ -155,7 +157,7 @@ func (r *BackupRunner) getMaxRetentionPeriodTsForMySQLInstance(ctx context.Contereturn maxRetentionPeriodTs, nil}-func (r *BackupRunner) purgeBinlogFiles(ctx context.Context, instanceID, retentionPeriodTs int) error {+func (r *Runner) purgeBinlogFiles(ctx context.Context, instanceID, retentionPeriodTs int) error {binlogDir := common.GetBinlogAbsDir(r.profile.DataDir, instanceID)switch r.profile.BackupStorageBackend {case api.BackupStorageBackendLocal:@@ -167,7 +169,7 @@ func (r *BackupRunner) purgeBinlogFiles(ctx context.Context, instanceID, retenti}}-func (r *BackupRunner) purgeBinlogFilesOnCloud(ctx context.Context, binlogDir string, retentionPeriodTs int) error {+func (r *Runner) purgeBinlogFilesOnCloud(ctx context.Context, binlogDir string, retentionPeriodTs int) error {binlogDirOnCloud := common.GetBinlogRelativeDir(binlogDir)listOutput, err := r.s3Client.ListObjects(ctx, binlogDirOnCloud)if err != nil {@@ -190,7 +192,7 @@ func (r *BackupRunner) purgeBinlogFilesOnCloud(ctx context.Context, binlogDir st}// TODO(dragonly): Remove metadata as well.-func (*BackupRunner) purgeBinlogFilesLocal(binlogDir string, retentionPeriodTs int) error {+func (*Runner) purgeBinlogFilesLocal(binlogDir string, retentionPeriodTs int) error {binlogFileInfoList, err := os.ReadDir(binlogDir)if err != nil {return errors.Wrapf(err, "failed to read backup directory %q", binlogDir)@@ -218,7 +220,7 @@ func (*BackupRunner) purgeBinlogFilesLocal(binlogDir string, retentionPeriodTs ireturn nil}-func (r *BackupRunner) purgeBackup(ctx context.Context, backup *api.Backup) error {+func (r *Runner) purgeBackup(ctx context.Context, backup *api.Backup) error {archive := api.ArchivedbackupPatch := api.BackupPatch{ID: backup.ID,@@ -232,7 +234,7 @@ func (r *BackupRunner) purgeBackup(ctx context.Context, backup *api.Backup) erroswitch backup.StorageBackend {case api.BackupStorageBackendLocal:- backupFilePath := getBackupAbsFilePath(r.profile.DataDir, backup.DatabaseID, backup.Name)+ backupFilePath := GetBackupAbsFilePath(r.profile.DataDir, backup.DatabaseID, backup.Name)if err := os.Remove(backupFilePath); err != nil {return errors.Wrapf(err, "failed to delete an expired backup file %q", backupFilePath)}@@ -248,7 +250,7 @@ func (r *BackupRunner) purgeBackup(ctx context.Context, backup *api.Backup) erroreturn nil}-func (r *BackupRunner) downloadBinlogFiles(ctx context.Context) {+func (r *Runner) downloadBinlogFiles(ctx context.Context) {instanceList, err := r.store.FindInstanceWithDatabaseBackupEnabled(ctx, db.MySQL)if err != nil {log.Error("Failed to retrieve MySQL instance list with at least one database backup enabled", zap.Error(err))@@ -266,7 +268,7 @@ func (r *BackupRunner) downloadBinlogFiles(ctx context.Context) {}}-func (r *BackupRunner) downloadBinlogFilesForInstance(ctx context.Context, instance *api.Instance) {+func (r *Runner) downloadBinlogFilesForInstance(ctx context.Context, instance *api.Instance) {defer func() {r.downloadBinlogMu.Lock()delete(r.downloadBinlogInstanceIDs, instance.ID)@@ -295,7 +297,7 @@ func (r *BackupRunner) downloadBinlogFilesForInstance(ctx context.Context, insta}}-func (r *BackupRunner) startAutoBackups(ctx context.Context, runningTasks map[int]bool, mu *sync.RWMutex) {+func (r *Runner) startAutoBackups(ctx context.Context, runningTasks map[int]bool, mu *sync.RWMutex) {// Find all databases that need a backup in this hour.t := time.Now().UTC().Truncate(time.Hour)match := &api.BackupSettingsMatch{@@ -346,7 +348,7 @@ func (r *BackupRunner) startAutoBackups(ctx context.Context, runningTasks map[inzap.String("database", database.Name),zap.String("backup", backupName),)- if _, err := r.scheduleBackupTask(ctx, database, backupName, api.BackupTypeAutomatic, api.SystemBotID); err != nil {+ if _, err := r.ScheduleBackupTask(ctx, database, backupName, api.BackupTypeAutomatic, api.SystemBotID); err != nil {log.Error("Failed to create automatic backup for database",zap.Int("databaseID", database.ID),zap.Error(err))@@ -367,7 +369,8 @@ func (r *BackupRunner) startAutoBackups(ctx context.Context, runningTasks map[in}}-func (r *BackupRunner) scheduleBackupTask(ctx context.Context, database *api.Database, backupName string, backupType api.BackupType, creatorID int) (*api.Backup, error) {+// ScheduleBackupTask schedules a backup task.+func (r *Runner) ScheduleBackupTask(ctx context.Context, database *api.Database, backupName string, backupType api.BackupType, creatorID int) (*api.Backup, error) {// Store the migration history version if exists.driver, err := r.dbFactory.GetAdminDatabaseDriver(ctx, database.Instance, database.Name)if err != nil {@@ -443,3 +446,26 @@ func (r *BackupRunner) scheduleBackupTask(ctx context.Context, database *api.Dat}return backupNew, nil}++// Get backup dir relative to the data dir.+func getBackupRelativeDir(databaseID int) string {+ return filepath.Join("backup", "db", fmt.Sprintf("%d", databaseID))+}++func getBackupRelativeFilePath(databaseID int, name string) string {+ dir := getBackupRelativeDir(databaseID)+ return filepath.Join(dir, fmt.Sprintf("%s.sql", name))+}++// GetBackupAbsFilePath returns backup absolute file path for a database.+func GetBackupAbsFilePath(dataDir string, databaseID int, name string) string {+ path := getBackupRelativeFilePath(databaseID, name)+ return filepath.Join(dataDir, path)+}++// Create backup directory for database.+func createBackupDirectory(dataDir string, databaseID int) error {+ dir := getBackupRelativeDir(databaseID)+ absDir := filepath.Join(dataDir, dir)+ return os.MkdirAll(absDir, os.ModePerm)+}diff --git a/server/rollback_runner.go b/server/runner/rollbackrun/runner.gosimilarity index 82%rename from server/rollback_runner.gorename to server/runner/rollbackrun/runner.goindex 9355c4f94e..057483628e 100644--- a/server/rollback_runner.go+++ b/server/runner/rollbackrun/runner.go@@ -1,4 +1,5 @@-package server+// Package rollbackrun is the runner for generating rollback statements for DMLs.+package rollbackrunimport ("context"@@ -15,26 +16,26 @@ import ("github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/plugin/db/mysql""github.com/bytebase/bytebase/server/component/dbfactory"+ "github.com/bytebase/bytebase/server/component/state""github.com/bytebase/bytebase/store")-// NewRollbackRunner creates a new rollback runner.-func NewRollbackRunner(store *store.Store, dbFactory *dbfactory.DBFactory) *RollbackRunner {- return &RollbackRunner{+// NewRunner creates a new rollback runner.+func NewRunner(store *store.Store, dbFactory *dbfactory.DBFactory) *Runner {+ return &Runner{store: store,dbFactory: dbFactory,}}-// RollbackRunner is the rollback runner generating rollback SQL statements.-type RollbackRunner struct {- store *store.Store- dbFactory *dbfactory.DBFactory- generateMap sync.Map+// Runner is the rollback runner generating rollback SQL statements.+type Runner struct {+ store *store.Store+ dbFactory *dbfactory.DBFactory}// Run starts the rollback runner.-func (r *RollbackRunner) Run(ctx context.Context, wg *sync.WaitGroup) {+func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup) {ticker := time.NewTicker(1 * time.Second)defer ticker.Stop()defer wg.Done()@@ -42,11 +43,11 @@ func (r *RollbackRunner) Run(ctx context.Context, wg *sync.WaitGroup) {for {select {case <-ticker.C:- r.generateMap.Range(func(key, value any) bool {+ state.RollbackGenerateMap.Range(func(key, value any) bool {task := value.(*api.Task)log.Debug(fmt.Sprintf("Generating rollback SQL for task %d", task.ID))r.generateRollbackSQL(ctx, task)- r.generateMap.Delete(key)+ state.RollbackGenerateMap.Delete(key)return true})case <-ctx.Done(): // if cancel() execute@@ -57,7 +58,7 @@ func (r *RollbackRunner) Run(ctx context.Context, wg *sync.WaitGroup) {// retryGenerateRollbackSQL retries generating rollback SQL for tasks.// It is currently called when Bytebase server starts and only rerun unfinished generation.-func (r *RollbackRunner) retryGenerateRollbackSQL(ctx context.Context) {+func (r *Runner) retryGenerateRollbackSQL(ctx context.Context) {find := &api.TaskFind{StatusList: &[]api.TaskStatus{api.TaskDone},TypeList: &[]api.TaskType{api.TaskDatabaseDataUpdate},@@ -70,11 +71,11 @@ func (r *RollbackRunner) retryGenerateRollbackSQL(ctx context.Context) {}for _, task := range taskList {log.Debug("retry generate rollback SQL for task", zap.Int("ID", task.ID), zap.String("name", task.Name))- r.generateMap.Store(task.ID, task)+ state.RollbackGenerateMap.Store(task.ID, task)}}-func (r *RollbackRunner) generateRollbackSQL(ctx context.Context, task *api.Task) {+func (r *Runner) generateRollbackSQL(ctx context.Context, task *api.Task) {defer func() {if r := recover(); r != nil {err, ok := r.(error)@@ -116,7 +117,7 @@ func (r *RollbackRunner) generateRollbackSQL(ctx context.Context, task *api.Tasklog.Debug("Rollback SQL generation success", zap.Int("taskID", task.ID))}-func (r *RollbackRunner) generateRollbackSQLImpl(ctx context.Context, task *api.Task, payload *api.TaskDatabaseDataUpdatePayload) (string, error) {+func (r *Runner) generateRollbackSQLImpl(ctx context.Context, task *api.Task, payload *api.TaskDatabaseDataUpdatePayload) (string, error) {basename, seqStart, err := mysql.ParseBinlogName(payload.BinlogFileStart)if err != nil {return "", errors.WithMessagef(err, "invalid start binlog file name %s", payload.BinlogFileStart)diff --git a/server/server.go b/server/server.goindex fc39dcd133..b9ed5546b6 100644--- a/server/server.go+++ b/server/server.go@@ -40,6 +40,9 @@ import ("github.com/bytebase/bytebase/server/component/config""github.com/bytebase/bytebase/server/component/dbfactory""github.com/bytebase/bytebase/server/runner/anomaly"+ "github.com/bytebase/bytebase/server/runner/apprun"+ "github.com/bytebase/bytebase/server/runner/backuprun"+ "github.com/bytebase/bytebase/server/runner/rollbackrun""github.com/bytebase/bytebase/server/runner/schemasync""github.com/bytebase/bytebase/server/runner/taskcheck""github.com/bytebase/bytebase/store"@@ -92,10 +95,10 @@ type Server struct {TaskCheckScheduler *taskcheck.SchedulerMetricReporter *MetricReporterSchemaSyncer *schemasync.Syncer- BackupRunner *BackupRunner+ BackupRunner *backuprun.RunnerAnomalyScanner *anomaly.Scanner- ApplicationRunner *ApplicationRunner- RollbackRunner *RollbackRunner+ ApplicationRunner *apprun.Runner+ RollbackRunner *rollbackrun.RunnerrunnerWG sync.WaitGroupActivityManager *activity.Manager@@ -117,7 +120,8 @@ type Server struct {// Postgres utility binariespgBinDir string- s3Client *bbs3.Client+ s3Client *bbs3.Client+ feishuProvider *feishu.Provider// boot specifies that whether the server boot correctlycancel context.CancelFunc@@ -286,17 +290,19 @@ func NewServer(ctx context.Context, profile config.Profile) (*Server, error) {if !profile.Readonly {s.SchemaSyncer = schemasync.NewSyncer(storeInstance, s.dbFactory)- s.ApplicationRunner = NewApplicationRunner(storeInstance, s.ActivityManager, feishu.NewProvider(profile.FeishuAPIURL), profile)- s.BackupRunner = NewBackupRunner(storeInstance, s.dbFactory, s.s3Client, &profile)- s.RollbackRunner = NewRollbackRunner(storeInstance, s.dbFactory)+ // TODO(p0ny): enable Feishu provider only when it is needed.+ s.feishuProvider = feishu.NewProvider(profile.FeishuAPIURL)+ s.ApplicationRunner = apprun.NewRunner(storeInstance, s.ActivityManager, s.feishuProvider, profile)+ s.BackupRunner = backuprun.NewRunner(storeInstance, s.dbFactory, s.s3Client, &profile)+ s.RollbackRunner = rollbackrun.NewRunner(storeInstance, s.dbFactory)taskScheduler := NewTaskScheduler(s, storeInstance, s.ApplicationRunner, s.SchemaSyncer, s.ActivityManager, s.licenseService, profile)taskScheduler.Register(api.TaskGeneral, NewDefaultTaskExecutor())taskScheduler.Register(api.TaskDatabaseCreate, NewDatabaseCreateTaskExecutor(storeInstance, s.dbFactory, profile))- taskScheduler.Register(api.TaskDatabaseSchemaBaseline, NewSchemaBaselineTaskExecutor(storeInstance, s.dbFactory, s.RollbackRunner, s.ActivityManager, profile))- taskScheduler.Register(api.TaskDatabaseSchemaUpdate, NewSchemaUpdateTaskExecutor(storeInstance, s.dbFactory, s.RollbackRunner, s.ActivityManager, profile))- taskScheduler.Register(api.TaskDatabaseSchemaUpdateSDL, NewSchemaUpdateSDLTaskExecutor(storeInstance, s.dbFactory, s.RollbackRunner, s.ActivityManager, profile))- taskScheduler.Register(api.TaskDatabaseDataUpdate, NewDataUpdateTaskExecutor(storeInstance, s.dbFactory, s.RollbackRunner, s.ActivityManager, profile))+ taskScheduler.Register(api.TaskDatabaseSchemaBaseline, NewSchemaBaselineTaskExecutor(storeInstance, s.dbFactory, s.ActivityManager, profile))+ taskScheduler.Register(api.TaskDatabaseSchemaUpdate, NewSchemaUpdateTaskExecutor(storeInstance, s.dbFactory, s.ActivityManager, profile))+ taskScheduler.Register(api.TaskDatabaseSchemaUpdateSDL, NewSchemaUpdateSDLTaskExecutor(storeInstance, s.dbFactory, s.ActivityManager, profile))+ taskScheduler.Register(api.TaskDatabaseDataUpdate, NewDataUpdateTaskExecutor(storeInstance, s.dbFactory, s.ActivityManager, profile))taskScheduler.Register(api.TaskDatabaseBackup, NewDatabaseBackupTaskExecutor(storeInstance, s.dbFactory, s.s3Client, profile))taskScheduler.Register(api.TaskDatabaseSchemaUpdateGhostSync, NewSchemaUpdateGhostSyncTaskExecutor(storeInstance, taskScheduler))taskScheduler.Register(api.TaskDatabaseSchemaUpdateGhostCutover, NewSchemaUpdateGhostCutoverTaskExecutor(storeInstance, s.dbFactory, taskScheduler, s.ActivityManager, profile))diff --git a/server/setting.go b/server/setting.goindex 002812bbee..02a8b7f47b 100644--- a/server/setting.go+++ b/server/setting.go@@ -75,7 +75,7 @@ func (s *Server) registerSettingRoutes(g *echo.Group) {if value.AppID == "" || value.AppSecret == "" {return echo.NewHTTPError(http.StatusBadRequest, "Application ID and secret cannot be empty")}- p := s.ApplicationRunner.p+ p := s.feishuProvider// clear token cache so that we won't use the previous token.p.ClearTokenCache()diff --git a/server/task.go b/server/task.goindex 8acf33c647..06a7fa5e4e 100644--- a/server/task.go+++ b/server/task.go@@ -363,7 +363,7 @@ func (s *Server) patchTask(ctx context.Context, task *api.Task, taskPatch *api.T// create an activity and trigger task check for statement updateif oldStatement != newStatement {// it's ok to fail.- if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonSQLModified); err != nil {+ if err := s.ApplicationRunner.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonSQLModified); err != nil {log.Error("failed to cancel external approval on SQL modified", zap.Int("issue_id", issue.ID), zap.Error(err))}diff --git a/server/task_executor.go b/server/task_executor.goindex bbba83e2b1..ab6fdfc64d 100644--- a/server/task_executor.go+++ b/server/task_executor.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/component/state""github.com/bytebase/bytebase/store")@@ -125,7 +126,7 @@ func preMigration(ctx context.Context, store *store.Store, profile config.Profilreturn mi, nil}-func executeMigration(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, rollbackRunner *RollbackRunner, task *api.Task, statement string, mi *db.MigrationInfo) (migrationID int64, schema string, err error) {+func executeMigration(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, task *api.Task, statement string, mi *db.MigrationInfo) (migrationID int64, schema string, err error) {statement = strings.TrimSpace(statement)databaseName := task.Database.Name@@ -170,7 +171,7 @@ func executeMigration(ctx context.Context, store *store.Store, dbFactory *dbfactreturn 0, "", errors.Wrap(err, "failed to update the task payload for MySQL rollback SQL")}// The runner will periodically scan the map to generate rollback SQL asynchronously.- rollbackRunner.generateMap.Store(updatedTask.ID, updatedTask)+ state.RollbackGenerateMap.Store(updatedTask.ID, updatedTask)}return migrationID, schema, nil@@ -419,12 +420,12 @@ func postMigration(ctx context.Context, store *store.Store, activityManager *act}, nil}-func runMigration(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, rollbackRunner *RollbackRunner, activityManager *activity.Manager, profile config.Profile, task *api.Task, migrationType db.MigrationType, statement, schemaVersion string, vcsPushEvent *vcsPlugin.PushEvent) (terminated bool, result *api.TaskRunResultPayload, err error) {+func runMigration(ctx context.Context, store *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, profile config.Profile, task *api.Task, migrationType db.MigrationType, statement, schemaVersion string, vcsPushEvent *vcsPlugin.PushEvent) (terminated bool, result *api.TaskRunResultPayload, err error) {mi, err := preMigration(ctx, store, profile, task, migrationType, statement, schemaVersion, vcsPushEvent)if err != nil {return true, nil, err}- migrationID, schema, err := executeMigration(ctx, store, dbFactory, rollbackRunner, task, statement, mi)+ migrationID, schema, err := executeMigration(ctx, store, dbFactory, task, statement, mi)if err != nil {return true, nil, err}diff --git a/server/task_executor_data_update.go b/server/task_executor_data_update.goindex bef5729ac1..58d4d33508 100644--- a/server/task_executor_data_update.go+++ b/server/task_executor_data_update.go@@ -15,11 +15,10 @@ import ()// NewDataUpdateTaskExecutor creates a data update (DML) task executor.-func NewDataUpdateTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, rollbackRunner *RollbackRunner, activityManager *activity.Manager, profile config.Profile) TaskExecutor {+func NewDataUpdateTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, profile config.Profile) TaskExecutor {return &DataUpdateTaskExecutor{store: store,dbFactory: dbFactory,- rollbackRunner: rollbackRunner,activityManager: activityManager,profile: profile,}@@ -29,7 +28,6 @@ func NewDataUpdateTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactortype DataUpdateTaskExecutor struct {store *store.StoredbFactory *dbfactory.DBFactory- rollbackRunner *RollbackRunneractivityManager *activity.Managerprofile config.Profile}@@ -41,5 +39,5 @@ func (exec *DataUpdateTaskExecutor) RunOnce(ctx context.Context, task *api.Task)return true, nil, errors.Wrap(err, "invalid database data update payload")}- return runMigration(ctx, exec.store, exec.dbFactory, exec.rollbackRunner, exec.activityManager, exec.profile, task, db.Data, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)+ return runMigration(ctx, exec.store, exec.dbFactory, exec.activityManager, exec.profile, task, db.Data, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)}diff --git a/server/task_executor_database_backup.go b/server/task_executor_database_backup.goindex 245c49885d..f1b578a8dc 100644--- a/server/task_executor_database_backup.go+++ b/server/task_executor_database_backup.go@@ -17,6 +17,7 @@ import (bbs3 "github.com/bytebase/bytebase/plugin/storage/s3""github.com/bytebase/bytebase/server/component/config""github.com/bytebase/bytebase/server/component/dbfactory"+ "github.com/bytebase/bytebase/server/runner/backuprun""github.com/bytebase/bytebase/store")@@ -105,7 +106,7 @@ func removeLocalBackupFile(dataDir string, backup *api.Backup) error {if backup.StorageBackend != api.BackupStorageBackendLocal {return nil}- backupFilePath := getBackupAbsFilePath(dataDir, backup.DatabaseID, backup.Name)+ backupFilePath := backuprun.GetBackupAbsFilePath(dataDir, backup.DatabaseID, backup.Name)if err := os.Remove(backupFilePath); err != nil {return errors.Wrapf(err, "failed to delete the local backup file %s", backupFilePath)}@@ -180,25 +181,3 @@ func (*DatabaseBackupTaskExecutor) backupDatabase(ctx context.Context, dbFactoryreturn "", errors.Errorf("backup to %s not implemented yet", backup.StorageBackend)}}--// Get backup dir relative to the data dir.-func getBackupRelativeDir(databaseID int) string {- return filepath.Join("backup", "db", fmt.Sprintf("%d", databaseID))-}--func getBackupRelativeFilePath(databaseID int, name string) string {- dir := getBackupRelativeDir(databaseID)- return filepath.Join(dir, fmt.Sprintf("%s.sql", name))-}--func getBackupAbsFilePath(dataDir string, databaseID int, name string) string {- path := getBackupRelativeFilePath(databaseID, name)- return filepath.Join(dataDir, path)-}--// Create backup directory for database.-func createBackupDirectory(dataDir string, databaseID int) error {- dir := getBackupRelativeDir(databaseID)- absDir := filepath.Join(dataDir, dir)- return os.MkdirAll(absDir, os.ModePerm)-}diff --git a/server/task_executor_pitr_cutover.go b/server/task_executor_pitr_cutover.goindex 017f31f325..2a052c3f09 100644--- a/server/task_executor_pitr_cutover.go+++ b/server/task_executor_pitr_cutover.go@@ -20,12 +20,13 @@ 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/runner/backuprun""github.com/bytebase/bytebase/server/runner/schemasync""github.com/bytebase/bytebase/store")// NewPITRCutoverTaskExecutor creates a PITR cutover task executor.-func NewPITRCutoverTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, schemaSyncer *schemasync.Syncer, backupRunner *BackupRunner, activityManager *activity.Manager, profile config.Profile) TaskExecutor {+func NewPITRCutoverTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, schemaSyncer *schemasync.Syncer, backupRunner *backuprun.Runner, activityManager *activity.Manager, profile config.Profile) TaskExecutor {return &PITRCutoverTaskExecutor{store: store,dbFactory: dbFactory,@@ -41,7 +42,7 @@ type PITRCutoverTaskExecutor struct {store *store.StoredbFactory *dbfactory.DBFactoryschemaSyncer *schemasync.Syncer- backupRunner *BackupRunner+ backupRunner *backuprun.RunneractivityManager *activity.Managerprofile config.Profile}@@ -93,7 +94,7 @@ func (exec *PITRCutoverTaskExecutor) RunOnce(ctx context.Context, task *api.Task// 1. Swap the current and PITR database.// 2. Create a backup with type PITR. The backup is scheduled asynchronously.// We must check the possible failed/ongoing PITR type backup in the recovery process.-func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, dbFactory *dbfactory.DBFactory, backupRunner *BackupRunner, schemaSyncer *schemasync.Syncer, profile config.Profile, task *api.Task, issue *api.Issue) (terminated bool, result *api.TaskRunResultPayload, err error) {+func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, dbFactory *dbfactory.DBFactory, backupRunner *backuprun.Runner, schemaSyncer *schemasync.Syncer, profile config.Profile, task *api.Task, issue *api.Issue) (terminated bool, result *api.TaskRunResultPayload, err error) {driver, err := dbFactory.GetAdminDatabaseDriver(ctx, task.Instance, "" /* databaseName */)if err != nil {return true, nil, err@@ -129,7 +130,7 @@ func (exec *PITRCutoverTaskExecutor) pitrCutover(ctx context.Context, dbFactory// TODO(dragonly): Only needed for in-place PITR.backupName := fmt.Sprintf("%s-%s-pitr-%d", api.ProjectShortSlug(task.Database.Project), api.EnvSlug(task.Database.Instance.Environment), issue.CreatedTs)- if _, err := backupRunner.scheduleBackupTask(ctx, task.Database, backupName, api.BackupTypePITR, api.SystemBotID); err != nil {+ if _, err := backupRunner.ScheduleBackupTask(ctx, task.Database, backupName, api.BackupTypePITR, api.SystemBotID); err != nil {return true, nil, errors.Wrapf(err, "failed to schedule backup task for database %q after PITR", task.Database.Name)}diff --git a/server/task_executor_pitr_restore.go b/server/task_executor_pitr_restore.goindex dc665e490b..24f084c562 100644--- a/server/task_executor_pitr_restore.go+++ b/server/task_executor_pitr_restore.go@@ -23,6 +23,7 @@ import (bbs3 "github.com/bytebase/bytebase/plugin/storage/s3""github.com/bytebase/bytebase/server/component/config""github.com/bytebase/bytebase/server/component/dbfactory"+ "github.com/bytebase/bytebase/server/runner/backuprun""github.com/bytebase/bytebase/server/runner/schemasync""github.com/bytebase/bytebase/store")@@ -228,7 +229,7 @@ func (exec *PITRRestoreTaskExecutor) doPITRRestore(ctx context.Context, store *sbinlogDir := common.GetBinlogAbsDir(profile.DataDir, task.Instance.ID)log.Debug("Got latest backup before or equal to targetTs", zap.String("backup", backup.Name))- backupAbsPathLocal := getBackupAbsFilePath(profile.DataDir, backup.DatabaseID, backup.Name)+ backupAbsPathLocal := backuprun.GetBackupAbsFilePath(profile.DataDir, backup.DatabaseID, backup.Name)if backup.StorageBackend == api.BackupStorageBackendS3 {if err := downloadBackupFileFromCloud(ctx, s3Client, backup.Path, backupAbsPathLocal); err != nil {return nil, errors.Wrapf(err, "failed to download backup %q from S3", backup.Path)@@ -334,7 +335,7 @@ func (*PITRRestoreTaskExecutor) doRestoreInPlacePostgres(ctx context.Context, stif backup == nil {return nil, errors.Errorf("backup with ID %d not found", *payload.BackupID)}- backupFileName := getBackupAbsFilePath(profile.DataDir, backup.DatabaseID, backup.Name)+ backupFileName := backuprun.GetBackupAbsFilePath(profile.DataDir, backup.DatabaseID, backup.Name)backupFile, err := os.Open(backupFileName)if err != nil {return nil, errors.Wrapf(err, "failed to open backup file %q", backupFileName)diff --git a/server/task_executor_schema_baseline.go b/server/task_executor_schema_baseline.goindex 5209769a85..fb14acae6f 100644--- a/server/task_executor_schema_baseline.go+++ b/server/task_executor_schema_baseline.go@@ -15,11 +15,10 @@ import ()// NewSchemaBaselineTaskExecutor creates a schema baseline task executor.-func NewSchemaBaselineTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, rollbackRunner *RollbackRunner, activityManager *activity.Manager, profile config.Profile) TaskExecutor {+func NewSchemaBaselineTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, profile config.Profile) TaskExecutor {return &SchemaBaselineTaskExecutor{store: store,dbFactory: dbFactory,- rollbackRunner: rollbackRunner,activityManager: activityManager,profile: profile,}@@ -29,7 +28,6 @@ func NewSchemaBaselineTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFatype SchemaBaselineTaskExecutor struct {store *store.StoredbFactory *dbfactory.DBFactory- rollbackRunner *RollbackRunneractivityManager *activity.Managerprofile config.Profile}@@ -41,5 +39,5 @@ func (exec *SchemaBaselineTaskExecutor) RunOnce(ctx context.Context, task *api.Treturn true, nil, errors.Wrap(err, "invalid database schema baseline payload")}- return runMigration(ctx, exec.store, exec.dbFactory, exec.rollbackRunner, exec.activityManager, exec.profile, task, db.Baseline, payload.Statement, payload.SchemaVersion, nil /* vcsPushEvent */)+ return runMigration(ctx, exec.store, exec.dbFactory, exec.activityManager, exec.profile, task, db.Baseline, payload.Statement, payload.SchemaVersion, nil /* vcsPushEvent */)}diff --git a/server/task_executor_schema_update.go b/server/task_executor_schema_update.goindex 3d6a60e32e..4b98dc62c1 100644--- a/server/task_executor_schema_update.go+++ b/server/task_executor_schema_update.go@@ -15,11 +15,10 @@ import ()// NewSchemaUpdateTaskExecutor creates a schema update (DDL) task executor.-func NewSchemaUpdateTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, rollbackRunner *RollbackRunner, activityManager *activity.Manager, profile config.Profile) TaskExecutor {+func NewSchemaUpdateTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, profile config.Profile) TaskExecutor {return &SchemaUpdateTaskExecutor{store: store,dbFactory: dbFactory,- rollbackRunner: rollbackRunner,activityManager: activityManager,profile: profile,}@@ -29,7 +28,6 @@ func NewSchemaUpdateTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFacttype SchemaUpdateTaskExecutor struct {store *store.StoredbFactory *dbfactory.DBFactory- rollbackRunner *RollbackRunneractivityManager *activity.Managerprofile config.Profile}@@ -41,5 +39,5 @@ func (exec *SchemaUpdateTaskExecutor) RunOnce(ctx context.Context, task *api.Tasreturn true, nil, errors.Wrap(err, "invalid database schema update payload")}- return runMigration(ctx, exec.store, exec.dbFactory, exec.rollbackRunner, exec.activityManager, exec.profile, task, db.Migrate, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)+ return runMigration(ctx, exec.store, exec.dbFactory, exec.activityManager, exec.profile, task, db.Migrate, payload.Statement, payload.SchemaVersion, payload.VCSPushEvent)}diff --git a/server/task_executor_schema_update_sdl.go b/server/task_executor_schema_update_sdl.goindex 0a57260411..7a209b005b 100644--- a/server/task_executor_schema_update_sdl.go+++ b/server/task_executor_schema_update_sdl.go@@ -18,11 +18,10 @@ import ()// NewSchemaUpdateSDLTaskExecutor creates a schema update (SDL) task executor.-func NewSchemaUpdateSDLTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, rollbackRunner *RollbackRunner, activityManager *activity.Manager, profile config.Profile) TaskExecutor {+func NewSchemaUpdateSDLTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFactory, activityManager *activity.Manager, profile config.Profile) TaskExecutor {return &SchemaUpdateSDLTaskExecutor{store: store,dbFactory: dbFactory,- rollbackRunner: rollbackRunner,activityManager: activityManager,profile: profile,}@@ -32,7 +31,6 @@ func NewSchemaUpdateSDLTaskExecutor(store *store.Store, dbFactory *dbfactory.DBFtype SchemaUpdateSDLTaskExecutor struct {store *store.StoredbFactory *dbfactory.DBFactory- rollbackRunner *RollbackRunneractivityManager *activity.Managerprofile config.Profile}@@ -48,7 +46,7 @@ func (exec *SchemaUpdateSDLTaskExecutor) RunOnce(ctx context.Context, task *api.if err != nil {return true, nil, errors.Wrap(err, "invalid database schema diff")}- return runMigration(ctx, exec.store, exec.dbFactory, exec.rollbackRunner, exec.activityManager, exec.profile, task, db.MigrateSDL, ddl, payload.SchemaVersion, payload.VCSPushEvent)+ return runMigration(ctx, exec.store, exec.dbFactory, exec.activityManager, exec.profile, task, db.MigrateSDL, ddl, payload.SchemaVersion, payload.VCSPushEvent)}// computeDatabaseSchemaDiff computes the diff between current database schemadiff --git a/server/task_scheduler.go b/server/task_scheduler.goindex 7b2fc9d70e..449ae9154f 100644--- a/server/task_scheduler.go+++ b/server/task_scheduler.go@@ -20,7 +20,9 @@ import ("github.com/bytebase/bytebase/plugin/db""github.com/bytebase/bytebase/server/component/activity""github.com/bytebase/bytebase/server/component/config"+ "github.com/bytebase/bytebase/server/runner/apprun""github.com/bytebase/bytebase/server/runner/schemasync"+ "github.com/bytebase/bytebase/server/utils""github.com/bytebase/bytebase/store")@@ -29,7 +31,7 @@ const ()// NewTaskScheduler creates a new task scheduler.-func NewTaskScheduler(server *Server, store *store.Store, applicationRunner *ApplicationRunner, schemaSyncer *schemasync.Syncer, activityManager *activity.Manager, licenseService enterpriseAPI.LicenseService, profile config.Profile) *TaskScheduler {+func NewTaskScheduler(server *Server, store *store.Store, applicationRunner *apprun.Runner, schemaSyncer *schemasync.Syncer, activityManager *activity.Manager, licenseService enterpriseAPI.LicenseService, profile config.Profile) *TaskScheduler {return &TaskScheduler{server: server,store: store,@@ -46,7 +48,7 @@ func NewTaskScheduler(server *Server, store *store.Store, applicationRunner *Apptype TaskScheduler struct {server *Serverstore *store.Store- applicationRunner *ApplicationRunner+ applicationRunner *apprun.RunnerschemaSyncer *schemasync.SynceractivityManager *activity.ManagerlicenseService enterpriseAPI.LicenseService@@ -264,7 +266,7 @@ func (s *TaskScheduler) Run(ctx context.Context, wg *sync.WaitGroup) {// The task has finished, and we may move to a new stage.// if the current assignee doesn't fit in the new assignee group, we will reassign a new one based on the new assignee group.if issue != nil {- if stage := getActiveStage(issue.Pipeline.StageList); stage != nil && stage.ID != taskPatched.StageID {+ if stage := utils.GetActiveStage(issue.Pipeline.StageList); stage != nil && stage.ID != taskPatched.StageID {environmentID := stage.EnvironmentIDok, err := s.canPrincipalBeAssignee(ctx, issue.AssigneeID, environmentID, issue.ProjectID, issue.Type)if err != nil {@@ -524,20 +526,9 @@ func (s *TaskScheduler) isTaskBlocked(ctx context.Context, task *api.Task) (boolreturn false, nil}-func getActiveStage(stageList []*api.Stage) *api.Stage {- for _, stage := range stageList {- for _, task := range stage.TaskList {- if task.Status != api.TaskDone {- return stage- }- }- }- return nil-}-// ScheduleActiveStage tries to schedule the tasks in the active stage.func (s *TaskScheduler) ScheduleActiveStage(ctx context.Context, pipeline *api.Pipeline) error {- stage := getActiveStage(pipeline.StageList)+ stage := utils.GetActiveStage(pipeline.StageList)if stage == nil {return nil}@@ -686,7 +677,7 @@ func (s *TaskScheduler) patchTaskStatus(ctx context.Context, task *api.Task, tas// every task in the stage completesif foundStage && stageTaskAllDone {// Cancel external approval, it's ok if we failed.- if err := s.applicationRunner.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonNoTaskPendingApproval); err != nil {+ if err := s.applicationRunner.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonNoTaskPendingApproval); err != nil {log.Error("failed to cancel external approval on stage tasks completion", zap.Int("issue_id", issue.ID), zap.Error(err))}@@ -996,7 +987,7 @@ func (s *TaskScheduler) changeIssueStatus(ctx context.Context, issue *api.Issue,// Cancel external approval, it's ok if we failed.if newStatus != api.IssueOpen {- if err := s.applicationRunner.CancelExternalApproval(ctx, issue.ID, externalApprovalCancelReasonIssueNotOpen); err != nil {+ if err := s.applicationRunner.CancelExternalApproval(ctx, issue.ID, api.ExternalApprovalCancelReasonIssueNotOpen); err != nil {log.Error("failed to cancel external approval on issue cancellation or completion", zap.Error(err))}}diff --git a/server/utils/utils.go b/server/utils/utils.goindex c9535f7515..601365dfc0 100644--- a/server/utils/utils.go+++ b/server/utils/utils.go@@ -186,3 +186,15 @@ func NewMigrationContext(config GhostConfig) (*base.MigrationContext, error) {}return migrationContext, nil}++// GetActiveStage returns an active stage among all stages.+func GetActiveStage(stageList []*api.Stage) *api.Stage {+ for _, stage := range stageList {+ for _, task := range stage.TaskList {+ if task.Status != api.TaskDone {+ return stage+ }+ }+ }+ return nil+}