gocron/routers/task/task.go

274 lines
7.7 KiB
Go
Raw Normal View History

2017-04-07 01:13:36 +00:00
package task
2017-04-07 09:26:46 +00:00
import (
"gopkg.in/macaron.v1"
"github.com/ouqiang/gocron/models"
"github.com/ouqiang/gocron/modules/logger"
"github.com/ouqiang/gocron/modules/utils"
2017-04-13 09:35:59 +00:00
"github.com/ouqiang/gocron/service"
"strconv"
"github.com/jakecoffman/cron"
2017-04-23 06:11:53 +00:00
"github.com/Unknwon/paginater"
"fmt"
"html/template"
2017-04-30 22:02:49 +00:00
"github.com/ouqiang/gocron/routers/base"
2017-05-05 08:31:24 +00:00
"github.com/go-macaron/binding"
"strings"
2017-04-07 09:26:46 +00:00
)
2017-04-07 01:13:36 +00:00
type TaskForm struct {
Id int
2017-05-05 08:31:24 +00:00
Name string `binding:"Required;MaxSize(32)"`
Spec string `binding:"Required;MaxSize(64)"`
Protocol models.TaskProtocol `binding:"In(1,2,3)"`
2017-05-05 08:31:24 +00:00
Command string `binding:"Required;MaxSize(256)"`
2017-05-04 02:47:14 +00:00
Timeout int `binding:"Range(-1,86400)"`
Multi int8 `binding:"In(1,2)"`
RetryTimes int8
HostId int16
Remark string
2017-04-30 17:12:07 +00:00
NotifyStatus int8 `binding:In(1,2,3)`
NotifyType int8 `binding:In(1,2)`
NotifyReceiverId string
}
2017-05-05 08:31:24 +00:00
func (f TaskForm) Error(ctx *macaron.Context, errs binding.Errors) {
if len(errs) == 0 {
return
}
json := utils.JsonResponse{}
content := json.CommonFailure("表单验证失败, 请检测输入")
ctx.Resp.Write([]byte(content))
}
2017-04-23 06:11:53 +00:00
// 首页
func Index(ctx *macaron.Context) {
taskModel := new(models.Task)
2017-04-21 09:41:59 +00:00
queryParams := parseQueryParams(ctx)
2017-04-23 06:11:53 +00:00
total, err := taskModel.Total(queryParams)
if err != nil {
logger.Error(err)
}
2017-04-21 09:41:59 +00:00
tasks, err := taskModel.List(queryParams)
if err != nil {
logger.Error(err)
}
2017-04-23 06:11:53 +00:00
name, ok := queryParams["name"].(string)
var safeNameHTML = ""
if ok {
safeNameHTML = template.HTMLEscapeString(name)
}
PageParams := fmt.Sprintf("id=%d&host_id=%d&name=%s&protocol=%d&status=%d&page_size=%d",
queryParams["Id"], queryParams["HostId"], safeNameHTML, queryParams["Protocol"], queryParams["Status"], queryParams["PageSize"]);
queryParams["PageParams"] = template.URL(PageParams)
p := paginater.New(int(total), queryParams["PageSize"].(int), queryParams["Page"].(int), 5)
ctx.Data["Pagination"] = p
2017-04-21 09:41:59 +00:00
setHostsToTemplate(ctx)
ctx.Data["Params"] = queryParams
ctx.Data["Title"] = "任务列表"
ctx.Data["Tasks"] = tasks
ctx.HTML(200, "task/index")
}
2017-04-23 06:11:53 +00:00
// 新增页面
2017-04-07 01:13:36 +00:00
func Create(ctx *macaron.Context) {
2017-04-21 09:41:59 +00:00
setHostsToTemplate(ctx)
2017-04-17 10:04:30 +00:00
ctx.Data["Title"] = "添加任务"
ctx.HTML(200, "task/task_form")
}
2017-04-23 06:11:53 +00:00
// 编辑页面
2017-04-17 10:04:30 +00:00
func Edit(ctx *macaron.Context) {
id := ctx.ParamsInt(":id")
taskModel := new(models.Task)
task, err := taskModel.Detail(id)
2017-04-20 01:36:42 +00:00
if err != nil || task.Id != id {
2017-04-17 10:04:30 +00:00
logger.Errorf("编辑任务#获取任务详情失败#任务ID-%d#%s", id, err.Error())
ctx.Redirect("/task")
}
ctx.Data["Task"] = task
ctx.Data["Title"] = "编辑"
setHostsToTemplate(ctx)
2017-04-16 08:24:09 +00:00
ctx.HTML(200, "task/task_form")
2017-04-07 01:13:36 +00:00
}
// 保存任务
2017-04-07 09:26:46 +00:00
func Store(ctx *macaron.Context, form TaskForm) string {
2017-04-13 09:35:59 +00:00
json := utils.JsonResponse{}
2017-04-07 09:26:46 +00:00
taskModel := models.Task{}
2017-04-17 10:04:30 +00:00
var id int = form.Id
_, err := cron.Parse(form.Spec)
if err != nil {
return json.CommonFailure("crontab表达式解析失败", err)
}
2017-04-17 10:04:30 +00:00
nameExists, err := taskModel.NameExist(form.Name, form.Id)
2017-04-13 09:35:59 +00:00
if err != nil {
return json.CommonFailure(utils.FailureContent, err)
}
if nameExists {
return json.CommonFailure("任务名称已存在")
}
if form.Protocol == models.TaskSSH && form.HostId <= 0 {
return json.CommonFailure("请选择主机名")
}
if form.Protocol != models.TaskHTTP {
taskModel.HostId = form.HostId
} else {
taskModel.HostId = 0
}
2017-04-07 09:26:46 +00:00
taskModel.Name = form.Name
taskModel.Protocol = form.Protocol
taskModel.Command = form.Command
taskModel.Timeout = form.Timeout
taskModel.Remark = form.Remark
taskModel.Multi = form.Multi
taskModel.RetryTimes = form.RetryTimes
if taskModel.Multi != 1 {
taskModel.Multi = 0
}
2017-04-30 17:12:07 +00:00
taskModel.NotifyStatus = form.NotifyStatus - 1
taskModel.NotifyType = form.NotifyType - 1
taskModel.NotifyReceiverId = form.NotifyReceiverId
2017-04-13 09:35:59 +00:00
taskModel.Spec = form.Spec
2017-04-30 17:12:07 +00:00
if taskModel.NotifyStatus > 0 && taskModel.NotifyReceiverId == "" {
return json.CommonFailure("请至少选择一个接收者")
2017-04-30 17:12:07 +00:00
}
if taskModel.Protocol == models.TaskHTTP {
command := strings.ToLower(taskModel.Command)
if !strings.HasPrefix(command, "http://") && !strings.HasPrefix(command, "https://") {
return json.CommonFailure("请输入正确的URL地址")
}
if taskModel.Timeout == -1 {
return json.CommonFailure("HTTP任务不支持后台运行")
}
if taskModel.Timeout > 300 {
return json.CommonFailure("HTTP任务超时时间不能超过300秒")
}
}
if taskModel.RetryTimes > 10 || taskModel.RetryTimes < 0 {
2017-05-05 08:31:24 +00:00
return json.CommonFailure("任务重试次数取值0-10")
}
if taskModel.Protocol != models.TaskSSH {
taskModel.HostId = 0
}
2017-04-17 10:04:30 +00:00
if id == 0 {
id, err = taskModel.Create()
} else {
_, err = taskModel.UpdateBean(id)
2017-04-17 10:04:30 +00:00
}
2017-04-07 09:26:46 +00:00
if err != nil {
2017-04-13 09:35:59 +00:00
return json.CommonFailure("保存失败", err)
}
2017-04-07 09:26:46 +00:00
return json.Success("保存成功", nil)
}
// 删除任务
2017-04-13 09:35:59 +00:00
func Remove(ctx *macaron.Context) string {
2017-04-16 08:24:09 +00:00
id := ctx.ParamsInt(":id")
2017-04-13 09:35:59 +00:00
json := utils.JsonResponse{}
taskModel := new(models.Task)
2017-04-16 08:24:09 +00:00
_, err := taskModel.Delete(id)
2017-04-13 09:35:59 +00:00
if err != nil {
return json.CommonFailure(utils.FailureContent, err)
}
service.Cron.RemoveJob(strconv.Itoa(id))
return json.Success(utils.SuccessContent, nil)
}
// 激活任务
func Enable(ctx *macaron.Context) string {
return changeStatus(ctx, models.Enabled)
}
// 暂停任务
func Disable(ctx *macaron.Context) string {
return changeStatus(ctx, models.Disabled)
}
2017-04-21 05:36:45 +00:00
// 手动运行任务
func Run(ctx *macaron.Context) string {
id := ctx.ParamsInt(":id")
json := utils.JsonResponse{}
taskModel := new(models.Task)
task , err := taskModel.Detail(id)
if err != nil || task.Id <= 0 {
return json.CommonFailure("获取任务详情失败", err)
}
task.Spec = "手动运行"
serviceTask := new(service.Task)
serviceTask.Run(task)
return json.Success("任务已开始运行, 请到任务日志中查看结果", nil);
}
2017-04-13 09:35:59 +00:00
// 改变任务状态
func changeStatus(ctx *macaron.Context, status models.Status) string {
2017-04-16 08:24:09 +00:00
id := ctx.ParamsInt(":id")
2017-04-13 09:35:59 +00:00
json := utils.JsonResponse{}
taskModel := new(models.Task)
2017-04-16 08:24:09 +00:00
_, err := taskModel.Update(id, models.CommonMap{
2017-04-13 09:35:59 +00:00
"Status": status,
})
if err != nil {
return json.CommonFailure(utils.FailureContent, err)
}
if status == models.Enabled {
addTaskToTimer(id)
} else {
service.Cron.RemoveJob(strconv.Itoa(id))
}
return json.Success(utils.SuccessContent, nil)
}
// 添加任务到定时器
func addTaskToTimer(id int) {
taskModel := new(models.Task)
task, err := taskModel.Detail(id)
if err != nil {
logger.Error(err)
return
}
2017-04-13 09:35:59 +00:00
taskService := service.Task{}
taskService.Add(task)
2017-04-21 09:41:59 +00:00
}
// 解析查询参数
func parseQueryParams(ctx *macaron.Context) (models.CommonMap) {
var params models.CommonMap = models.CommonMap{}
params["Id"] = ctx.QueryInt("id")
2017-04-21 09:41:59 +00:00
params["HostId"] = ctx.QueryInt("host_id")
params["Name"] = ctx.QueryTrim("name")
params["Protocol"] = ctx.QueryInt("protocol")
2017-04-23 06:11:53 +00:00
status := ctx.QueryInt("status")
if status >=0 {
status -= 1
}
params["Status"] = status
2017-04-30 22:02:49 +00:00
base.ParsePageAndPageSize(ctx, params)
2017-04-21 09:41:59 +00:00
return params
}
func setHostsToTemplate(ctx *macaron.Context) {
hostModel := new(models.Host)
hosts, err := hostModel.List(models.CommonMap{})
2017-04-24 05:57:39 +00:00
if err != nil {
2017-04-21 09:41:59 +00:00
logger.Error(err)
}
ctx.Data["Hosts"] = hosts
}