/
runner.go
103 lines (83 loc) · 1.89 KB
/
runner.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package tychus
import (
"bytes"
"errors"
"io"
"os"
"os/exec"
"strings"
"syscall"
)
type runner struct {
args []string
cmd *exec.Cmd
errors chan error
stderr *bytes.Buffer
config *Configuration
}
func newRunner(c *Configuration, args []string) *runner {
return &runner{
args: args,
config: c,
errors: make(chan error),
}
}
func (r *runner) run() error {
r.kill()
if err := r.execute(); err != nil {
return err
}
if r.config.Wait {
return r.wait()
} else {
go r.wait()
}
return nil
}
func (r *runner) execute() error {
if r.cmd != nil && r.cmd.ProcessState != nil && r.cmd.ProcessState.Exited() {
return nil
}
r.stderr = &bytes.Buffer{}
mw := io.MultiWriter(r.stderr, os.Stderr)
r.cmd = exec.Command("/bin/sh", "-c", strings.Join(r.args, " "))
r.cmd.Stdout = os.Stdout
r.cmd.Stderr = mw
// Setup a process group so when this process gets stopped, so do any child
// process that it may spawn.
r.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if err := r.cmd.Start(); err != nil {
return errors.New(r.stderr.String())
}
return nil
}
// Wait for the command to finish. If the process exits with an error, only log
// it if it exit status is postive, as status code -1 is returned when the
// process was killed by runner#kill.
func (r *runner) wait() error {
err := r.cmd.Wait()
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
ws := exiterr.Sys().(syscall.WaitStatus)
if ws.ExitStatus() > 0 {
err = errors.New(r.stderr.String())
if r.config.Wait {
return err
} else {
r.errors <- err
}
}
}
}
return nil
}
// Kill the existing process & process group
func (r *runner) kill() {
if r.cmd != nil && r.cmd.Process != nil {
if pgid, err := syscall.Getpgid(r.cmd.Process.Pid); err == nil {
syscall.Kill(-pgid, syscall.SIGKILL)
}
syscall.Kill(-r.cmd.Process.Pid, syscall.SIGKILL)
r.cmd = nil
}
}