-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
command.go
72 lines (55 loc) · 1.54 KB
/
command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package executor
import (
"errors"
"fmt"
"os/exec"
"time"
"github.com/spf13/viper"
)
type CommandOutputWriter struct {
TimeoutSecond int
}
type CmdExecutionResult struct {
Stdout []byte
Stderr []byte
}
func (c *CommandOutputWriter) ExecFullOutput(command string) (outOk []byte, outErr []byte, err error) {
chResponse := make(chan CmdExecutionResult)
executor := viper.GetString("shell_executor")
if executor == "" {
executor = "/bin/bash"
}
cmd := exec.Command(executor, "-c", command)
go func(cnl chan CmdExecutionResult, cmd *exec.Cmd) {
out, err := cmd.CombinedOutput()
errOut := []byte("")
if err != nil {
errOut = []byte(err.Error())
}
cnl <- CmdExecutionResult{Stdout: out, Stderr: errOut}
}(chResponse, cmd)
if c.TimeoutSecond == 0 {
result := <-chResponse
outOk = result.Stdout
outErr = result.Stderr
return
}
select {
case result := <-chResponse:
outOk = result.Stdout
outErr = result.Stderr
cmd.Process.Kill()
case <-time.After(time.Second * time.Duration(c.TimeoutSecond)):
cmd.Process.Kill()
errMsg := "TIMEOUT: EXCEEDED -- Process killed"
err = errors.New(errMsg)
outErr = []byte(errMsg)
}
return
}
func (c *CommandOutputWriter) ExecHeadOutput(command string) (outOk []byte, outErr []byte, err error) {
return c.ExecFullOutput(fmt.Sprintf("%s | head", command))
}
func (c *CommandOutputWriter) ExecTailOutput(command string) (outOk []byte, outErr []byte, err error) {
return c.ExecFullOutput(fmt.Sprintf("%s | tail", command))
}