Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(backend): added timing task check to backend (#156)
Luke Zhou2baad1b01e77
diff --git a/api/task.go b/api/task.goindex 07631f8760..3281a36302 100644--- a/api/task.go+++ b/api/task.go@@ -128,10 +128,11 @@ type Task struct {TaskCheckRunList []*TaskCheckRun `jsonapi:"relation,taskCheckRun"`// Domain specific fields- Name string `jsonapi:"attr,name"`- Status TaskStatus `jsonapi:"attr,status"`- Type TaskType `jsonapi:"attr,type"`- Payload string `jsonapi:"attr,payload"`+ Name string `jsonapi:"attr,name"`+ Status TaskStatus `jsonapi:"attr,status"`+ Type TaskType `jsonapi:"attr,type"`+ Payload string `jsonapi:"attr,payload"`+ EarliestAllowedTs int64 `jsonapi:"attr,earliestAllowedTs"`}// TaskCreate is the API message for creating a task.@@ -151,8 +152,9 @@ type TaskCreate struct {Name string `jsonapi:"attr,name"`Status TaskStatus `jsonapi:"attr,status"`Type TaskType `jsonapi:"attr,type"`- // Payload is dirived from fields below it+ // Payload is derived from fields below itPayload string+ EarliestAllowedTs int64 `jsonapi:"attr,earliestAllowedTs"`Statement string `jsonapi:"attr,statement"`RollbackStatement string `jsonapi:"attr,rollbackStatement"`DatabaseName string `jsonapi:"attr,databaseName"`@@ -192,8 +194,9 @@ type TaskPatch struct {UpdaterID int// Domain specific fields- Statement *string `jsonapi:"attr,statement"`- Payload *string+ Statement *string `jsonapi:"attr,statement"`+ Payload *string+ EarliestAllowedTs *int64 `jsonapi:"attr,earliestAllowedTs"`}// TaskStatusPatch is the API message for patching a task status.diff --git a/api/task_check_run.go b/api/task_check_run.goindex 943db0ed4c..04f2cbf764 100644--- a/api/task_check_run.go+++ b/api/task_check_run.go@@ -77,8 +77,15 @@ const (TaskCheckDatabaseConnect TaskCheckType = "bb.task-check.database.connect"// TaskCheckInstanceMigrationSchema is the task check type for migrating schemas.TaskCheckInstanceMigrationSchema TaskCheckType = "bb.task-check.instance.migration-schema"+ // TaskCheckGeneralEarliestAllowedTime is the task check type for earliest allowed time.+ TaskCheckGeneralEarliestAllowedTime TaskCheckType = "bb.task-check.general.earliest-allowed-time")+// TaskCheckEarliestAllowedTimePayload is the task check payload for earliest allowed time+type TaskCheckEarliestAllowedTimePayload struct {+ EarliestAllowedTs int64 `json:"earliestAllowedTs"`+}+// TaskCheckDatabaseStatementAdvisePayload is the task check payload for database statement advise.type TaskCheckDatabaseStatementAdvisePayload struct {Statement string `json:"statement,omitempty"`diff --git a/common/error.go b/common/error.goindex 2da64dda9d..c8a735ec94 100644--- a/common/error.go+++ b/common/error.go@@ -30,6 +30,9 @@ const (MigrationOutOfOrder Code = 203MigrationBaselineMissing Code = 204+ // 301 task error+ TaskTimingNotAllowed Code = 301+// 10001 advisor error codeCompatibilityDropDatabase Code = 10001CompatibilityRenameTable Code = 10002diff --git a/server/server.go b/server/server.goindex a2a2b1186e..140e97ad48 100644--- a/server/server.go+++ b/server/server.go@@ -160,6 +160,9 @@ func NewServer(logger *zap.Logger, version string, host string, port int, frontemigrationSchemaExecutor := NewTaskCheckMigrationSchemaExecutor(logger)taskCheckScheduler.Register(string(api.TaskCheckInstanceMigrationSchema), migrationSchemaExecutor)+ timingExecutor := NewTaskCheckTimingExecutor(logger)+ taskCheckScheduler.Register(string(api.TaskCheckGeneralEarliestAllowedTime), timingExecutor)+s.TaskCheckScheduler = taskCheckScheduler// Schema syncerdiff --git a/server/task_check_executor_timing.go b/server/task_check_executor_timing.gonew file mode 100644index 0000000000..0d05cbc6cc--- /dev/null+++ b/server/task_check_executor_timing.go@@ -0,0 +1,54 @@+package server++import (+ "context"+ "encoding/json"+ "fmt"+ "time"++ "github.com/bytebase/bytebase/api"+ "github.com/bytebase/bytebase/common"+ "go.uber.org/zap"+)++// NewTaskCheckTimingExecutor creates a task check timing executor.+func NewTaskCheckTimingExecutor(logger *zap.Logger) TaskCheckExecutor {+ return &TaskCheckTimingExecutor{+ l: logger,+ }+}++// TaskCheckTimingExecutor is the task check timing executor.+type TaskCheckTimingExecutor struct {+ l *zap.Logger+}++const dataFormat = "2006-01-02 15:04:05"++// Run will run the task check timing executor once.+func (exec *TaskCheckTimingExecutor) Run(ctx context.Context, server *Server, taskCheckRun *api.TaskCheckRun) (result []api.TaskCheckResult, err error) {+ payload := &api.TaskCheckEarliestAllowedTimePayload{}+ if err := json.Unmarshal([]byte(taskCheckRun.Payload), payload); err != nil {+ return []api.TaskCheckResult{}, common.Errorf(common.Invalid, fmt.Errorf("invalid check timing payload: %w", err))+ }++ if time.Now().Before(time.Unix(payload.EarliestAllowedTs, 0)) {+ return []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusError,+ Code: common.TaskTimingNotAllowed,+ Title: "Not ready to run",+ Content: fmt.Sprintf("Need to wait until the configured earliest running time: %s", time.Unix(payload.EarliestAllowedTs, 0).Format(dataFormat)),+ },+ }, nil+ }++ return []api.TaskCheckResult{+ {+ Status: api.TaskCheckStatusSuccess,+ Code: common.Ok,+ Title: "OK",+ Content: fmt.Sprintf("Passed the configured earliest running time: %s", time.Unix(payload.EarliestAllowedTs, 0).Format(dataFormat)),+ },+ }, nil+}diff --git a/server/task_check_scheduler.go b/server/task_check_scheduler.goindex edf385994d..8485637e7a 100644--- a/server/task_check_scheduler.go+++ b/server/task_check_scheduler.go@@ -177,8 +177,89 @@ func (s *TaskCheckScheduler) Register(taskType string, executor TaskCheckExecutos.executors[taskType] = executor}+// shouldScheduleTimingTaskCheck will return whether should we schedule a timing task check for current task+// the logic goes like the following:+// 1. there is no running timing task check+// 2(a). the earliestAllowedTs state has been altered since last check (either via new creation or patch).+// 2(b). the earliestAllowedTs has NOT been altered since last check, however the last check had failed && earliestAllowedTs has passed now.+// ONLY when {1 && (2.a || 2.b)} listed above or EXPLICITLY set the forceSchedule to TRUE would this function return true+func (s *TaskCheckScheduler) shouldScheduleTimingTaskCheck(ctx context.Context, task *api.Task, forceSchedule bool) (bool, error) {+ if forceSchedule {+ return true, nil+ }++ statusList := []api.TaskCheckRunStatus{api.TaskCheckRunDone, api.TaskCheckRunFailed, api.TaskCheckRunRunning}+ taskCheckType := api.TaskCheckGeneralEarliestAllowedTime+ taskCheckRunFind := &api.TaskCheckRunFind{+ TaskID: &task.ID,+ Type: &taskCheckType,+ StatusList: &statusList,+ Latest: true,+ }+ taskCheckRunList, err := s.server.TaskCheckRunService.FindTaskCheckRunList(ctx, taskCheckRunFind)+ if err != nil {+ return false, err+ }++ if len(taskCheckRunList) == 0 {+ return true, nil+ }++ if taskCheckRunList[0].Status == api.TaskCheckRunRunning {+ return false, nil+ }++ taskCheckPayload := &api.TaskCheckEarliestAllowedTimePayload{}+ if err := json.Unmarshal([]byte(taskCheckRunList[0].Payload), taskCheckPayload); err != nil {+ return false, err+ }++ if taskCheckPayload.EarliestAllowedTs != task.EarliestAllowedTs {+ return true, nil+ }++ if time.Now().After(time.Unix(task.EarliestAllowedTs, 0)) {+ checkResult := &api.TaskCheckRunResultPayload{}+ if err := json.Unmarshal([]byte(taskCheckRunList[0].Result), checkResult); err != nil {+ return false, err+ }+ if checkResult.ResultList[0].Status == api.TaskCheckStatusSuccess {+ return false, nil+ }+ return true, nil+ }++ return false, nil+}+// ScheduleCheckIfNeeded schedules a check if needed.func (s *TaskCheckScheduler) ScheduleCheckIfNeeded(ctx context.Context, task *api.Task, creatorID int, skipIfAlreadyTerminated bool) (*api.Task, error) {+ // the following block is for timing task check+ {+ // we only set skipIfAlreadyTerminated to false when user explicitly want to reschedule a taskCheck+ flag, err := s.shouldScheduleTimingTaskCheck(ctx, task, !skipIfAlreadyTerminated /* forceSchedule */)+ if err != nil {+ return nil, err+ }++ if flag {+ taskCheckPayload, err := json.Marshal(task)+ if err != nil {+ return nil, err+ }+ _, err = s.server.TaskCheckRunService.CreateTaskCheckRunIfNeeded(ctx, &api.TaskCheckRunCreate{+ CreatorID: creatorID,+ Payload: string(taskCheckPayload),+ TaskID: task.ID,+ Type: api.TaskCheckGeneralEarliestAllowedTime,+ SkipIfAlreadyTerminated: false,+ })+ if err != nil {+ return nil, err+ }+ }+ }+if task.Type == api.TaskDatabaseSchemaUpdate {taskPayload := &api.TaskDatabaseSchemaUpdatePayload{}if err := json.Unmarshal([]byte(task.Payload), taskPayload); err != nil {@@ -259,3 +340,48 @@ func (s *TaskCheckScheduler) ScheduleCheckIfNeeded(ctx context.Context, task *ap}return task, nil}++// Returns true only if there is NO warning and error. User can still manually run the task if there is warning.+// But this method is used for gating the automatic run, so we are more cautious here.+func (s *Server) passCheck(ctx context.Context, server *Server, task *api.Task, checkType api.TaskCheckType) (bool, error) {+ statusList := []api.TaskCheckRunStatus{api.TaskCheckRunDone, api.TaskCheckRunFailed}+ taskCheckRunFind := &api.TaskCheckRunFind{+ TaskID: &task.ID,+ Type: &checkType,+ StatusList: &statusList,+ Latest: true,+ }++ taskCheckRunList, err := server.TaskCheckRunService.FindTaskCheckRunList(ctx, taskCheckRunFind)+ if err != nil {+ return false, err+ }++ if len(taskCheckRunList) == 0 || taskCheckRunList[0].Status == api.TaskCheckRunFailed {+ server.l.Debug("Task is waiting for check to pass",+ zap.Int("task_id", task.ID),+ zap.String("task_name", task.Name),+ zap.String("task_type", string(task.Type)),+ zap.String("task_check_type", string(api.TaskCheckDatabaseConnect)),+ )+ return false, nil+ }++ checkResult := &api.TaskCheckRunResultPayload{}+ if err := json.Unmarshal([]byte(taskCheckRunList[0].Result), checkResult); err != nil {+ return false, err+ }+ for _, result := range checkResult.ResultList {+ if result.Status == api.TaskCheckStatusError || result.Status == api.TaskCheckStatusWarn {+ server.l.Debug("Task is waiting for check to pass",+ zap.Int("task_id", task.ID),+ zap.String("task_name", task.Name),+ zap.String("task_type", string(task.Type)),+ zap.String("task_check_type", string(api.TaskCheckDatabaseConnect)),+ )+ return false, nil+ }+ }++ return true, nil+}diff --git a/server/task_scheduler.go b/server/task_scheduler.goindex fd9eb4d1cd..5d3576aa1e 100644--- a/server/task_scheduler.go+++ b/server/task_scheduler.go@@ -233,9 +233,18 @@ func (s *TaskScheduler) Register(taskType string, executor TaskExecutor) {// ScheduleIfNeeded schedules the task if its required check does not contain error in the latest runfunc (s *TaskScheduler) ScheduleIfNeeded(ctx context.Context, task *api.Task) (*api.Task, error) {- // For now, only schema update task has required task check+ // timing task check+ pass, err := s.server.passCheck(ctx, s.server, task, api.TaskCheckGeneralEarliestAllowedTime)+ if err != nil {+ return nil, err+ }+ if !pass {+ return task, nil+ }++ // only schema update task has required task checkif task.Type == api.TaskDatabaseSchemaUpdate {- pass, err := passCheck(ctx, s.server, task, api.TaskCheckDatabaseConnect)+ pass, err := s.server.passCheck(ctx, s.server, task, api.TaskCheckDatabaseConnect)if err != nil {return nil, err}@@ -243,7 +252,7 @@ func (s *TaskScheduler) ScheduleIfNeeded(ctx context.Context, task *api.Task) (*return task, nil}- pass, err = passCheck(ctx, s.server, task, api.TaskCheckInstanceMigrationSchema)+ pass, err = s.server.passCheck(ctx, s.server, task, api.TaskCheckInstanceMigrationSchema)if err != nil {return nil, err}@@ -260,7 +269,7 @@ func (s *TaskScheduler) ScheduleIfNeeded(ctx context.Context, task *api.Task) (*}// For now we only supported MySQL dialect syntax and compatibility checkif instance.Engine == db.MySQL || instance.Engine == db.TiDB {- pass, err = passCheck(ctx, s.server, task, api.TaskCheckDatabaseStatementSyntax)+ pass, err = s.server.passCheck(ctx, s.server, task, api.TaskCheckDatabaseStatementSyntax)if err != nil {return nil, err}@@ -268,7 +277,7 @@ func (s *TaskScheduler) ScheduleIfNeeded(ctx context.Context, task *api.Task) (*return task, nil}- pass, err = passCheck(ctx, s.server, task, api.TaskCheckDatabaseStatementCompatibility)+ pass, err = s.server.passCheck(ctx, s.server, task, api.TaskCheckDatabaseStatementCompatibility)if err != nil {return nil, err}@@ -284,48 +293,3 @@ func (s *TaskScheduler) ScheduleIfNeeded(ctx context.Context, task *api.Task) (*return updatedTask, nil}--// Returns true only if there is NO warning and error. User can still manually run the task if there is warning.-// But this method is used for gating the automatic run, so we are more cautious here.-func passCheck(ctx context.Context, server *Server, task *api.Task, checkType api.TaskCheckType) (bool, error) {- statusList := []api.TaskCheckRunStatus{api.TaskCheckRunDone, api.TaskCheckRunFailed}- taskCheckRunFind := &api.TaskCheckRunFind{- TaskID: &task.ID,- Type: &checkType,- StatusList: &statusList,- Latest: true,- }-- taskCheckRunList, err := server.TaskCheckRunService.FindTaskCheckRunList(ctx, taskCheckRunFind)- if err != nil {- return false, err- }-- if len(taskCheckRunList) == 0 || taskCheckRunList[0].Status == api.TaskCheckRunFailed {- server.l.Debug("Task is waiting for check to pass",- zap.Int("task_id", task.ID),- zap.String("task_name", task.Name),- zap.String("task_type", string(task.Type)),- zap.String("task_check_type", string(api.TaskCheckDatabaseConnect)),- )- return false, nil- }-- checkResult := &api.TaskCheckRunResultPayload{}- if err := json.Unmarshal([]byte(taskCheckRunList[0].Result), checkResult); err != nil {- return false, err- }- for _, result := range checkResult.ResultList {- if result.Status == api.TaskCheckStatusError || result.Status == api.TaskCheckStatusWarn {- server.l.Debug("Task is waiting for check to pass",- zap.Int("task_id", task.ID),- zap.String("task_name", task.Name),- zap.String("task_type", string(task.Type)),- zap.String("task_check_type", string(api.TaskCheckDatabaseConnect)),- )- return false, nil- }- }-- return true, nil-}diff --git a/store/migration/10001__init_schema.sql b/store/migration/10001__init_schema.sqlindex b60b34b005..3d1cef2c16 100644--- a/store/migration/10001__init_schema.sql+++ b/store/migration/10001__init_schema.sql@@ -842,14 +842,14 @@ CREATE TABLE task (),`type` TEXT NOT NULL CHECK (`type` LIKE 'bb.task.%'),payload TEXT NOT NULL DEFAULT '',- `not_before_ts` BIGINT NOT NULL DEFAULT 0+ `earliest_allowed_ts` BIGINT NOT NULL DEFAULT 0);CREATE INDEX idx_task_pipeline_id_stage_id ON task(pipeline_id, stage_id);CREATE INDEX idx_task_status ON task(`status`);-CREATE INDEX idx_task_not_before_ts ON task(not_before_ts);+CREATE INDEX idx_task_earliest_allowed_ts ON task(earliest_allowed_ts);INSERT INTOsqlite_sequence (name, seq)diff --git a/store/task.go b/store/task.goindex 863fb409d2..b6cae3ee3d 100644--- a/store/task.go+++ b/store/task.go@@ -137,10 +137,11 @@ func (s *TaskService) createTask(ctx context.Context, tx *Tx, create *api.TaskCrname,`+"`status`,"+``+"`type`,"+`- payload+ payload,+ earliest_allowed_ts)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)- RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, `+"`status`, `type`, payload"+`+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, `+"`status`, `type`, payload, earliest_allowed_ts"+``,create.CreatorID,create.CreatorID,@@ -151,6 +152,7 @@ func (s *TaskService) createTask(ctx context.Context, tx *Tx, create *api.TaskCrcreate.Status,create.Type,create.Payload,+ create.EarliestAllowedTs,)} else {row, err = tx.QueryContext(ctx, `@@ -164,10 +166,11 @@ func (s *TaskService) createTask(ctx context.Context, tx *Tx, create *api.TaskCrname,`+"`status`,"+``+"`type`,"+`- payload+ payload,+ earliest_allowed_ts)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, `+"`status`, `type`, payload"+`+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, `+"`status`, `type`, payload, earliest_allowed_ts"+``,create.CreatorID,create.CreatorID,@@ -179,6 +182,7 @@ func (s *TaskService) createTask(ctx context.Context, tx *Tx, create *api.TaskCrcreate.Status,create.Type,create.Payload,+ create.EarliestAllowedTs,)}@@ -206,6 +210,7 @@ func (s *TaskService) createTask(ctx context.Context, tx *Tx, create *api.TaskCr&task.Status,&task.Type,&task.Payload,+ &task.EarliestAllowedTs,); err != nil {return nil, FormatError(err)}@@ -265,7 +270,8 @@ func (s *TaskService) findTaskList(ctx context.Context, tx *Tx, find *api.TaskFiname,`+"`status`,"+``+"`type`,"+`- payload+ payload,+ earliest_allowed_tsFROM taskWHERE `+strings.Join(where, " AND "),args...,@@ -293,6 +299,7 @@ func (s *TaskService) findTaskList(ctx context.Context, tx *Tx, find *api.TaskFi&task.Status,&task.Type,&task.Payload,+ &task.EarliestAllowedTs,); err != nil {return nil, FormatError(err)}@@ -328,6 +335,9 @@ func (s *TaskService) patchTask(ctx context.Context, tx *Tx, patch *api.TaskPatcif v := patch.Payload; v != nil {set, args = append(set, "payload = ?"), append(args, *v)}+ if v := patch.EarliestAllowedTs; v != nil {+ set, args = append(set, "earliest_allowed_ts = ?"), append(args, *v)+ }args = append(args, patch.ID)// Execute update query with RETURNING.@@ -335,7 +345,7 @@ func (s *TaskService) patchTask(ctx context.Context, tx *Tx, patch *api.TaskPatcUPDATE taskSET `+strings.Join(set, ", ")+`WHERE id = ?- RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, `+"`status`, `type`, payload"+`+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, `+"`status`, `type`, payload, earliest_allowed_ts"+``,args...,)@@ -360,6 +370,7 @@ func (s *TaskService) patchTask(ctx context.Context, tx *Tx, patch *api.TaskPatc&task.Status,&task.Type,&task.Payload,+ &task.EarliestAllowedTs,); err != nil {return nil, FormatError(err)}@@ -450,7 +461,7 @@ func (s *TaskService) patchTaskStatus(ctx context.Context, tx *Tx, patch *api.TaUPDATE taskSET `+strings.Join(set, ", ")+`WHERE id = ?- RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, `+"`status`, `type`, payload"+`+ RETURNING id, creator_id, created_ts, updater_id, updated_ts, pipeline_id, stage_id, instance_id, database_id, name, `+"`status`, `type`, payload, earliest_allowed_ts"+``,args...,)@@ -475,6 +486,7 @@ func (s *TaskService) patchTaskStatus(ctx context.Context, tx *Tx, patch *api.Ta&task.Status,&task.Type,&task.Payload,+ &task.EarliestAllowedTs,); err != nil {return nil, FormatError(err)}