-
Notifications
You must be signed in to change notification settings - Fork 70
/
go_task_recipe_executor.go
227 lines (194 loc) · 6.04 KB
/
go_task_recipe_executor.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
package execution
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/imdario/mergo"
"github.com/go-task/task/v3"
taskargs "github.com/go-task/task/v3/args"
"github.com/go-task/task/v3/taskfile"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"github.com/newrelic/newrelic-cli/internal/install/types"
)
// GoTaskRecipeExecutor is an implementation of the recipeExecutor interface that
// uses the go-task module to execute the steps defined in each recipe.
type GoTaskRecipeExecutor struct {
Stderr io.Writer
Stdin io.Reader
Stdout io.Writer
Output *OutputParser
RecipeOutput []string
}
// NewGoTaskRecipeExecutor returns a new instance of GoTaskRecipeExecutor.
func NewGoTaskRecipeExecutor() *GoTaskRecipeExecutor {
return &GoTaskRecipeExecutor{
Stderr: os.Stderr,
Stdin: os.Stdin,
Stdout: os.Stdout,
Output: NewOutputParser(map[string]interface{}{}),
RecipeOutput: []string{},
}
}
func (re *GoTaskRecipeExecutor) ExecutePreInstall(ctx context.Context, r types.OpenInstallationRecipe, recipeVars types.RecipeVars) error {
return errors.New("not implemented")
}
func (re *GoTaskRecipeExecutor) Execute(ctx context.Context, r types.OpenInstallationRecipe, recipeVars types.RecipeVars) (retErr error) {
defer func() {
if r := recover(); r != nil {
switch x := r.(type) {
case string:
retErr = errors.New(x)
case error:
retErr = x
default:
retErr = errors.New("unknown panic")
}
}
}()
log.Debugf("executing recipe %s", r.Name)
// unmarshall task file & create/write to temp file
taskFile, err := createRecipeTempFile(r)
if err != nil {
return err
}
defer os.Remove(taskFile.Name())
// Create temp 'flags' file.
outputJSONFile, err := createOutputJSONFile(r, recipeVars)
if err != nil {
return err
}
outputJSONFile.Close()
defer os.Remove(outputJSONFile.Name())
silentInstall, _ := strconv.ParseBool(recipeVars["assumeYes"])
var stdoutCapture *LineCaptureBuffer
var stderrCapture *LineCaptureBuffer
if silentInstall {
stdoutCapture = NewLineCaptureBuffer(&bytes.Buffer{})
stderrCapture = NewLineCaptureBuffer(&bytes.Buffer{})
} else {
buffer := NewLineCaptureBuffer(re.Stdout)
stdoutCapture = buffer
stderrCapture = buffer
}
e := task.Executor{
Dir: os.TempDir(),
Entrypoint: filepath.Base(taskFile.Name()),
Stdin: re.Stdin,
Stdout: stdoutCapture,
Stderr: stderrCapture,
}
if err = e.Setup(); err != nil {
return fmt.Errorf("could not set up task executor: %s", err)
}
calls, globals := taskargs.ParseV3()
e.Taskfile.Vars.Merge(globals)
for k, val := range recipeVars {
e.Taskfile.Vars.Set(k, taskfile.Var{Static: val})
}
if err = e.Run(ctx, calls...); err != nil {
log.WithFields(log.Fields{
"err": err,
}).Debug("Task execution returned error")
// should contain both out and err
re.RecipeOutput = stdoutCapture.GetFullRecipeOutput()
re.setOutput(outputJSONFile.Name())
goTaskError := types.NewGoTaskGeneralError(err)
// go-task does not provide an error type to denote context cancelation
// Therefore we need to match inside the error message
if strings.Contains(err.Error(), "context canceled") {
return types.ErrInterrupt
}
// Recipe trigger a canceled event with specific exit code 130 used
if isExitStatusCode(130, err) {
return types.ErrInterrupt
}
// We return exit code 131 when a user attempts to
// install a recipe on an unsupported operating system.
if isExitStatusCode(131, err) {
return &types.UnsupportedOperatingSystemError{
Err: errors.New(stderrCapture.LastFullLine),
}
}
// Catchall error formatting for child process errors
if strings.Contains(err.Error(), "exit status") {
lastStderr := stderrCapture.LastFullLine
return types.NewNonZeroExitCode(goTaskError, lastStderr)
}
return goTaskError
}
re.setOutput(outputJSONFile.Name())
return nil
}
func createRecipeTempFile(r types.OpenInstallationRecipe) (*os.File, error) {
out := []byte(r.Install)
err := yaml.Unmarshal(out, &taskfile.Taskfile{})
if err != nil {
return nil, fmt.Errorf("could not unmarshal taskfile: %s", err)
}
taskFile, err := ioutil.TempFile("", r.Name)
if err != nil {
return nil, err
}
_, err = taskFile.Write(out)
if err != nil {
return nil, err
}
return taskFile, nil
}
func createOutputJSONFile(r types.OpenInstallationRecipe, recipeVars types.RecipeVars) (*os.File, error) {
outputJSONFile, err := ioutil.TempFile("", fmt.Sprintf("%s_out", r.Name))
if err != nil {
return nil, err
}
recipeVars["NR_CLI_OUTPUT"] = outputJSONFile.Name()
return outputJSONFile, nil
}
func (re *GoTaskRecipeExecutor) setOutput(outputFileName string) {
outputFile, err := os.Open(outputFileName)
if err != nil {
log.Debugf("error openning json output file %s", outputFileName)
return
}
defer outputFile.Close()
outputBytes, _ := ioutil.ReadAll(outputFile)
if len(outputBytes) > 0 {
var result map[string]interface{}
lines := strings.Split(string(outputBytes), "\n")
for _, line := range lines {
if json.Valid([]byte(line)) {
var jsonFromString map[string]interface{}
if err := json.Unmarshal([]byte(line), &jsonFromString); err == nil {
if mergoErr := mergo.Merge(&result, jsonFromString, mergo.WithOverride); mergoErr != nil {
log.Debugf("error while merging JSON output resuls, details:%s", mergoErr.Error())
}
} else {
log.Debugf("error while unmarshaling JSON output, details:%s", err.Error())
}
} else {
log.Debugf(fmt.Sprintf("Invalid JSON string found in output file, skipping: %v", line))
}
}
re.Output = NewOutputParser(result)
} else {
re.Output = NewOutputParser(map[string]interface{}{})
}
}
func (re *GoTaskRecipeExecutor) GetOutput() *OutputParser {
return re.Output
}
func (re *GoTaskRecipeExecutor) GetRecipeOutput() []string {
return re.RecipeOutput
}
func isExitStatusCode(exitCode int, err error) bool {
exitCodeString := fmt.Sprintf("exit status %d", exitCode)
return strings.Contains(err.Error(), exitCodeString)
}