forked from evergreen-ci/evergreen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec.go
236 lines (186 loc) · 6.46 KB
/
exec.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
package command
import (
"context"
"io"
"os"
"strconv"
"github.com/evergreen-ci/evergreen/model"
"github.com/evergreen-ci/evergreen/rest/client"
"github.com/evergreen-ci/evergreen/subprocess"
"github.com/evergreen-ci/evergreen/util"
"github.com/google/shlex"
"github.com/mitchellh/mapstructure"
"github.com/mongodb/grip"
"github.com/mongodb/grip/level"
"github.com/mongodb/grip/message"
"github.com/pkg/errors"
)
type subprocessExec struct {
Binary string `mapstructure:"binary"`
Args []string `mapstructure:"args"`
Env map[string]string `mapstructure:"env"`
Command string `mapstructure:"command"`
// Background, if set to true, prevents shell code/output from
// waiting for the script to complete and immediately returns
// to the caller
Background bool `mapstructure:"background"`
// Silent, if set to true, prevents shell code/output from being
// logged to the agent's task logs. This can be used to avoid
// exposing sensitive expansion parameters and keys.
Silent bool `mapstructure:"silent"`
// SystemLog if set will write the shell command's output to the system logs, instead of the
// task logs. This can be used to collect diagnostic data in the background of a running task.
SystemLog bool `mapstructure:"system_log"`
// WorkingDir is the working directory to start the shell in.
WorkingDir string `mapstructure:"working_dir"`
// IgnoreStandardOutput and IgnoreStandardError allow users to
// elect to ignore either standard out and/or standard output.
IgnoreStandardOutput bool `mapstructure:"ignore_standard_out"`
IgnoreStandardError bool `mapstructure:"ignore_standard_error"`
// RedirectStandardErrorToOutput allows you to capture
// standard error in the same stream as standard output. This
// improves the synchronization of these streams.
RedirectStandardErrorToOutput bool `mapstructure:"redirect_standard_error_to_output"`
// ContinueOnError determines whether or not a failed return code
// should cause the task to be marked as failed. Setting this to true
// allows following commands to execute even if this shell command fails.
ContinueOnError bool `mapstructure:"continue_on_err"`
base
}
func subprocessExecFactory() Command { return &subprocessExec{} }
func (c *subprocessExec) Name() string { return "subprocess.exec" }
func (c *subprocessExec) ParseParams(params map[string]interface{}) error {
err := mapstructure.Decode(params, c)
if err != nil {
return errors.Wrapf(err, "error decoding %s params", c.Name())
}
if c.Command != "" {
if c.Binary != "" || len(c.Args) > 0 {
return errors.New("must specify command as either arguments or a command string but not both")
}
args, err := shlex.Split(c.Command)
if err != nil || len(args) == 0 {
return errors.Wrap(err, "problem parsing shell command")
}
c.Binary = args[0]
if len(args) > 1 {
c.Args = args[1:]
}
}
if c.Silent {
c.IgnoreStandardError = true
c.IgnoreStandardOutput = true
}
if c.IgnoreStandardOutput && c.RedirectStandardErrorToOutput {
return errors.New("cannot ignore standard out, and redirect standard error to it")
}
if c.Env == nil {
c.Env = make(map[string]string)
}
return nil
}
func (c *subprocessExec) doExpansions(exp *util.Expansions) error {
var err error
catcher := grip.NewBasicCatcher()
c.WorkingDir, err = exp.ExpandString(c.WorkingDir)
catcher.Add(err)
c.Binary, err = exp.ExpandString(c.Binary)
catcher.Add(err)
for idx := range c.Args {
c.Args[idx], err = exp.ExpandString(c.Args[idx])
catcher.Add(err)
}
for k, v := range c.Env {
c.Env[k], err = exp.ExpandString(v)
catcher.Add(err)
}
return errors.Wrap(catcher.Resolve(), "problem expanding strings")
}
func (c *subprocessExec) getProc(taskID string, logger client.LoggerProducer) (subprocess.Command, func(), error) {
c.Env[subprocess.MarkerTaskID] = taskID
c.Env[subprocess.MarkerAgentPID] = strconv.Itoa(os.Getpid())
proc, err := subprocess.NewLocalExec(c.Binary, c.Args, c.Env, c.WorkingDir)
if err != nil {
return nil, nil, errors.Wrap(err, "problem constructing command wrapper")
}
var output io.WriteCloser
var error io.WriteCloser
opts := subprocess.OutputOptions{
SuppressOutput: c.IgnoreStandardOutput,
SuppressError: c.IgnoreStandardError,
SendOutputToError: c.RedirectStandardErrorToOutput,
}
if !opts.SuppressOutput {
if c.SystemLog {
output = logger.SystemWriter(level.Info)
} else {
output = logger.TaskWriter(level.Info)
}
opts.Output = output
}
if !opts.SuppressError {
if c.SystemLog {
error = logger.SystemWriter(level.Error)
} else {
error = logger.TaskWriter(level.Error)
}
opts.Error = error
}
closer := func() {
if output != nil {
_ = output.Close()
}
if error != nil {
_ = error.Close()
}
}
return proc, closer, proc.SetOutput(opts)
}
func (c *subprocessExec) Execute(ctx context.Context, comm client.Communicator, logger client.LoggerProducer, conf *model.TaskConfig) error {
var err error
if err = c.doExpansions(conf.Expansions); err != nil {
logger.Execution().Error("problem expanding command values")
return errors.WithStack(err)
}
c.WorkingDir, err = conf.GetWorkingDirectory(c.WorkingDir)
if err != nil {
logger.Execution().Warning(err.Error())
return errors.WithStack(err)
}
proc, closer, err := c.getProc(conf.Task.Id, logger)
if err != nil {
logger.Execution().Warning(err.Error())
return errors.WithStack(err)
}
defer closer()
grip.Info(proc)
err = errors.WithStack(c.runCommand(ctx, conf.Task.Id, proc, logger))
if ctx.Err() != nil {
logger.System().Debug("dumping running processes")
logger.System().Debug(message.CollectAllProcesses())
logger.Execution().Notice(err)
return errors.Errorf("%s aborted", c.Name())
}
return err
}
func (c *subprocessExec) runCommand(ctx context.Context, taskID string, proc subprocess.Command, logger client.LoggerProducer) error {
if c.Silent {
logger.Execution().Info("executing command in silent mode")
}
if err := proc.Start(ctx); err != nil {
return errors.Wrap(err, "problem starting background process")
}
pid := proc.GetPid()
subprocess.TrackProcess(taskID, pid, logger.System())
if c.Background {
logger.Execution().Infof("started background process with pid %d", pid)
return nil
}
logger.Execution().Debugf("started foreground process with pid %d, waiting for completion", pid)
err := errors.Wrapf(proc.Wait(), "command with pid %s encountered error", pid)
if c.ContinueOnError {
logger.Execution().Notice(err)
return nil
}
return err
}