81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
|
|
package api
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"devops/agent/tasks"
|
|||
|
|
"devops/server/apps/task"
|
|||
|
|
|
|||
|
|
restfulspec "github.com/emicklei/go-restful-openapi/v2"
|
|||
|
|
"github.com/emicklei/go-restful/v3"
|
|||
|
|
"github.com/google/uuid"
|
|||
|
|
"github.com/infraboard/mcube/v2/exception"
|
|||
|
|
"github.com/infraboard/mcube/v2/http/restful/response"
|
|||
|
|
"github.com/infraboard/mcube/v2/ioc"
|
|||
|
|
"github.com/infraboard/mcube/v2/ioc/config/gorestful"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
func init() {
|
|||
|
|
ioc.Api().Registry(&TaskApiHandler{})
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 一个API, 提供给外部调用的接口,来触发一个Task的执行
|
|||
|
|
// 参数 TaskSpec, 返回 Task
|
|||
|
|
type TaskApiHandler struct {
|
|||
|
|
ioc.ObjectImpl
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func (h *TaskApiHandler) Name() string {
|
|||
|
|
return "tasks"
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func (i *TaskApiHandler) Version() string {
|
|||
|
|
return "v1"
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
func (h *TaskApiHandler) Init() error {
|
|||
|
|
ws := gorestful.ObjectRouter(h)
|
|||
|
|
|
|||
|
|
// restfulspec "github.com/emicklei/go-restful-openapi/v2"
|
|||
|
|
// 这个库是 go-restful 的一个扩展库,用于生成 OpenAPI 规范的文档
|
|||
|
|
tags := []string{"Task管理"}
|
|||
|
|
ws.Route(ws.POST("").To(h.RunTask).
|
|||
|
|
Doc("运行任务").
|
|||
|
|
Metadata(restfulspec.KeyOpenAPITags, tags).
|
|||
|
|
Reads(task.TaskSpec{}).
|
|||
|
|
Writes(task.Task{}).
|
|||
|
|
Returns(200, "OK", task.Task{}))
|
|||
|
|
return nil
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// RunTask 处理运行任务的API请求
|
|||
|
|
// Body 参数是 TaskSpec, 返回 Task
|
|||
|
|
func (h *TaskApiHandler) RunTask(r *restful.Request, w *restful.Response) {
|
|||
|
|
// 解析请求参数,构造 TaskSpec
|
|||
|
|
req := &task.TaskSpec{}
|
|||
|
|
if err := r.ReadEntity(req); err != nil {
|
|||
|
|
// "github.com/infraboard/mcube/v2/http/restful/response"
|
|||
|
|
// Failed 封装的 GoRestful框架的 异常返回
|
|||
|
|
response.Failed(w, err)
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 补充TaskId
|
|||
|
|
if req.Id == "" {
|
|||
|
|
req.Id = uuid.NewString()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 找到对应的 TaskRunner, 这里我们通过 TaskSpec 中的 Name 字段来找到对应的 TaskRunner
|
|||
|
|
taskDebugRunner := tasks.GetTaskRunner(req.Name)
|
|||
|
|
if taskDebugRunner == nil {
|
|||
|
|
response.Failed(w, exception.NewInternalServerError("%s not found", req.Name))
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 处理请求
|
|||
|
|
taskResp, err := taskDebugRunner.Run(r.Request.Context(), req)
|
|||
|
|
if err != nil {
|
|||
|
|
response.Failed(w, err)
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
response.Success(w, taskResp)
|
|||
|
|
}
|