[agent v0.3.5] 🐛 fix: exec timeout

This commit is contained in:
naiba 2021-01-29 10:40:57 +08:00
parent 67230ee4b8
commit e439747c09
3 changed files with 39 additions and 22 deletions

View File

@ -11,6 +11,7 @@ import (
"os" "os"
"os/exec" "os/exec"
"strings" "strings"
"syscall"
"time" "time"
"github.com/blang/semver" "github.com/blang/semver"
@ -232,30 +233,30 @@ func doTask(task *pb.Task) {
case model.TaskTypeCommand: case model.TaskTypeCommand:
startedAt := time.Now() startedAt := time.Now()
var cmd *exec.Cmd var cmd *exec.Cmd
var resChan chan string var endCh = make(chan struct{})
var errChan chan string timeout := time.NewTimer(time.Hour * 2)
timeout := time.NewTimer(time.Minute * 30)
if utils.IsWindows() { if utils.IsWindows() {
cmd = exec.Command("cmd", "/c", task.GetData()) cmd = exec.Command("cmd", "/c", task.GetData())
} else { } else {
cmd = exec.Command("sh", "-c", task.GetData()) cmd = exec.Command("sh", "-c", task.GetData())
} }
go func(resChan, errChan chan string) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
output, err := cmd.Output() go func() {
if err != nil { select {
errChan <- fmt.Sprintf("%s\n%s", string(output), err.Error()) case <-timeout.C:
return result.Data = "任务执行超时\n"
cmd.Process.Kill()
close(endCh)
case <-endCh:
} }
resChan <- string(output) }()
}(resChan, errChan) output, err := cmd.Output()
select { if err != nil {
case <-timeout.C: result.Data += fmt.Sprintf("%s\n%s", string(output), err.Error())
result.Data = "任务执行超时30分钟" } else {
case output := <-resChan: close(endCh)
result.Data = output result.Data = string(output)
result.Successful = true result.Successful = true
case errString := <-errChan:
result.Data = errString
} }
result.Delay = float32(time.Now().Sub(startedAt).Seconds()) result.Delay = float32(time.Now().Sub(startedAt).Seconds())
default: default:

View File

@ -3,8 +3,8 @@ set -x
ME=`whoami` ME=`whoami`
ping example.com -c3 && \ ping example.com -c20 && \
echo "==== $ME ====" && \ echo "==== $ME ====" && \
ping example.net -c3 && \ ping example.net -c20 && \
echo $1 && \ echo $1 && \
echo "==== done! ====" echo "==== done! ===="

View File

@ -8,6 +8,7 @@ import (
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
"syscall"
"time" "time"
"github.com/go-ping/ping" "github.com/go-ping/ping"
@ -85,7 +86,22 @@ func cmdExec() {
cmd = exec.Command("sh", "-c", execFrom+`/cmd/playground/example.sh hello && \ cmd = exec.Command("sh", "-c", execFrom+`/cmd/playground/example.sh hello && \
echo world!`) echo world!`)
} }
output, err := cmd.Output() cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
log.Println("output:", string(output)) var endCh = make(chan struct{})
log.Println("err:", err) go func() {
output, err := cmd.Output()
log.Println("output:", string(output))
log.Println("err:", err)
close(endCh)
}()
go func() {
time.Sleep(time.Second * 2)
fmt.Println("killed")
if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil {
panic(err)
}
}()
select {
case <-endCh:
}
} }