This repository has been archived by the owner on Dec 10, 2018. It is now read-only.
/
exec_cmd_runner.go
316 lines (249 loc) · 6.97 KB
/
exec_cmd_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package system
import (
"bytes"
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"time"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
const (
execProcessLogTag = "Cmd Runner"
execErrorMsgFmt = "Running command: '%s', stdout: '%s', stderr: '%s'"
execShortErrorMaxLines = 100
)
type ExecError struct {
Command string
StdOut string
StdErr string
}
func NewExecError(cmd, stdout, stderr string) ExecError {
return ExecError{
Command: cmd,
StdOut: stdout,
StdErr: stderr,
}
}
func (e ExecError) Error() string {
return fmt.Sprintf(execErrorMsgFmt, e.Command, e.StdOut, e.StdErr)
}
// ShortError returns an error message that has stdout/stderr truncated.
func (e ExecError) ShortError() string {
outStr := e.truncateStr(e.StdOut, execShortErrorMaxLines)
errStr := e.truncateStr(e.StdErr, execShortErrorMaxLines)
return fmt.Sprintf(execErrorMsgFmt, e.Command, outStr, errStr)
}
func (e ExecError) truncateStr(in string, maxLines int) string {
outLines := strings.Split(in, "\n")
if i := len(outLines); i > maxLines {
outLines = outLines[i-maxLines:]
}
return strings.Join(outLines, "\n")
}
type execProcess struct {
cmd *exec.Cmd
stdoutWriter *bytes.Buffer
stderrWriter *bytes.Buffer
pid int
logger boshlog.Logger
waitCh chan Result
}
func newExecProcess(cmd *exec.Cmd, logger boshlog.Logger) *execProcess {
return &execProcess{
cmd: cmd,
stdoutWriter: bytes.NewBufferString(""),
stderrWriter: bytes.NewBufferString(""),
logger: logger,
}
}
func (p *execProcess) Start() error {
if p.cmd.Stdout == nil {
p.cmd.Stdout = p.stdoutWriter
}
if p.cmd.Stderr == nil {
p.cmd.Stderr = p.stderrWriter
}
cmdString := strings.Join(p.cmd.Args, " ")
p.logger.Debug(execProcessLogTag, "Running command: %s", cmdString)
p.cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
err := p.cmd.Start()
if err != nil {
return bosherr.WrapErrorf(err, "Starting command %s", cmdString)
}
p.pid = p.cmd.Process.Pid
return nil
}
func (p *execProcess) Wait() <-chan Result {
if p.waitCh != nil {
panic("Wait() must be called only once")
}
// Use buffer=1 to allow goroutine below to finish
p.waitCh = make(chan Result, 1)
go func() {
p.waitCh <- p.wait()
}()
return p.waitCh
}
func (p execProcess) wait() Result {
// err will be non-nil if command exits with non-0 status
err := p.cmd.Wait()
stdout := string(p.stdoutWriter.Bytes())
p.logger.Debug(execProcessLogTag, "Stdout: %s", stdout)
stderr := string(p.stderrWriter.Bytes())
p.logger.Debug(execProcessLogTag, "Stderr: %s", stderr)
exitStatus := -1
waitStatus := p.cmd.ProcessState.Sys().(syscall.WaitStatus)
if waitStatus.Exited() {
exitStatus = waitStatus.ExitStatus()
} else if waitStatus.Signaled() {
exitStatus = 128 + int(waitStatus.Signal())
}
p.logger.Debug(execProcessLogTag, "Successful: %t (%d)", err == nil, exitStatus)
if err != nil {
cmdString := strings.Join(p.cmd.Args, " ")
err = bosherr.WrapComplexError(err, NewExecError(cmdString, stdout, stderr))
}
return Result{
Stdout: stdout,
Stderr: stderr,
ExitStatus: exitStatus,
Error: err,
}
}
// TerminateNicely can be called multiple times simultaneously from different goroutines
func (p *execProcess) TerminateNicely(killGracePeriod time.Duration) error {
// Make sure process is being waited on for process state reaping to occur
// as to avoid forcibly killing the process after killGracePeriod
if p.waitCh == nil {
panic("TerminateNicely() must be called after Wait()")
}
err := p.signalGroup(syscall.SIGTERM)
if err != nil {
return bosherr.WrapErrorf(err, "Sending SIGTERM to process group %d", p.pid)
}
terminatedCh := make(chan struct{})
stopCheckingTerminatedCh := make(chan struct{})
go func() {
for p.groupExists() {
select {
case <-time.After(500 * time.Millisecond):
// nothing to do
case <-stopCheckingTerminatedCh:
return
}
}
close(terminatedCh)
}()
select {
case <-terminatedCh:
// nothing to do
case <-time.After(killGracePeriod):
close(stopCheckingTerminatedCh)
err = p.signalGroup(syscall.SIGKILL)
if err != nil {
return bosherr.WrapErrorf(err, "Sending SIGKILL to process group %d", p.pid)
}
}
// It takes some time for the process to disappear
for i := 0; i < 20; i++ {
if !p.groupExists() {
return nil
}
time.Sleep(500 * time.Millisecond)
}
return bosherr.Errorf("Failed to kill process after grace timeout (PID %d)", p.pid)
}
// signalGroup does not return an error if the process group does not exist
func (p *execProcess) signalGroup(sig syscall.Signal) error {
err := syscall.Kill(-p.pid, sig)
if p.isGroupDoesNotExistError(err) {
return nil
}
return err
}
func (p *execProcess) groupExists() bool {
err := syscall.Kill(-p.pid, syscall.Signal(0))
if p.isGroupDoesNotExistError(err) {
return false
}
return true
}
func (p *execProcess) isGroupDoesNotExistError(err error) bool {
if err == syscall.ESRCH {
return true
}
if err == syscall.EPERM {
// On BSD process is owned by no user while waiting to be reaped
return true
}
return false
}
type execCmdRunner struct {
logger boshlog.Logger
}
func NewExecCmdRunner(logger boshlog.Logger) CmdRunner {
return execCmdRunner{logger}
}
func (r execCmdRunner) RunComplexCommand(cmd Command) (string, string, int, error) {
process := newExecProcess(r.buildComplexCommand(cmd), r.logger)
err := process.Start()
if err != nil {
return "", "", -1, err
}
result := <-process.Wait()
return result.Stdout, result.Stderr, result.ExitStatus, result.Error
}
func (r execCmdRunner) RunComplexCommandAsync(cmd Command) (Process, error) {
process := newExecProcess(r.buildComplexCommand(cmd), r.logger)
err := process.Start()
if err != nil {
return nil, err
}
return process, nil
}
func (r execCmdRunner) RunCommand(cmdName string, args ...string) (string, string, int, error) {
process := newExecProcess(exec.Command(cmdName, args...), r.logger)
err := process.Start()
if err != nil {
return "", "", -1, err
}
result := <-process.Wait()
return result.Stdout, result.Stderr, result.ExitStatus, result.Error
}
func (r execCmdRunner) RunCommandWithInput(input, cmdName string, args ...string) (string, string, int, error) {
cmd := Command{
Name: cmdName,
Args: args,
Stdin: strings.NewReader(input),
}
return r.RunComplexCommand(cmd)
}
func (r execCmdRunner) CommandExists(cmdName string) bool {
_, err := exec.LookPath(cmdName)
return err == nil
}
func (r execCmdRunner) buildComplexCommand(cmd Command) *exec.Cmd {
execCmd := exec.Command(cmd.Name, cmd.Args...)
if cmd.Stdin != nil {
execCmd.Stdin = cmd.Stdin
}
if cmd.Stdout != nil {
execCmd.Stdout = cmd.Stdout
}
if cmd.Stderr != nil {
execCmd.Stderr = cmd.Stderr
}
execCmd.Dir = cmd.WorkingDir
env := []string{}
if !cmd.UseIsolatedEnv {
env = os.Environ()
}
for name, value := range cmd.Env {
env = append(env, fmt.Sprintf("%s=%s", name, value))
}
execCmd.Env = env
return execCmd
}