2020-07-15 01:40:56 +08:00
|
|
|
|
package worker
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2020-08-15 23:34:37 +08:00
|
|
|
|
"ferry/pkg/logger"
|
2020-07-15 01:40:56 +08:00
|
|
|
|
"os/exec"
|
|
|
|
|
"syscall"
|
|
|
|
|
|
|
|
|
|
"github.com/RichardKnop/machinery/v1/tasks"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var asyncTaskMap map[string]interface{}
|
|
|
|
|
|
|
|
|
|
func executeTaskBase(scriptPath string) {
|
|
|
|
|
command := exec.Command("/bin/bash", "-c", scriptPath) //初始化Cmd
|
|
|
|
|
err := command.Start() //运行脚本
|
|
|
|
|
if nil != err {
|
2020-08-15 23:34:37 +08:00
|
|
|
|
logger.Errorf("task exec failed,%v", err.Error())
|
2020-07-15 01:40:56 +08:00
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-15 23:34:37 +08:00
|
|
|
|
logger.Info("Process PID:", command.Process.Pid)
|
2020-07-15 01:40:56 +08:00
|
|
|
|
|
|
|
|
|
err = command.Wait() //等待执行完成
|
|
|
|
|
if nil != err {
|
2020-08-15 23:34:37 +08:00
|
|
|
|
logger.Errorf("task exec failed,%v", err.Error())
|
2020-07-15 01:40:56 +08:00
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-15 23:34:37 +08:00
|
|
|
|
logger.Info("ProcessState PID:", command.ProcessState.Pid())
|
|
|
|
|
logger.Info("Exit Code", command.ProcessState.Sys().(syscall.WaitStatus).ExitStatus())
|
2020-07-15 01:40:56 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ExecCommand 异步任务
|
|
|
|
|
func ExecCommand(classify string, scriptPath string) error {
|
|
|
|
|
if classify == "shell" {
|
2020-08-15 23:34:37 +08:00
|
|
|
|
logger.Info("start exec shell...", scriptPath)
|
2020-07-15 01:40:56 +08:00
|
|
|
|
executeTaskBase(scriptPath)
|
|
|
|
|
return nil
|
|
|
|
|
} else if classify == "python" {
|
2020-08-15 23:34:37 +08:00
|
|
|
|
logger.Info("start exec python...", scriptPath)
|
2020-07-15 01:40:56 +08:00
|
|
|
|
executeTaskBase(scriptPath)
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func SendTask(ctx context.Context, classify string, scriptPath string) {
|
|
|
|
|
args := make([]tasks.Arg, 0)
|
|
|
|
|
args = append(args, tasks.Arg{
|
|
|
|
|
Name: "classify",
|
|
|
|
|
Type: "string",
|
|
|
|
|
Value: classify,
|
|
|
|
|
})
|
|
|
|
|
args = append(args, tasks.Arg{
|
|
|
|
|
Name: "scriptPath",
|
|
|
|
|
Type: "string",
|
|
|
|
|
Value: scriptPath,
|
|
|
|
|
})
|
|
|
|
|
task, _ := tasks.NewSignature("ExecCommandTask", args)
|
|
|
|
|
task.RetryCount = 5
|
|
|
|
|
_, err := AsyncTaskCenter.SendTaskWithContext(ctx, task)
|
|
|
|
|
if err != nil {
|
2020-08-15 23:34:37 +08:00
|
|
|
|
logger.Error(err.Error())
|
2020-07-15 01:40:56 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func initAsyncTaskMap() {
|
|
|
|
|
asyncTaskMap = make(map[string]interface{})
|
|
|
|
|
asyncTaskMap["ExecCommandTask"] = ExecCommand
|
|
|
|
|
}
|