-
Notifications
You must be signed in to change notification settings - Fork 2
/
command.go
73 lines (61 loc) · 1.46 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
73
package main
import (
"bytes"
"os/exec"
"strconv"
"text/template"
"time"
sprig "github.com/Masterminds/sprig"
)
type command struct {
Cmd string `yaml:"cmd"`
After int `yaml:"after"`
Results []byte
Error error
RunTime int64
}
func (c *command) exec(commandType string, check *check) *command {
// reset the goods
c.Error, c.Results = nil, nil
c.RunTime = -1
// no need to go on really ...
if !c.okToExec() {
return c
}
// capture when the command started
started := time.Now().Unix()
// setup our template
template, templateError := template.New("cmdTemplate").Funcs(sprig.TxtFuncMap()).Parse(c.Cmd)
if templateError != nil {
c.Error = templateError
return c
}
// assign our template to a buffer for later
b := new(bytes.Buffer)
templateExecError := template.Execute(b, check)
if templateExecError != nil {
c.Error = templateExecError
return c
}
// alright, lets see what we get
cmd := exec.Command("sh", "-c", b.String())
c.Results, c.Error = cmd.CombinedOutput()
// calculate the runtime for the given command
c.RunTime = time.Now().Unix() - started
if c.Error == nil {
return c
}
// hmmm ... if we made it here, we error'd out
return c
}
func (c *command) id() string {
return c.Cmd + strconv.Itoa(c.After)
}
func (c *command) ok() bool {
return c.Error == nil
}
func (c *command) okToExec() bool {
// in case there are additional things we'd want to skip
// mute, maintenance mode, etc ...
return !(c.Cmd == "")
}