/
defaultExecute.go
306 lines (246 loc) · 9.04 KB
/
defaultExecute.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
package execute
import (
"context"
"fmt"
"io"
"os"
osexec "os/exec"
"strings"
"sync"
"github.com/apenella/go-ansible/v2/internal/executable/os/exec"
"github.com/apenella/go-ansible/v2/pkg/execute/result"
defaultresults "github.com/apenella/go-ansible/v2/pkg/execute/result/default"
"github.com/apenella/go-ansible/v2/pkg/execute/result/transformer"
errors "github.com/apenella/go-common-utils/error"
)
const (
// AnsiblePlaybookErrorCodeGeneralError is the error code for a general error
AnsiblePlaybookErrorCodeGeneralError = 1
// AnsiblePlaybookErrorCodeOneOrMoreHostFailed is the error code for a one or more host failed
AnsiblePlaybookErrorCodeOneOrMoreHostFailed = 2
// AnsiblePlaybookErrorCodeOneOrMoreHostUnreachable is the error code for a one or more host unreachable
AnsiblePlaybookErrorCodeOneOrMoreHostUnreachable = 3
// AnsiblePlaybookErrorCodeParserError is the error code for a parser error
AnsiblePlaybookErrorCodeParserError = 4
// AnsiblePlaybookErrorCodeBadOrIncompleteOptions is the error code for a bad or incomplete options
AnsiblePlaybookErrorCodeBadOrIncompleteOptions = 5
// AnsiblePlaybookErrorCodeUserInterruptedExecution is the error code for a user interrupted execution
AnsiblePlaybookErrorCodeUserInterruptedExecution = 99
// AnsiblePlaybookErrorCodeUnexpectedError is the error code for a unexpected error
AnsiblePlaybookErrorCodeUnexpectedError = 250
// AnsiblePlaybookErrorMessageGeneralError is the error message for a general error
AnsiblePlaybookErrorMessageGeneralError = "ansible-playbook error: general error"
// AnsiblePlaybookErrorMessageOneOrMoreHostFailed is the error message for a one or more host failed
AnsiblePlaybookErrorMessageOneOrMoreHostFailed = "ansible-playbook error: one or more host failed"
// AnsiblePlaybookErrorMessageOneOrMoreHostUnreachable is the error message for a one or more host unreachable
AnsiblePlaybookErrorMessageOneOrMoreHostUnreachable = "ansible-playbook error: one or more host unreachable"
// AnsiblePlaybookErrorMessageParserError is the error message for a parser error
AnsiblePlaybookErrorMessageParserError = "ansible-playbook error: parser error"
// AnsiblePlaybookErrorMessageBadOrIncompleteOptions is the error message for a bad or incomplete options
AnsiblePlaybookErrorMessageBadOrIncompleteOptions = "ansible-playbook error: bad or incomplete options"
// AnsiblePlaybookErrorMessageUserInterruptedExecution is the error message for a user interrupted execution
AnsiblePlaybookErrorMessageUserInterruptedExecution = "ansible-playbook error: user interrupted execution"
// AnsiblePlaybookErrorMessageUnexpectedError is the error message for a unexpected error
AnsiblePlaybookErrorMessageUnexpectedError = "ansible-playbook error: unexpected error"
)
// EnvVars represents a custom environment for an ansible playbook execution.
type EnvVars map[string]string
// Environ returns a copy of strings representing the custom environment, in the form "key=value".
func (e EnvVars) Environ() []string {
result := make([]string, 0, len(e))
for k, v := range e {
result = append(result, fmt.Sprintf("%s=%s", k, v))
}
return result
}
// DefaultExecute is a simple definition of an executor
type DefaultExecute struct {
// Cmd is the command generator
Cmd Commander
// CmdRunDir specifies the working directory of the command.
CmdRunDir string
// EnvVars specifies env vars of the command.
EnvVars EnvVars
// ErrContext is the error context
ErrorEnrich ErrorEnricher
// Exec is the executor
Exec Executabler
// Output manages the output of the command
Output result.ResultsOutputer
// quiet is a flag to set the executor in quiet mode
quiet bool
// Transformers is the list of transformers func for the output
Transformers []transformer.TransformerFunc
// Writer is where is written the command stdout
Write io.Writer
// WriterError is where is written the command stderr
WriterError io.Writer
}
// NewDefaultExecute return a new DefaultExecute instance with all options
func NewDefaultExecute(options ...ExecuteOptions) *DefaultExecute {
execute := &DefaultExecute{
EnvVars: make(map[string]string),
}
for _, opt := range options {
opt(execute)
}
return execute
}
// WithOutput sets the output mechanism to DefaultExecutor
func (e *DefaultExecute) WithOutput(output result.ResultsOutputer) {
e.Output = output
}
// AddEnvVar add the provided environment variable. It overwrites the variable when it already exists.
func (e *DefaultExecute) AddEnvVar(key, value string) {
if e.EnvVars == nil {
e.EnvVars = make(EnvVars)
}
e.EnvVars[key] = value
}
// AddEnvVarSafe add the provided environment variable. It returns an error when the variable already exists
func (e *DefaultExecute) AddEnvVarSafe(key, value string) error {
errContext := "execute::DefaultExecute:AddEnvVarSafe"
if e.EnvVars == nil {
e.EnvVars = make(EnvVars)
}
_, exists := e.EnvVars[key]
if exists {
return errors.New(errContext, fmt.Sprintf("Environment variable '%s' already exists", key))
}
e.EnvVars[key] = value
return nil
}
// Quiet sets the executor in quiet mode
func (e *DefaultExecute) Quiet() {
e.quiet = true
}
// quietCommand returns the command without the verbose flags -v, -vv, -vvv, -vvvv and --verbose
func (e *DefaultExecute) quietCommand() ([]string, error) {
errContext := "(execute::DefaultExecute:quietCommand)"
command, err := e.Cmd.Command()
if err != nil {
return nil, errors.New(errContext, "Error creating command", err)
}
quietCommand := make([]string, 0)
for _, cmd := range command {
if cmd == "-v" || cmd == "-vv" || cmd == "-vvv" || cmd == "-vvvv" || cmd == "--verbose" {
continue
}
quietCommand = append(quietCommand, cmd)
}
return quietCommand, nil
}
// Execute takes a command and args and runs it, streaming output to stdout
func (e *DefaultExecute) Execute(ctx context.Context) (err error) {
var errCmd error
var cmdStderr, cmdStdout io.ReadCloser
var wg sync.WaitGroup
errContext := "(execute::DefaultExecute::Execute)"
defer e.checkCompatibility()
execErrChan := make(chan error)
// default stdout and stderr for the main process
if e.Write == nil {
e.Write = os.Stdout
}
if e.WriterError == nil {
e.WriterError = os.Stderr
}
if e.Exec == nil {
e.Exec = exec.NewExec()
}
if e.Cmd == nil {
return errors.New(errContext, "Command is not defined")
}
command, err := e.Cmd.Command()
if err != nil {
return errors.New(errContext, "Error creating command", err)
}
if e.quiet {
command, err = e.quietCommand()
if err != nil {
return errors.New(errContext, "Error creating quiet command", err)
}
}
cmd := e.Exec.CommandContext(ctx, command[0], command[1:]...)
// Assert if cmd's type is the Golang's exec.Cmd as set the desired values for that case
_, isOsExecCmd := cmd.(*osexec.Cmd)
if isOsExecCmd {
if len(e.CmdRunDir) > 0 {
cmd.(*osexec.Cmd).Dir = e.CmdRunDir
}
if len(e.EnvVars) > 0 {
cmd.(*osexec.Cmd).Env = append(os.Environ(), e.EnvVars.Environ()...)
}
// connects the main process' stdin to ansible's stdin
cmd.(*osexec.Cmd).Stdin = os.Stdin
}
trans := make([]transformer.TransformerFunc, 0)
trans = append(trans, e.Transformers...)
cmdStdout, err = cmd.StdoutPipe()
defer func() {
_ = cmdStdout.Close()
}()
if err != nil {
return errors.New(errContext, "Error creating stdout pipe", err)
}
cmdStderr, err = cmd.StderrPipe()
defer func() {
_ = cmdStderr.Close()
}()
if err != nil {
return errors.New(errContext, "Error creating stderr pipe", err)
}
if e.Output == nil {
e.Output = defaultresults.NewDefaultResults(
defaultresults.WithTransformers(trans...),
)
}
err = cmd.Start()
if err != nil {
return errors.New(errContext, "Error starting command", err)
}
// Waig for stdout and stderr
wg.Add(2)
// stdout management
go func() {
defer close(execErrChan)
// when using the default results func DefaultStdoutCallbackResults,
// reads from ansible's stdout and writes to main process' stdout
e.Output.Print(ctx, cmdStdout, e.Write)
wg.Done()
execErrChan <- err
}()
// stderr management
go func() {
// show stderr messages using default stdout callback results
e.Output.Print(ctx, cmdStderr, e.WriterError)
wg.Done()
}()
wg.Wait()
if err := <-execErrChan; err != nil {
return errors.New(errContext, "Error managing results output", err)
}
err = cmd.Wait()
if err != nil {
if ctx.Err() != nil {
fmt.Fprintf(e.Write, "%s\n", fmt.Sprintf("\nWhoops! %s\n", ctx.Err()))
} else {
if e.ErrorEnrich != nil {
errCmd = e.ErrorEnrich.Enrich(err)
} else {
errCmd = err
}
errorMessage := fmt.Sprintf(" Command executed: %s\n", e.Cmd.String())
if len(e.EnvVars) > 0 {
errorMessage = fmt.Sprintf("%s\n Environment variables:\n%s\n", errorMessage, strings.Join(e.EnvVars.Environ(), "\n"))
}
stderrErrorMessage := string(err.(*osexec.ExitError).Stderr)
if len(stderrErrorMessage) > 0 {
errorMessage = fmt.Sprintf("%s\n'%s'\n", errorMessage, stderrErrorMessage)
}
return errors.New(errContext, fmt.Sprintf("Error during command execution.\n%s", errorMessage), errCmd)
}
}
return nil
}
func (e *DefaultExecute) checkCompatibility() {}