Skip to content

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

Move task_run_service from scheduler to store package

天舟ad6c65dc5a8f
diff --git a/backend/api/task.go b/backend/api/task.go
index 3403d784be..24bd338198 100644
--- a/backend/api/task.go
+++ b/backend/api/task.go
@@ -69,10 +69,11 @@ type Task struct {
// Related fields
// Just returns PipelineId and StageId otherwise would cause circular dependency.
- PipelineId int `jsonapi:"attr,pipelineId"`
- StageId int `jsonapi:"attr,stageId"`
- DatabaseId int
- Database *Database `jsonapi:"relation,database"`
+ PipelineId int `jsonapi:"attr,pipelineId"`
+ StageId int `jsonapi:"attr,stageId"`
+ DatabaseId int
+ Database *Database `jsonapi:"relation,database"`
+ TaskRunList []*TaskRun `jsonapi:"relation,taskRun"`
// Domain specific fields
Name string `jsonapi:"attr,name"`
@@ -111,22 +112,6 @@ type TaskFind struct {
StageId *int
}
-type TaskPatch struct {
- ID int `jsonapi:"primary,taskPatch"`
-
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- UpdaterId int
- WorkspaceId int
-
- // Related fields
- PipelineId int
-
- // Domain specific fields
- // Status is only set manualy via TaskStatusPatch
- Status *TaskStatus `jsonapi:"attr,status"`
-}
-
type TaskStatusPatch struct {
ID int `jsonapi:"primary,taskStatusPatch"`
@@ -136,18 +121,18 @@ type TaskStatusPatch struct {
WorkspaceId int
// Related fields
- PipelineId int
+ TaskRunId *int
// Domain specific fields
- // This is the container containing the pipeline this task belongs.
- ContainerId *int `jsonapi:"attr,containerId"`
- Status *string `jsonapi:"attr,status"`
- Comment *string `jsonapi:"attr,comment"`
+ Status TaskStatus `jsonapi:"attr,status"`
+ // If set will also update the corresponding TaskRunStatus
+ TaskRunStatus *TaskRunStatus
+ Comment *string `jsonapi:"attr,comment"`
}
type TaskService interface {
CreateTask(ctx context.Context, create *TaskCreate) (*Task, error)
FindTaskList(ctx context.Context, find *TaskFind) ([]*Task, error)
FindTask(ctx context.Context, find *TaskFind) (*Task, error)
- PatchTask(ctx context.Context, patch *TaskPatch) (*Task, error)
+ PatchTaskStatus(ctx context.Context, patch *TaskStatusPatch) (*Task, error)
}
diff --git a/backend/api/task_run.go b/backend/api/task_run.go
new file mode 100644
index 0000000000..35c67b10f6
--- /dev/null
+++ b/backend/api/task_run.go
@@ -0,0 +1,90 @@
+package api
+
+import "context"
+
+type TaskRunStatus string
+
+const (
+ TaskRunUnknown TaskRunStatus = "UNKNOWN"
+ TaskRunPending TaskRunStatus = "PENDING"
+ TaskRunRunning TaskRunStatus = "RUNNING"
+ TaskRunDone TaskRunStatus = "DONE"
+ TaskRunFailed TaskRunStatus = "FAILED"
+ TaskRunCanceled TaskRunStatus = "CANCELED"
+)
+
+func (e TaskRunStatus) String() string {
+ switch e {
+ case TaskRunPending:
+ return "PENDING"
+ case TaskRunRunning:
+ return "RUNNING"
+ case TaskRunDone:
+ return "DONE"
+ case TaskRunFailed:
+ return "FAILED"
+ case TaskRunCanceled:
+ return "CANCELED"
+ }
+ return "UNKNOWN"
+}
+
+type TaskRun struct {
+ ID int
+
+ // Standard fields
+ CreatorId int
+ Creator *Principal `jsonapi:"attr,creator"`
+ CreatedTs int64 `jsonapi:"attr,createdTs"`
+ UpdaterId int
+ Updater *Principal `jsonapi:"attr,updater"`
+ UpdatedTs int64 `jsonapi:"attr,updatedTs"`
+ WorkspaceId int
+
+ // Related fields
+ TaskId int `jsonapi:"attr,taskId"`
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Status TaskRunStatus `jsonapi:"attr,status"`
+ Type TaskType `jsonapi:"attr,type"`
+ Payload []byte `jsonapi:"attr,payload"`
+}
+
+type TaskRunCreate struct {
+ // Standard fields
+ // Value is assigned from the jwt subject field passed by the client.
+ CreatorId int
+ WorkspaceId int
+
+ // Related fields
+ TaskId int
+
+ // Domain specific fields
+ Name string `jsonapi:"attr,name"`
+ Type TaskType `jsonapi:"attr,type"`
+ Payload []byte `jsonapi:"attr,payload"`
+}
+
+type TaskRunFind struct {
+ ID *int
+
+ // Related fields
+ TaskId *int
+
+ // Domain specific fields
+ Status *TaskRunStatus
+}
+
+type TaskRunStatusChange struct {
+ ID int
+
+ // Domain specific fields
+ Status TaskRunStatus
+}
+
+type TaskRunService interface {
+ CreateTaskRun(ctx context.Context, create *TaskRunCreate) (*TaskRun, error)
+ FindTaskRunList(ctx context.Context, find *TaskRunFind) ([]*TaskRun, error)
+ FindTaskRun(ctx context.Context, find *TaskRunFind) (*TaskRun, error)
+}
diff --git a/backend/cmd/echo/main.go b/backend/cmd/echo/main.go
index 4ecf194870..efb794c4f7 100644
--- a/backend/cmd/echo/main.go
+++ b/backend/cmd/echo/main.go
@@ -3,15 +3,12 @@ package main
import (
"context"
"fmt"
- "log"
"net/http"
"os"
"os/signal"
"time"
"github.com/bytebase/bytebase"
- "github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/scheduler"
"github.com/bytebase/bytebase/server"
"github.com/bytebase/bytebase/store"
)
@@ -20,8 +17,7 @@ import (
const DSN = "./data/bytebase_dev.db"
type Main struct {
- l *bytebase.Logger
- scheduler *scheduler.Scheduler
+ l *bytebase.Logger
server *server.Server
@@ -42,16 +38,7 @@ func (m *Main) Run() error {
m.db = db
- s := scheduler.NewScheduler(log.Default(), db.Db)
- sqlExecutor := scheduler.NewSqlExecutor(log.Default(), db.Db)
- s.Register(string(api.TaskDatabaseSchemaUpdate), sqlExecutor)
- m.scheduler = s
-
- if err := m.scheduler.Run(); err != nil {
- return err
- }
-
- server := server.NewServer(m.l, m.scheduler)
+ server := server.NewServer(m.l)
server.PrincipalService = store.NewPrincipalService(m.l, db)
server.MemberService = store.NewMemberService(m.l, db)
server.ProjectService = store.NewProjectService(m.l, db)
@@ -64,6 +51,7 @@ func (m *Main) Run() error {
server.PipelineService = store.NewPipelineService(m.l, db)
server.StageService = store.NewStageService(m.l, db)
server.TaskService = store.NewTaskService(m.l, db)
+ server.TaskRunService = store.NewTaskRunService(m.l, db)
server.ActivityService = store.NewActivityService(m.l, db)
server.BookmarkService = store.NewBookmarkService(m.l, db)
diff --git a/backend/scheduler/scheduler.go b/backend/scheduler/scheduler.go
deleted file mode 100644
index 43936b2262..0000000000
--- a/backend/scheduler/scheduler.go
+++ /dev/null
@@ -1,172 +0,0 @@
-package scheduler
-
-import (
- "context"
- "database/sql"
- "fmt"
- "log"
- "runtime"
- "time"
-)
-
-const (
- STACK_SIZE = 4 << 10 // 4 KB
- ALL_STACK = true
-
- INTERVAL = time.Duration(1) * time.Second
-)
-
-func NewScheduler(logger *log.Logger, db *sql.DB) *Scheduler {
- return &Scheduler{
- l: logger,
- executors: make(map[string]Executor),
- taskRunService: newTaskRunService(logger, db),
- }
-}
-
-type Scheduler struct {
- l *log.Logger
- executors map[string]Executor
-
- taskRunService TaskRunService
-}
-
-func (s *Scheduler) Run() error {
- go func() {
- for {
- time.Sleep(INTERVAL)
-
- func() {
- defer func() {
- if r := recover(); r != nil {
- err, ok := r.(error)
- if !ok {
- err = fmt.Errorf("%v", r)
- }
- stack := make([]byte, STACK_SIZE)
- length := runtime.Stack(stack, ALL_STACK)
- msg := fmt.Sprintf("[Scheduler PANIC RECOVER] %v %s\n", err, stack[:length])
-
- s.l.Println(msg)
- }
- }()
- status := TaskRunPending
- taskRunFind := &TaskRunFind{
- Status: &status,
- }
- list, err := s.taskRunService.FindTaskRunList(context.Background(), taskRunFind)
- if err != nil {
- s.l.Printf("Failed to retrieve pending tasks: %v\n", err)
- }
-
- for _, taskRun := range list {
- executor, ok := s.executors[taskRun.Type]
- if !ok {
- s.l.Printf("Unknown task type: %v. Skip.", taskRun.Type)
- continue
- }
-
- s.l.Printf("Try to change task '%v(%v)' to RUNNING.\n", taskRun.Name, taskRun.ID)
- if err := s.changeTaskRunStatus(taskRun.ID, TaskRunRunning); err != nil {
- s.l.Printf("Failed to change task: %v.\n", err)
- continue
- }
-
- done, err := executor.Run(context.Background(), *taskRun)
- if done {
- if err != nil {
- s.l.Printf("Task failed '%v(%v)': %v.\n", taskRun.Name, taskRun.ID, err)
- if err := s.changeTaskRunStatus(taskRun.ID, TaskRunFailed); err != nil {
- s.l.Printf("Failed to change task: %v.\n", err)
- }
- continue
- }
- s.l.Printf("Task completed '%v(%v)'.\n", taskRun.Name, taskRun.ID)
- if err := s.changeTaskRunStatus(taskRun.ID, TaskRunDone); err != nil {
- s.l.Printf("Failed to change task: %v.\n", err)
- }
- }
- }
- }()
- }
- }()
-
- return nil
-}
-
-func (s *Scheduler) Register(taskType string, executor Executor) {
- if executor == nil {
- panic("scheduler: Register executor is nil for task type: " + taskType)
- }
- if _, dup := s.executors[taskType]; dup {
- panic("scheduler: Register called twice for task type: " + taskType)
- }
- s.executors[taskType] = executor
-}
-
-func (s *Scheduler) Schedule(task Task) (*TaskRun, error) {
- taskRunCreate := &TaskRunCreate{
- TaskId: task.ID,
- Name: task.Name,
- Type: task.Type,
- Payload: task.Payload,
- }
- createdTaskRun, err := s.taskRunService.CreateTaskRun(context.Background(), taskRunCreate)
- if err != nil {
- return nil, fmt.Errorf("failed to create task: %w", err)
- }
-
- return createdTaskRun, nil
-}
-
-// func (s *Scheduler) CheckTaskRunStatus(taskRunId TaskRunId) (TaskRunStatus, error) {
-// taskRun, err := s.findTaskRun(context.Background(), taskRunId)
-// if err != nil {
-// return TaskRunUnknown, fmt.Errorf("failed to check task status %v: %w", taskRunId, err)
-// }
-
-// executor, ok := s.executors[taskRun.Type]
-// if !ok {
-// return TaskRunUnknown, fmt.Errorf("failed to check task status '%v(%v)': unknown task type: %v", taskRun.Name, taskRunId, taskRun.Type)
-// }
-
-// return executor.Status(taskRunId)
-// }
-
-// func (s *Scheduler) CancelTaskRun(taskRunId TaskRunId) error {
-// taskRun, err := s.findTaskRun(context.Background(), taskRunId)
-// if err != nil {
-// return fmt.Errorf("failed to cancel task status %v: %w", taskRunId, err)
-// }
-
-// executor, ok := s.executors[taskRun.Type]
-// if !ok {
-// return fmt.Errorf("failed to cancel task status '%v(%v)': unknown task type: %v", taskRun.Name, taskRunId, taskRun.Type)
-// }
-
-// return executor.Cancel(taskRunId)
-// }
-
-// func (s *Scheduler) findTaskRun(ctx context.Context, taskRunId TaskRunId) (*TaskRun, error) {
-// taskRunFind := &TaskRunFind{
-// ID: &taskRunId,
-// }
-// taskRun, err := s.taskRunService.FindTaskRun(ctx, taskRunFind)
-// if err != nil {
-// return nil, fmt.Errorf("failed to retrieve task %v: %w", taskRunId, err)
-// }
-
-// return taskRun, nil
-// }
-
-func (s *Scheduler) changeTaskRunStatus(taskRunId TaskRunId, newStatus TaskRunStatus) error {
- taskRunStatusPatch := &TaskRunStatusPatch{
- ID: taskRunId,
- Status: newStatus,
- }
- _, err := s.taskRunService.PatchTaskRunStatus(context.Background(), taskRunStatusPatch)
- if err != nil {
- return fmt.Errorf("failed to change task %v status: %w", taskRunId, err)
- }
- return nil
-}
diff --git a/backend/scheduler/sql_executor.go b/backend/scheduler/sql_executor.go
deleted file mode 100644
index bba90f65fa..0000000000
--- a/backend/scheduler/sql_executor.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package scheduler
-
-import (
- "context"
- "database/sql"
- "encoding/json"
- "fmt"
- "log"
-
- "github.com/bytebase/bytebase/api"
-)
-
-func NewSqlExecutor(logger *log.Logger, db *sql.DB) Executor {
- return &SqlExecutor{
- l: logger,
- db: db,
- }
-}
-
-type SqlExecutor struct {
- l *log.Logger
- db *sql.DB
-}
-
-func (exec *SqlExecutor) Run(ctx context.Context, taskRun TaskRun) (terminated bool, err error) {
- payload := &api.TaskDatabaseSchemaUpdatePayload{}
- if err := json.Unmarshal(taskRun.Payload, payload); err != nil {
- return true, fmt.Errorf("sql executor: invalid payload: %w", err)
- }
-
- if payload.Sql == "" {
- return true, fmt.Errorf("sql executor: missing sql statement")
- }
-
- exec.l.Printf("sql executor: run %v", payload.Sql)
-
- tx, err := exec.db.BeginTx(ctx, nil)
- if err != nil {
- // Transient error
- return false, err
- }
- defer tx.Rollback()
-
- res, err := tx.ExecContext(ctx, payload.Sql)
- if err != nil {
- return true, err
- }
-
- rows, err := res.RowsAffected()
- if err != nil {
- // Transient error
- return false, err
- }
-
- exec.l.Printf("sql executor: rows affected %v", rows)
-
- return true, nil
-}
diff --git a/backend/scheduler/task.go b/backend/scheduler/task.go
deleted file mode 100644
index 8a90949b76..0000000000
--- a/backend/scheduler/task.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package scheduler
-
-import "context"
-
-type TaskId = int
-
-type TaskRunId = string
-
-type TaskRunStatus string
-
-const (
- TaskRunUnknown TaskRunStatus = "UNKNOWN"
- TaskRunPending TaskRunStatus = "PENDING"
- TaskRunRunning TaskRunStatus = "RUNNING"
- TaskRunDone TaskRunStatus = "DONE"
- TaskRunFailed TaskRunStatus = "FAILED"
- TaskRunCanceled TaskRunStatus = "CANCELED"
-)
-
-func (e TaskRunStatus) String() string {
- switch e {
- case TaskRunPending:
- return "PENDING"
- case TaskRunRunning:
- return "RUNNING"
- case TaskRunDone:
- return "DONE"
- case TaskRunFailed:
- return "FAILED"
- case TaskRunCanceled:
- return "CANCELED"
- }
- return "UNKNOWN"
-}
-
-type Task struct {
- ID TaskId
- Name string
- Type string
- Payload []byte
-}
-
-type TaskRun struct {
- ID TaskRunId
- CreatedTs int64
- UpdatedTs int64
- TaskId TaskId
- Name string
- Type string
- Status TaskRunStatus
- Payload []byte
-}
-
-type TaskRunCreate struct {
- TaskId TaskId
- Name string
- Type string
- Payload []byte
-}
-
-type TaskRunFind struct {
- ID *TaskRunId
- Status *TaskRunStatus
-}
-
-type TaskRunStatusPatch struct {
- ID TaskRunId
- Status TaskRunStatus
-}
-
-type TaskRunService interface {
- CreateTaskRun(ctx context.Context, create *TaskRunCreate) (*TaskRun, error)
- FindTaskRunList(ctx context.Context, find *TaskRunFind) ([]*TaskRun, error)
- FindTaskRun(ctx context.Context, find *TaskRunFind) (*TaskRun, error)
- PatchTaskRunStatus(ctx context.Context, patch *TaskRunStatusPatch) (*TaskRun, error)
-}
diff --git a/backend/server/issue.go b/backend/server/issue.go
index 74ef9db453..5315aaba49 100644
--- a/backend/server/issue.go
+++ b/backend/server/issue.go
@@ -9,7 +9,6 @@ import (
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/scheduler"
"github.com/google/jsonapi"
"github.com/labstack/echo/v4"
)
@@ -76,12 +75,7 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
for _, stage := range issue.Pipeline.StageList {
for _, task := range stage.TaskList {
- _, err := s.scheduler.Schedule(scheduler.Task{
- ID: task.ID,
- Name: task.Name,
- Type: string(task.Type),
- Payload: task.Payload,
- })
+ _, err := s.TaskScheduler.Schedule(*task)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to schedule task after creating the issue").SetInternal(err)
}
@@ -235,14 +229,13 @@ func (s *Server) registerIssueRoutes(g *echo.Group) {
for _, stage := range issue.Pipeline.StageList {
for _, task := range stage.TaskList {
if task.Status == api.TaskRunning {
- taskStatus := api.TaskCanceled
- taskPatch := &api.TaskPatch{
+ taskStatusPatch := &api.TaskStatusPatch{
ID: id,
WorkspaceId: api.DEFAULT_WORKPSACE_ID,
UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
- Status: &taskStatus,
+ Status: api.TaskCanceled,
}
- if _, err := s.TaskService.PatchTask(context.Background(), taskPatch); err != nil {
+ if _, err := s.TaskService.PatchTaskStatus(context.Background(), taskStatusPatch); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to cancel issue: %v. Failed to cancel task: %v.", issue.Name, task.Name)).SetInternal(err)
}
}
diff --git a/backend/server/server.go b/backend/server/server.go
index d5d632c6a8..800235bdab 100644
--- a/backend/server/server.go
+++ b/backend/server/server.go
@@ -5,13 +5,13 @@ import (
"embed"
"fmt"
"io/fs"
+ "log"
"net/http"
"strings"
"time"
"github.com/bytebase/bytebase"
"github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/scheduler"
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
"github.com/labstack/echo/v4"
@@ -20,8 +20,8 @@ import (
)
type Server struct {
- l *bytebase.Logger
- scheduler *scheduler.Scheduler
+ l *bytebase.Logger
+ TaskScheduler *TaskScheduler
PrincipalService api.PrincipalService
MemberService api.MemberService
@@ -35,6 +35,7 @@ type Server struct {
PipelineService api.PipelineService
StageService api.StageService
TaskService api.TaskService
+ TaskRunService api.TaskRunService
ActivityService api.ActivityService
BookmarkService api.BookmarkService
@@ -68,7 +69,7 @@ func getFileSystem() http.FileSystem {
return http.FS(fsys)
}
-func NewServer(logger *bytebase.Logger, scheduler *scheduler.Scheduler) *Server {
+func NewServer(logger *bytebase.Logger) *Server {
e := echo.New()
// Catch-all route to return index.html, this is to prevent 404 when accessing non-root url.
@@ -81,11 +82,15 @@ func NewServer(logger *bytebase.Logger, scheduler *scheduler.Scheduler) *Server
e.GET("/assets/*", echo.WrapHandler(assetHandler))
s := &Server{
- l: logger,
- scheduler: scheduler,
- e: e,
+ l: logger,
+ e: e,
}
+ scheduler := NewTaskScheduler(log.Default(), s)
+ sqlExecutor := NewSqlTaskExecutor(log.Default())
+ scheduler.Register(string(api.TaskDatabaseSchemaUpdate), sqlExecutor)
+ s.TaskScheduler = scheduler
+
g := e.Group("/api")
// Middleware
@@ -141,6 +146,10 @@ func NewServer(logger *bytebase.Logger, scheduler *scheduler.Scheduler) *Server
}
func (server *Server) Run() error {
+ if err := server.TaskScheduler.Run(); err != nil {
+ return err
+ }
+
const port int = 8080
// Sleep for 1 sec to make sure port is released between runs.
time.Sleep(time.Duration(1) * time.Second)
diff --git a/backend/server/task.go b/backend/server/task.go
index 0118b71fb7..cb36d745a9 100644
--- a/backend/server/task.go
+++ b/backend/server/task.go
@@ -14,11 +14,6 @@ import (
func (s *Server) registerTaskRoutes(g *echo.Group) {
g.PATCH("/pipeline/:pipelineId/task/:taskId/status", func(c echo.Context) error {
- pipelineId, err := strconv.Atoi(c.Param("pipelineId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Pipeline ID is not a number: %s", c.Param("pipelineId"))).SetInternal(err)
- }
-
taskId, err := strconv.Atoi(c.Param("taskId"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Task ID is not a number: %s", c.Param("taskId"))).SetInternal(err)
@@ -28,21 +23,12 @@ func (s *Server) registerTaskRoutes(g *echo.Group) {
ID: taskId,
WorkspaceId: api.DEFAULT_WORKPSACE_ID,
UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
- PipelineId: pipelineId,
}
if err := jsonapi.UnmarshalPayload(c.Request().Body, taskStatusPatch); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformatted update task status request").SetInternal(err)
}
- taskStatus := api.TaskStatus(*taskStatusPatch.Status)
- taskPatch := &api.TaskPatch{
- ID: taskId,
- WorkspaceId: api.DEFAULT_WORKPSACE_ID,
- UpdaterId: c.Get(GetPrincipalIdContextKey()).(int),
- PipelineId: pipelineId,
- Status: &taskStatus,
- }
- updatedTask, err := s.TaskService.PatchTask(context.Background(), taskPatch)
+ updatedTask, err := s.TaskService.PatchTaskStatus(context.Background(), taskStatusPatch)
if err != nil {
if bytebase.ErrorCode(err) == bytebase.ENOTFOUND {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Task ID not found: %d", taskId))
@@ -98,5 +84,44 @@ func (s *Server) ComposeTaskRelationship(ctx context.Context, task *api.Task, in
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch database for task: %v", task.Name)).SetInternal(err)
}
+ task.TaskRunList, err = s.ComposeTaskRunListByTaskId(context.Background(), task.ID, includeList)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch task run list for task: %v", task.Name)).SetInternal(err)
+ }
+
+ return nil
+}
+
+func (s *Server) ChangeTaskStatus(taskRun *api.TaskRun, newStatus api.TaskStatus) error {
+ newTaskRunStatus := api.TaskRunUnknown
+ switch newStatus {
+ case api.TaskPending:
+ newTaskRunStatus = api.TaskRunPending
+ case api.TaskRunning:
+ newTaskRunStatus = api.TaskRunRunning
+ case api.TaskDone:
+ newTaskRunStatus = api.TaskRunDone
+ case api.TaskFailed:
+ newTaskRunStatus = api.TaskRunFailed
+ case api.TaskCanceled:
+ newTaskRunStatus = api.TaskRunCanceled
+ case api.TaskSkipped:
+ newTaskRunStatus = api.TaskRunCanceled
+ }
+ taskStatusPatch := &api.TaskStatusPatch{
+ ID: taskRun.TaskId,
+ UpdaterId: taskRun.UpdaterId,
+ WorkspaceId: taskRun.WorkspaceId,
+ Status: newStatus,
+ }
+
+ if newTaskRunStatus != api.TaskRunUnknown {
+ taskStatusPatch.TaskRunId = &taskRun.ID
+ taskStatusPatch.TaskRunStatus = &newTaskRunStatus
+ }
+ _, err := s.TaskService.PatchTaskStatus(context.Background(), taskStatusPatch)
+ if err != nil {
+ return fmt.Errorf("failed to change task %v status: %w", taskRun.TaskId, err)
+ }
return nil
}
diff --git a/backend/scheduler/executor.go b/backend/server/task_executor.go
similarity index 57%
rename from backend/scheduler/executor.go
rename to backend/server/task_executor.go
index 232e2c9199..85aecc6054 100644
--- a/backend/scheduler/executor.go
+++ b/backend/server/task_executor.go
@@ -1,10 +1,14 @@
-package scheduler
+package server
-import "context"
+import (
+ "context"
-type Executor interface {
+ "github.com/bytebase/bytebase/api"
+)
+
+type TaskExecutor interface {
// Run will be called periodically by the scheduler until terminated is true.
// Note, it's possible that err could be non-nil while terminated is false, which
// usually indicates a transient error and will make scheduler retry later.
- Run(ctx context.Context, taskRun TaskRun) (terminated bool, err error)
+ Run(ctx context.Context, taskRun api.TaskRun) (terminated bool, err error)
}
diff --git a/backend/server/task_executor_sql.go b/backend/server/task_executor_sql.go
new file mode 100644
index 0000000000..b5d05d6afa
--- /dev/null
+++ b/backend/server/task_executor_sql.go
@@ -0,0 +1,55 @@
+package server
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+
+ "github.com/bytebase/bytebase/api"
+)
+
+func NewSqlTaskExecutor(logger *log.Logger) TaskExecutor {
+ return &SqlTaskExecutor{
+ l: logger,
+ }
+}
+
+type SqlTaskExecutor struct {
+ l *log.Logger
+}
+
+func (exec *SqlTaskExecutor) Run(ctx context.Context, taskRun api.TaskRun) (terminated bool, err error) {
+ payload := &api.TaskDatabaseSchemaUpdatePayload{}
+ if err := json.Unmarshal(taskRun.Payload, payload); err != nil {
+ return true, fmt.Errorf("sql executor: invalid payload: %w", err)
+ }
+
+ if payload.Sql == "" {
+ return true, fmt.Errorf("sql executor: missing sql statement")
+ }
+
+ exec.l.Printf("sql executor: run %v", payload.Sql)
+
+ // tx, err := exec.db.BeginTx(ctx, nil)
+ // if err != nil {
+ // // Transient error
+ // return false, err
+ // }
+ // defer tx.Rollback()
+
+ // res, err := tx.ExecContext(ctx, payload.Sql)
+ // if err != nil {
+ // return true, err
+ // }
+
+ // rows, err := res.RowsAffected()
+ // if err != nil {
+ // // Transient error
+ // return false, err
+ // }
+
+ // exec.l.Printf("sql executor: rows affected %v", rows)
+
+ return true, nil
+}
diff --git a/backend/server/task_run.go b/backend/server/task_run.go
new file mode 100644
index 0000000000..a78dca7e55
--- /dev/null
+++ b/backend/server/task_run.go
@@ -0,0 +1,43 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+
+ "github.com/bytebase/bytebase/api"
+ "github.com/labstack/echo/v4"
+)
+
+func (s *Server) ComposeTaskRunListByTaskId(ctx context.Context, taskId int, includeList []string) ([]*api.TaskRun, error) {
+ taskRunFind := &api.TaskRunFind{
+ TaskId: &taskId,
+ }
+ taskRunList, err := s.TaskRunService.FindTaskRunList(context.Background(), taskRunFind)
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch task run list for task ID: %v", taskId)).SetInternal(err)
+ }
+ for _, taskRun := range taskRunList {
+ if err := s.ComposeTaskRunRelationship(ctx, taskRun, includeList); err != nil {
+ return nil, err
+ }
+ }
+
+ return taskRunList, nil
+}
+
+func (s *Server) ComposeTaskRunRelationship(ctx context.Context, taskRun *api.TaskRun, includeList []string) error {
+ var err error
+
+ taskRun.Creator, err = s.ComposePrincipalById(context.Background(), taskRun.CreatorId, includeList)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch creator for taskRun: %v", taskRun.Name)).SetInternal(err)
+ }
+
+ taskRun.Updater, err = s.ComposePrincipalById(context.Background(), taskRun.UpdaterId, includeList)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updater for taskRun: %v", taskRun.Name)).SetInternal(err)
+ }
+
+ return nil
+}
diff --git a/backend/server/task_scheduler.go b/backend/server/task_scheduler.go
new file mode 100644
index 0000000000..1a2605fefd
--- /dev/null
+++ b/backend/server/task_scheduler.go
@@ -0,0 +1,119 @@
+package server
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "runtime"
+ "time"
+
+ "github.com/bytebase/bytebase/api"
+)
+
+const (
+ INTERVAL = time.Duration(1) * time.Second
+)
+
+func NewTaskScheduler(logger *log.Logger, server *Server) *TaskScheduler {
+ return &TaskScheduler{
+ l: logger,
+ executors: make(map[string]TaskExecutor),
+ server: server,
+ }
+}
+
+type TaskScheduler struct {
+ l *log.Logger
+ executors map[string]TaskExecutor
+
+ server *Server
+}
+
+func (s *TaskScheduler) Run() error {
+ go func() {
+ for {
+ time.Sleep(INTERVAL)
+
+ func() {
+ defer func() {
+ if r := recover(); r != nil {
+ err, ok := r.(error)
+ if !ok {
+ err = fmt.Errorf("%v", r)
+ }
+ stack := make([]byte, STACK_SIZE)
+ length := runtime.Stack(stack, ALL_STACK)
+ msg := fmt.Sprintf("[Scheduler PANIC RECOVER] %v %s\n", err, stack[:length])
+
+ s.l.Println(msg)
+ }
+ }()
+ status := api.TaskRunPending
+ taskRunFind := &api.TaskRunFind{
+ Status: &status,
+ }
+ list, err := s.server.TaskRunService.FindTaskRunList(context.Background(), taskRunFind)
+ if err != nil {
+ s.l.Printf("Failed to retrieve pending tasks: %v\n", err)
+ }
+
+ for _, taskRun := range list {
+ executor, ok := s.executors[string(taskRun.Type)]
+ if !ok {
+ s.l.Printf("Unknown task type: %v. Skip.", taskRun.Type)
+ continue
+ }
+
+ s.l.Printf("Try to change task '%v(%v)' to RUNNING.\n", taskRun.Name, taskRun.ID)
+ if err := s.server.ChangeTaskStatus(taskRun, api.TaskRunning); err != nil {
+ s.l.Printf("Failed to change task: %v.\n", err)
+ continue
+ }
+
+ done, err := executor.Run(context.Background(), *taskRun)
+ if done {
+ if err != nil {
+ s.l.Printf("Task failed '%v(%v)': %v.\n", taskRun.Name, taskRun.ID, err)
+ if err := s.server.ChangeTaskStatus(taskRun, api.TaskFailed); err != nil {
+ s.l.Printf("Failed to change task: %v.\n", err)
+ }
+ continue
+ }
+
+ s.l.Printf("Task completed '%v(%v)'.\n", taskRun.Name, taskRun.ID)
+ if err := s.server.ChangeTaskStatus(taskRun, api.TaskDone); err != nil {
+ s.l.Printf("Failed to change task: %v.\n", err)
+ }
+ }
+ }
+ }()
+ }
+ }()
+
+ return nil
+}
+
+func (s *TaskScheduler) Register(taskType string, executor TaskExecutor) {
+ if executor == nil {
+ panic("scheduler: Register executor is nil for task type: " + taskType)
+ }
+ if _, dup := s.executors[taskType]; dup {
+ panic("scheduler: Register called twice for task type: " + taskType)
+ }
+ s.executors[taskType] = executor
+}
+
+func (s *TaskScheduler) Schedule(task api.Task) (*api.TaskRun, error) {
+ taskRunCreate := &api.TaskRunCreate{
+ TaskId: task.ID,
+ Name: fmt.Sprintf("%s %d", task.Name, time.Now().Unix()),
+ Type: task.Type,
+ Payload: task.Payload,
+ }
+ createdTaskRun, err := s.server.TaskRunService.CreateTaskRun(context.Background(), taskRunCreate)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create task: %w", err)
+ }
+
+ return createdTaskRun, nil
+}
diff --git a/backend/store/migration/0001_init_schema.up.sql b/backend/store/migration/0001_init_schema.up.sql
index 023c08f65d..5813cb8c26 100644
--- a/backend/store/migration/0001_init_schema.up.sql
+++ b/backend/store/migration/0001_init_schema.up.sql
@@ -471,6 +471,7 @@ CREATE TABLE task (
'RUNNING',
'DONE',
'FAILED',
+ "CANCELED",
"SKIPPED"
)
),
@@ -513,7 +514,7 @@ CREATE TABLE task_run (
"CANCELED"
)
),
- `type` TEXT NOT NULL,
+ `type` TEXT NOT NULL CHECK (`type` LIKE 'bb.task.%'),
payload TEXT NOT NULL DEFAULT ''
);
diff --git a/backend/store/task.go b/backend/store/task.go
index 3087dd9415..c675b31899 100644
--- a/backend/store/task.go
+++ b/backend/store/task.go
@@ -81,16 +81,16 @@ func (s *TaskService) FindTask(ctx context.Context, find *api.TaskFind) (*api.Ta
return list[0], nil
}
-// PatchTask updates an existing task by ID.
+// PatchTaskStatus updates an existing task status and the correspondng task run status atomically.
// Returns ENOTFOUND if task does not exist.
-func (s *TaskService) PatchTask(ctx context.Context, patch *api.TaskPatch) (*api.Task, error) {
+func (s *TaskService) PatchTaskStatus(ctx context.Context, patch *api.TaskStatusPatch) (*api.Task, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, FormatError(err)
}
defer tx.Rollback()
- task, err := s.patchTask(ctx, tx, patch)
+ task, err := s.patchTaskStatus(ctx, tx, patch)
if err != nil {
return nil, FormatError(err)
}
@@ -235,21 +235,33 @@ func (s *TaskService) findTaskList(ctx context.Context, tx *Tx, find *api.TaskFi
}
// patchTask updates a task by ID. Returns the new state of the task after update.
-func (s *TaskService) patchTask(ctx context.Context, tx *Tx, patch *api.TaskPatch) (*api.Task, error) {
- // Build UPDATE clause.
- set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
- if v := patch.Status; v != nil {
- set, args = append(set, "`status` = ?"), append(args, api.TaskStatus(*v))
+func (s *TaskService) patchTaskStatus(ctx context.Context, tx *Tx, patch *api.TaskStatusPatch) (*api.Task, error) {
+ // Updates the corresponding task run if applicable.
+ // We update the task run first because updating task below returns row and it's a bit complicated to
+ // arrange code to prevent that opening row interfering with the task run update.
+ if patch.TaskRunId != nil && patch.TaskRunStatus != nil {
+ taskRunStatusPatch := &taskRunStatusPatch{
+ ID: patch.TaskRunId,
+ TaskId: &patch.ID,
+ Status: *patch.TaskRunStatus,
+ }
+
+ if err := patchTaskRunStatus(ctx, tx, taskRunStatusPatch); err != nil {
+ return nil, FormatError(err)
+ }
}
+ // Updates the task
+ // Build UPDATE clause.
+ set, args := []string{"updater_id = ?"}, []interface{}{patch.UpdaterId}
+ set, args = append(set, "`status` = ?"), append(args, patch.Status)
args = append(args, patch.ID)
- args = append(args, patch.PipelineId)
// Execute update query with RETURNING.
row, err := tx.QueryContext(ctx, `
UPDATE task
SET `+strings.Join(set, ", ")+`
- WHERE id = ? AND pipeline_id = ?
+ WHERE id = ?
RETURNING id, creator_id, created_ts, updater_id, updated_ts, workspace_id, pipeline_id, stage_id, database_id, name, `+"`status`, `type`, `when`, payload"+`
`,
args...,
@@ -285,3 +297,41 @@ func (s *TaskService) patchTask(ctx context.Context, tx *Tx, patch *api.TaskPatc
return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("task ID not found: %d", patch.ID)}
}
+
+type taskRunStatusPatch struct {
+ ID *int
+
+ // Related fields
+ TaskId *int
+
+ // Domain specific fields
+ Status api.TaskRunStatus
+}
+
+// patchTaskRun updates a taskRun by ID. Returns the new state of the taskRun after update.
+func patchTaskRunStatus(ctx context.Context, tx *Tx, patch *taskRunStatusPatch) error {
+ // Build UPDATE clause.
+ set, args := []string{}, []interface{}{}
+ set, args = append(set, "`status` = ?"), append(args, patch.Status)
+
+ // Build WHERE clause.
+ where := []string{"1 = 1"}
+ if v := patch.ID; v != nil {
+ where, args = append(where, "id = ?"), append(args, *v)
+ }
+ if v := patch.TaskId; v != nil {
+ where, args = append(where, "task_id = ?"), append(args, *v)
+ }
+
+ _, err := tx.ExecContext(ctx, `
+ UPDATE task_run
+ SET `+strings.Join(set, ", ")+`
+ WHERE `+strings.Join(where, " AND "),
+ args...,
+ )
+ if err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/backend/scheduler/default_task_run_service.go b/backend/store/task_run.go
similarity index 52%
rename from backend/scheduler/default_task_run_service.go
rename to backend/store/task_run.go
index c04c4cc822..f99038521b 100644
--- a/backend/scheduler/default_task_run_service.go
+++ b/backend/store/task_run.go
@@ -1,32 +1,31 @@
-package scheduler
+package store
import (
"context"
- "database/sql"
"fmt"
- "log"
"strings"
"github.com/bytebase/bytebase"
+ "github.com/bytebase/bytebase/api"
)
var (
- _ TaskRunService = (*DefaultTaskRunService)(nil)
+ _ api.TaskRunService = (*TaskRunService)(nil)
)
// TaskRunService represents a service for managing taskRun.
-type DefaultTaskRunService struct {
- l *log.Logger
- db *sql.DB
+type TaskRunService struct {
+ l *bytebase.Logger
+ db *DB
}
// newTaskRunService returns a new TaskRunService.
-func newTaskRunService(logger *log.Logger, db *sql.DB) *DefaultTaskRunService {
- return &DefaultTaskRunService{l: logger, db: db}
+func NewTaskRunService(logger *bytebase.Logger, db *DB) *TaskRunService {
+ return &TaskRunService{l: logger, db: db}
}
// CreateTaskRun creates a new taskRun.
-func (s *DefaultTaskRunService) CreateTaskRun(ctx context.Context, create *TaskRunCreate) (*TaskRun, error) {
+func (s *TaskRunService) CreateTaskRun(ctx context.Context, create *api.TaskRunCreate) (*api.TaskRun, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
@@ -46,7 +45,7 @@ func (s *DefaultTaskRunService) CreateTaskRun(ctx context.Context, create *TaskR
}
// FindTaskRunList retrieves a list of taskRuns based on find.
-func (s *DefaultTaskRunService) FindTaskRunList(ctx context.Context, find *TaskRunFind) ([]*TaskRun, error) {
+func (s *TaskRunService) FindTaskRunList(ctx context.Context, find *api.TaskRunFind) ([]*api.TaskRun, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
@@ -55,7 +54,7 @@ func (s *DefaultTaskRunService) FindTaskRunList(ctx context.Context, find *TaskR
list, err := findTaskRunList(ctx, tx, find)
if err != nil {
- return []*TaskRun{}, err
+ return []*api.TaskRun{}, err
}
return list, nil
@@ -64,7 +63,7 @@ func (s *DefaultTaskRunService) FindTaskRunList(ctx context.Context, find *TaskR
// FindTaskRun retrieves a single taskRun based on find.
// Returns ENOTFOUND if no matching record.
// Returns the first matching one and prints a warning if finding more than 1 matching records.
-func (s *DefaultTaskRunService) FindTaskRun(ctx context.Context, find *TaskRunFind) (*TaskRun, error) {
+func (s *TaskRunService) FindTaskRun(ctx context.Context, find *api.TaskRunFind) (*api.TaskRun, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
@@ -77,38 +76,13 @@ func (s *DefaultTaskRunService) FindTaskRun(ctx context.Context, find *TaskRunFi
} else if len(list) == 0 {
return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("task run not found: %v", find)}
} else if len(list) > 1 {
- s.l.Printf("found mulitple task runs: %d, expect 1\n", len(list))
+ s.l.Warnf("found mulitple task runs: %d, expect 1\n", len(list))
}
return list[0], nil
}
-// PatchTaskRunStatus updates an existing taskRun by ID.
-// Returns ENOTFOUND if taskRun does not exist.
-func (s *DefaultTaskRunService) PatchTaskRunStatus(ctx context.Context, patch *TaskRunStatusPatch) (*TaskRun, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, err
- }
- defer tx.Rollback()
-
- taskRunPatch := &taskRunPatch{
- ID: patch.ID,
- Status: &patch.Status,
- }
- taskRun, err := patchTaskRun(ctx, tx, taskRunPatch)
- if err != nil {
- return nil, err
- }
-
- if err := tx.Commit(); err != nil {
- return nil, err
- }
-
- return taskRun, nil
-}
-
// createTaskRun creates a new taskRun.
-func createTaskRun(ctx context.Context, tx *sql.Tx, create *TaskRunCreate) (*TaskRun, error) {
+func createTaskRun(ctx context.Context, tx *Tx, create *api.TaskRunCreate) (*api.TaskRun, error) {
row, err := tx.QueryContext(ctx, `
INSERT INTO task_run (
task_id,
@@ -132,7 +106,7 @@ func createTaskRun(ctx context.Context, tx *sql.Tx, create *TaskRunCreate) (*Tas
defer row.Close()
row.Next()
- var taskRun TaskRun
+ var taskRun api.TaskRun
if err := row.Scan(
&taskRun.ID,
&taskRun.CreatedTs,
@@ -149,7 +123,7 @@ func createTaskRun(ctx context.Context, tx *sql.Tx, create *TaskRunCreate) (*Tas
return &taskRun, nil
}
-func findTaskRunList(ctx context.Context, tx *sql.Tx, find *TaskRunFind) (_ []*TaskRun, err error) {
+func findTaskRunList(ctx context.Context, tx *Tx, find *api.TaskRunFind) (_ []*api.TaskRun, err error) {
// Build WHERE clause.
where, args := []string{"1 = 1"}, []interface{}{}
if v := find.ID; v != nil {
@@ -179,9 +153,9 @@ func findTaskRunList(ctx context.Context, tx *sql.Tx, find *TaskRunFind) (_ []*T
defer rows.Close()
// Iterate over result set and deserialize rows into list.
- list := make([]*TaskRun, 0)
+ list := make([]*api.TaskRun, 0)
for rows.Next() {
- var taskRun TaskRun
+ var taskRun api.TaskRun
if err := rows.Scan(
&taskRun.ID,
&taskRun.CreatedTs,
@@ -203,54 +177,3 @@ func findTaskRunList(ctx context.Context, tx *sql.Tx, find *TaskRunFind) (_ []*T
return list, nil
}
-
-type taskRunPatch struct {
- ID TaskRunId
-
- Status *TaskRunStatus
-}
-
-// patchTaskRun updates a taskRun by ID. Returns the new state of the taskRun after update.
-func patchTaskRun(ctx context.Context, tx *sql.Tx, patch *taskRunPatch) (*TaskRun, error) {
- // Build UPDATE clause.
- set, args := []string{}, []interface{}{}
- if v := patch.Status; v != nil {
- set, args = append(set, "`status` = ?"), append(args, TaskRunStatus(*v))
- }
-
- args = append(args, patch.ID)
-
- // Execute update query with RETURNING.
- row, err := tx.QueryContext(ctx, `
- UPDATE task_run
- SET `+strings.Join(set, ", ")+`
- WHERE id = ?
- RETURNING id, created_ts, updated_ts, task_id, name, `+"`status`, `type`, payload"+`
- `,
- args...,
- )
- if err != nil {
- return nil, err
- }
- defer row.Close()
-
- if row.Next() {
- var taskRun TaskRun
- if err := row.Scan(
- &taskRun.ID,
- &taskRun.CreatedTs,
- &taskRun.UpdatedTs,
- &taskRun.TaskId,
- &taskRun.Name,
- &taskRun.Status,
- &taskRun.Type,
- &taskRun.Payload,
- ); err != nil {
- return nil, err
- }
-
- return &taskRun, nil
- }
-
- return nil, &bytebase.Error{Code: bytebase.ENOTFOUND, Message: fmt.Sprintf("task run ID not found: %s", patch.ID)}
-}