forked from realvnc-labs/tacoscript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmdRunTask.go
More file actions
287 lines (233 loc) · 6.68 KB
/
cmdRunTask.go
File metadata and controls
287 lines (233 loc) · 6.68 KB
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
package tasks
import (
"bytes"
"context"
"fmt"
"strings"
"time"
exec2 "github.com/cloudradar-monitoring/tacoscript/exec"
"gopkg.in/yaml.v2"
"github.com/cloudradar-monitoring/tacoscript/utils"
"github.com/cloudradar-monitoring/tacoscript/conv"
"github.com/sirupsen/logrus"
)
type CmdRunTask struct {
TypeName string
Path string
NamedTask
WorkingDir string
User string
Shell string
Envs conv.KeyValues
MissingFilesCondition []string
Require []string
OnlyIf []string
Unless []string
// aborts task execution if one task fails
AbortOnError bool
}
type CmdRunTaskBuilder struct {
}
func (crtb CmdRunTaskBuilder) Build(typeName, path string, ctx interface{}) (Task, error) {
t := &CmdRunTask{
TypeName: typeName,
Path: path,
}
errs := utils.Errors{}
for _, item := range ctx.([]interface{}) {
row := item.(yaml.MapSlice)[0]
key := row.Key.(string)
val := row.Value
var err error
switch key {
case NameField:
t.Name = fmt.Sprint(val)
case CwdField:
t.WorkingDir = fmt.Sprint(val)
case UserField:
t.User = fmt.Sprint(val)
case ShellField:
t.Shell = fmt.Sprint(val)
case EnvField:
var envs conv.KeyValues
envs, err = conv.ConvertToKeyValues(val, path)
errs.Add(err)
t.Envs = envs
case CreatesField:
t.MissingFilesCondition, err = parseCreatesField(val, path)
errs.Add(err)
case NamesField:
var names []string
names, err = conv.ConvertToValues(val, path)
errs.Add(err)
t.Names = names
case RequireField:
t.Require, err = parseRequireField(val, path)
errs.Add(err)
case OnlyIf:
t.OnlyIf, err = parseOnlyIfField(val, path)
errs.Add(err)
case Unless:
t.Unless, err = parseUnlessField(val, path)
errs.Add(err)
case AbortOnErrorField:
t.AbortOnError = conv.ConvertToBool(val)
}
}
return t, errs.ToError()
}
func (crt *CmdRunTask) GetName() string {
return crt.TypeName
}
func (crt *CmdRunTask) GetRequirements() []string {
return crt.Require
}
func (crt *CmdRunTask) Validate() error {
errs := &utils.Errors{}
err1 := ValidateRequired(crt.Name, crt.Path+"."+NameField)
err2 := ValidateRequiredMany(crt.Names, crt.Path+"."+NamesField)
if err1 != nil && err2 != nil {
errs.Add(err1)
errs.Add(err2)
return errs.ToError()
}
return nil
}
func (crt *CmdRunTask) GetPath() string {
return crt.Path
}
func (crt *CmdRunTask) String() string {
return conv.ConvertSourceToJSONStrIfPossible(crt)
}
type CmdRunTaskExecutor struct {
Runner exec2.Runner
FsManager FsManager
}
func (crte *CmdRunTaskExecutor) Execute(ctx context.Context, task Task) ExecutionResult {
execRes := ExecutionResult{}
cmdRunTask, ok := task.(*CmdRunTask)
if !ok {
execRes.Err = fmt.Errorf("cannot convert task '%v' to CmdRunTask", task)
return execRes
}
execRes.Name = strings.Join(cmdRunTask.GetNames(), "; ")
var stdoutBuf, stderrBuf bytes.Buffer
execCtx := &exec2.Context{
Ctx: ctx,
StdoutWriter: &stdoutBuf,
StderrWriter: &stderrBuf,
WorkingDir: cmdRunTask.WorkingDir,
User: cmdRunTask.User,
Path: cmdRunTask.Path,
Envs: cmdRunTask.Envs,
Cmds: cmdRunTask.GetNames(),
Shell: cmdRunTask.Shell,
}
shouldNotBeExecutedReason, err := crte.shouldBeExecuted(execCtx, cmdRunTask)
if err != nil {
execRes.Err = err
return execRes
}
if shouldNotBeExecutedReason != "" {
execRes.IsSkipped = true
execRes.SkipReason = shouldNotBeExecutedReason
execRes.Comment = `Command "` + execRes.Name + `" did not run: ` + shouldNotBeExecutedReason
return execRes
}
start := time.Now()
err = crte.Runner.Run(execCtx)
execRes.Duration = time.Since(start)
if err != nil {
execRes.Err = err
}
logrus.Debugf("execution of %s has finished, took: %v", cmdRunTask.Name, execRes.Duration)
execRes.StdErr = stderrBuf.String()
execRes.StdOut = stdoutBuf.String()
execRes.Pid = execCtx.Pid
return execRes
}
func (crte *CmdRunTaskExecutor) checkOnlyIfs(ctx *exec2.Context, cmdRunTask *CmdRunTask) (isSuccess bool, err error) {
if len(cmdRunTask.OnlyIf) == 0 {
return true, nil
}
newCtx := ctx.Copy()
newCtx.Cmds = cmdRunTask.OnlyIf
err = crte.Runner.Run(&newCtx)
if err != nil {
runErr, isRunErr := err.(exec2.RunError)
if isRunErr {
logrus.Debugf("will skip %s since onlyif condition has failed: %v", cmdRunTask.Path, runErr)
return false, nil
}
return false, err
}
return true, nil
}
func (crte *CmdRunTaskExecutor) checkUnless(ctx *exec2.Context, cmdRunTask *CmdRunTask) (isExpectationSuccess bool, err error) {
if len(cmdRunTask.Unless) == 0 {
return true, nil
}
newCtx := ctx.Copy()
newCtx.Cmds = cmdRunTask.Unless
err = crte.Runner.Run(&newCtx)
if err != nil {
runErr, isRunErr := err.(exec2.RunError)
if isRunErr {
logrus.Infof("will continue cmd since at least one unless condition has failed: %v", runErr)
return true, nil
}
return false, err
}
logrus.Debugf("any unless condition didn't fail for task '%s'", cmdRunTask.Path)
return false, nil
}
func (crte *CmdRunTaskExecutor) shouldBeExecuted(ctx *exec2.Context, cmdRunTask *CmdRunTask) (skipExecutionReason string, err error) {
isExists, filename, err := crte.checkMissingFileCondition(cmdRunTask)
if err != nil {
return "", err
}
if isExists {
skipExecutionReason = fmt.Sprintf("file %s exists", filename)
logrus.Debugf(skipExecutionReason+", will skip the execution of %s", cmdRunTask.Path)
return skipExecutionReason, nil
}
isSuccess, err := crte.checkOnlyIfs(ctx, cmdRunTask)
if err != nil {
return "", err
}
if !isSuccess {
return onlyIfConditionFailedReason, nil
}
isExpectationSuccess, err := crte.checkUnless(ctx, cmdRunTask)
if err != nil {
return "", err
}
if !isExpectationSuccess {
skipExecutionReason = "unless condition is true"
logrus.Debugf(skipExecutionReason+", will skip %s", cmdRunTask.Path)
return skipExecutionReason, nil
}
logrus.Debugf("all execution conditions are met, will continue %s", cmdRunTask.Path)
return "", nil
}
func (crte *CmdRunTaskExecutor) checkMissingFileCondition(cmdRunTask *CmdRunTask) (isExists bool, filename string, err error) {
if len(cmdRunTask.MissingFilesCondition) == 0 {
return
}
for _, missingFileCondition := range cmdRunTask.MissingFilesCondition {
if missingFileCondition == "" {
continue
}
isExists, err = crte.FsManager.FileExists(missingFileCondition)
if err != nil {
err = fmt.Errorf("failed to check if file '%s' exists: %w", missingFileCondition, err)
return
}
if isExists {
logrus.Debugf("file '%s' exists", missingFileCondition)
return true, missingFileCondition, nil
}
logrus.Debugf("file '%s' doesn't exist", missingFileCondition)
}
return
}