/
command.go
67 lines (54 loc) · 1.34 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
package checkers
import (
"bytes"
"context"
"os/exec"
"strings"
"time"
"github.com/google/shlex"
"github.com/juju/errors"
log "github.com/sirupsen/logrus"
)
type CommandChecker struct {
commonChecker
Exec []string
}
func (cc *CommandChecker) StrCommand() string {
var buf bytes.Buffer
for _, v := range cc.Exec {
if strings.ContainsRune(v, ' ') {
buf.WriteRune('"')
buf.WriteString(v)
buf.WriteRune('"')
} else {
buf.WriteString(v)
}
buf.WriteRune(' ')
}
return strings.TrimSpace(buf.String())
}
func (cc *CommandChecker) Run(ctx context.Context, results chan<- *CheckResult) {
cmd := cc.StrCommand()
newCtx, cancel := context.WithTimeout(ctx, cc.Timeout)
defer cancel()
log.WithFields(log.Fields{
"command": cmd,
"timeout": cc.Timeout,
}).Debug("Run command")
result := CheckResult{Ok: true, Producer: "command: " + cmd}
if err := exec.CommandContext(newCtx, cc.Exec[0], cc.Exec[1:]...).Run(); err != nil {
result.Ok = false
result.Error = errors.Annotate(err, "Command "+cmd+" failed")
}
results <- &result
}
func NewCommandChecker(timeout time.Duration, command string) (Checker, error) {
parsedCommand, err := shlex.Split(command)
if err != nil {
return nil, errors.Trace(err)
}
return &CommandChecker{
commonChecker: commonChecker{Timeout: timeout},
Exec: parsedCommand,
}, nil
}