-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathsynthexec.go
311 lines (268 loc) · 9.62 KB
/
synthexec.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
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package synthexec
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/elastic/beats/v7/heartbeat/monitors/jobs"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/libbeat/logp"
)
const debugSelector = "synthexec"
type StdSuiteFields struct {
Name string
Id string
Type string
IsInline bool
}
type FilterJourneyConfig struct {
Tags []string `config:"tags"`
Match string `config:"match"`
}
// SuiteJob will run a single journey by name from the given suite.
func SuiteJob(ctx context.Context, suitePath string, params common.MapStr, filterJourneys FilterJourneyConfig, fields StdSuiteFields, extraArgs ...string) (jobs.Job, error) {
// Run the command in the given suitePath, use '.' as the first arg since the command runs
// in the correct dir
cmdFactory, err := suiteCommandFactory(suitePath, extraArgs...)
if err != nil {
return nil, err
}
return startCmdJob(ctx, cmdFactory, nil, params, filterJourneys, fields), nil
}
func suiteCommandFactory(suitePath string, args ...string) (func() *exec.Cmd, error) {
npmRoot, err := getNpmRoot(suitePath)
if err != nil {
return nil, err
}
newCmd := func() *exec.Cmd {
bin := filepath.Join(npmRoot, "node_modules/.bin/elastic-synthetics")
// Always put the suite path first to prevent conflation with variadic args!
// See https://github.com/tj/commander.js/blob/master/docs/options-taking-varying-arguments.md
// Note, we don't use the -- approach because it's cleaner to always know we can add new options
// to the end.
cmd := exec.Command(bin, append([]string{suitePath}, args...)...)
cmd.Dir = npmRoot
return cmd
}
return newCmd, nil
}
// InlineJourneyJob returns a job that runs the given source as a single journey.
func InlineJourneyJob(ctx context.Context, script string, params common.MapStr, fields StdSuiteFields, extraArgs ...string) jobs.Job {
newCmd := func() *exec.Cmd {
return exec.Command("elastic-synthetics", append(extraArgs, "--inline")...)
}
return startCmdJob(ctx, newCmd, &script, params, FilterJourneyConfig{}, fields)
}
// startCmdJob adapts commands into a heartbeat job. This is a little awkward given that the command's output is
// available via a sequence of events in the multiplexer, while heartbeat jobs are tail recursive continuations.
// Here, we adapt one to the other, where each recursive job pulls another item off the chan until none are left.
func startCmdJob(ctx context.Context, newCmd func() *exec.Cmd, stdinStr *string, params common.MapStr, filterJourneys FilterJourneyConfig, fields StdSuiteFields) jobs.Job {
return func(event *beat.Event) ([]jobs.Job, error) {
mpx, err := runCmd(ctx, newCmd(), stdinStr, params, filterJourneys)
if err != nil {
return nil, err
}
senr := streamEnricher{}
return []jobs.Job{readResultsJob(ctx, mpx.SynthEvents(), senr.enrich, fields)}, nil
}
}
// readResultsJob adapts the output of an ExecMultiplexer into a Job, that uses continuations
// to read all output.
func readResultsJob(ctx context.Context, synthEvents <-chan *SynthEvent, enrich enricher, fields StdSuiteFields) jobs.Job {
return func(event *beat.Event) (conts []jobs.Job, err error) {
se := <-synthEvents
err = enrich(event, se, fields)
if se != nil {
return []jobs.Job{readResultsJob(ctx, synthEvents, enrich, fields)}, err
} else {
return nil, err
}
}
}
// runCmd runs the given command, piping stdinStr if present to the command's stdin, and supplying
// the params var as a CLI argument.
func runCmd(
ctx context.Context,
cmd *exec.Cmd,
stdinStr *string,
params common.MapStr,
filterJourneys FilterJourneyConfig,
) (mpx *ExecMultiplexer, err error) {
mpx = NewExecMultiplexer()
// Setup a pipe for JSON structured output
jsonReader, jsonWriter, err := os.Pipe()
if err != nil {
return nil, err
}
// Common args
cmd.Env = append(os.Environ(), "NODE_ENV=production")
cmd.Args = append(cmd.Args, "--rich-events")
if len(filterJourneys.Tags) > 0 {
cmd.Args = append(cmd.Args, "--tags", strings.Join(filterJourneys.Tags, " "))
}
if filterJourneys.Match != "" {
cmd.Args = append(cmd.Args, "--match", filterJourneys.Match)
}
// Variant of the command with no params, which could contain sensitive stuff
loggableCmd := exec.Command(cmd.Path, cmd.Args...)
if len(params) > 0 {
paramsBytes, _ := json.Marshal(params)
cmd.Args = append(cmd.Args, "--params", string(paramsBytes))
loggableCmd.Args = append(loggableCmd.Args, "--params", fmt.Sprintf("\"{%d hidden params}\"", len(params)))
}
// We need to pass both files in here otherwise we get a broken pipe, even
// though node only touches the writer
cmd.ExtraFiles = []*os.File{jsonWriter, jsonReader}
// Out fd is always 3 since it's the only FD passed into cmd.ExtraFiles
// see the docs for ExtraFiles in https://golang.org/pkg/os/exec/#Cmd
cmd.Args = append(cmd.Args, "--outfd", "3")
logp.Info("Running command: %s in directory: '%s'", loggableCmd.String(), cmd.Dir)
if stdinStr != nil {
logp.Debug(debugSelector, "Using stdin str %s", *stdinStr)
cmd.Stdin = strings.NewReader(*stdinStr)
}
wg := sync.WaitGroup{}
// Send stdout into the output
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("could not open stdout pipe: %w", err)
}
wg.Add(1)
go func() {
scanToSynthEvents(stdoutPipe, stdoutToSynthEvent, mpx.writeSynthEvent)
wg.Done()
}()
stderrPipe, err := cmd.StderrPipe()
if err != nil {
return nil, fmt.Errorf("could not open stderr pipe: %w", err)
}
wg.Add(1)
go func() {
scanToSynthEvents(stderrPipe, stderrToSynthEvent, mpx.writeSynthEvent)
wg.Done()
}()
// Send the test results into the output
wg.Add(1)
go func() {
scanToSynthEvents(jsonReader, jsonToSynthEvent, mpx.writeSynthEvent)
wg.Done()
}()
err = cmd.Start()
if err != nil {
logp.Warn("Could not start command %s: %s", cmd, err)
return nil, err
}
// Kill the process if the context ends
go func() {
<-ctx.Done()
cmd.Process.Kill()
}()
// Close mpx after the process is done and all events have been sent / consumed
go func() {
err := cmd.Wait()
jsonWriter.Close()
jsonReader.Close()
logp.Info("Command has completed(%d): %s", cmd.ProcessState.ExitCode(), loggableCmd.String())
if err != nil {
str := fmt.Sprintf("command exited with status %d: %s", cmd.ProcessState.ExitCode(), err)
mpx.writeSynthEvent(&SynthEvent{
Type: "cmd/status",
Error: &SynthError{Name: "cmdexit", Message: str},
TimestampEpochMicros: float64(time.Now().UnixMicro()),
})
logp.Warn("Error executing command '%s' (%d): %s", loggableCmd.String(), cmd.ProcessState.ExitCode(), err)
}
wg.Wait()
mpx.Close()
}()
return mpx, nil
}
// scanToSynthEvents takes a reader, a transform function, and a callback, and processes
// each scanned line via the reader before invoking it with the callback.
func scanToSynthEvents(rdr io.ReadCloser, transform func(bytes []byte, text string) (*SynthEvent, error), cb func(*SynthEvent)) error {
scanner := bufio.NewScanner(rdr)
buf := make([]byte, 1024*1024*2) // 2MiB initial buffer (images can be big!)
scanner.Buffer(buf, 1024*1024*40) // Max 50MiB Buffer
for scanner.Scan() {
se, err := transform(scanner.Bytes(), scanner.Text())
if err != nil {
logp.Warn("error parsing line: %s for line: %s", err, scanner.Text())
continue
}
if se != nil {
cb(se)
}
}
if scanner.Err() != nil {
logp.Warn("error scanning synthetics runner results %s", scanner.Err())
return scanner.Err()
}
return nil
}
var stdoutToSynthEvent = lineToSynthEventFactory("stdout")
var stderrToSynthEvent = lineToSynthEventFactory("stderr")
// lineToSynthEventFactory is a factory that can take a line from the scanner and transform it into a *SynthEvent.
func lineToSynthEventFactory(typ string) func(bytes []byte, text string) (res *SynthEvent, err error) {
return func(bytes []byte, text string) (res *SynthEvent, err error) {
logp.Info("%s: %s", typ, text)
return &SynthEvent{
Type: typ,
TimestampEpochMicros: float64(time.Now().UnixMicro()),
Payload: common.MapStr{
"message": text,
},
}, nil
}
}
var emptyStringRegexp = regexp.MustCompile(`^\s*$`)
// jsonToSynthEvent can take a line from the scanner and transform it into a *SynthEvent. Will return
// nil res on empty lines.
func jsonToSynthEvent(bytes []byte, text string) (res *SynthEvent, err error) {
// Skip empty lines
if emptyStringRegexp.Match(bytes) {
return nil, nil
}
res = &SynthEvent{}
err = json.Unmarshal(bytes, res)
if err != nil {
return nil, err
}
if res.Type == "" {
return nil, fmt.Errorf("unmarshal succeeded, but no type found for: %s", text)
}
return
}
// getNpmRoot gets the closest ancestor path that contains package.json.
func getNpmRoot(path string) (string, error) {
return getNpmRootIn(path, path)
}
// getNpmRootIn does the same as getNpmRoot but remembers the original path for
// debugging.
func getNpmRootIn(path, origPath string) (string, error) {
if path == "" {
return "", fmt.Errorf("cannot check for package.json in empty path: '%s'", origPath)
}
candidate := filepath.Join(path, "package.json")
_, err := os.Lstat(candidate)
if err == nil {
return path, nil
}
// Try again one level up
parent := filepath.Dir(path)
if len(parent) < 2 {
return "", fmt.Errorf("no package.json found in '%s'", origPath)
}
return getNpmRootIn(parent, origPath)
}