Repository navigation
Expand file tree
/
Copy pathexecutor.go
More file actions
585 lines (493 loc) · 13.8 KB
/
Copy pathexecutor.go
File metadata and controls
585 lines (493 loc) · 13.8 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package godexer
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"text/template"
"github.com/expr-lang/expr"
"github.com/go-extras/errors"
"github.com/spf13/afero"
"gopkg.in/Knetic/govaluate.v2"
"github.com/go-extras/godexer/internal/logger"
)
const experimentExpr = "expr"
type BeforeCommandExecuteCallback func(command Command, variables map[string]any)
type HooksAfter map[string]func(variables map[string]any) error
var registeredCommands = make(map[string]func(ectx *ExecutorContext) Command)
var registeredValueFuncs = make(map[string]any)
func MaybeEvalValue(val any, variables map[string]any) any {
// we can only eval strings
v1, ok := val.(string)
if !ok {
return val
}
fnMap := template.FuncMap{
"shell_escape": ShellEscape,
}
for k, v := range registeredValueFuncs {
fnMap[k] = v
}
// check if the value is a valid template
tmpl, err := template.
New("tpl").
Funcs(fnMap).
Parse(v1)
if err != nil {
return val
}
// execute
var buf bytes.Buffer
err = tmpl.Execute(&buf, variables)
if err != nil {
return val
}
return buf.String()
}
// RegisterValueFunc registers template value functions.
// Not safe for concurrent usage.
func RegisterValueFunc(name string, fn any) {
registeredValueFuncs[name] = fn
}
// UnregisterValueFunc unregisters template value functions.
// Not safe for concurrent usage.
func UnregisterValueFunc(name string) {
delete(registeredValueFuncs, name)
}
func RegisterCommand(name string, cmd func(ectx *ExecutorContext) Command) {
registeredCommands[name] = cmd
}
func GetRegisteredCommands() map[string]func(ectx *ExecutorContext) Command {
m := make(map[string]func(ectx *ExecutorContext) Command)
for k, v := range registeredCommands {
m[k] = v
}
return m
}
type CommandDebugInfo struct {
ID int
Contents []byte
}
type Command interface {
GetRequires() string
GetStepName() string
GetHookAfter() string
GetDescription(variables map[string]any) string
Execute(variables map[string]any) error
}
type DebugInfoer interface {
DebugInfo() *CommandDebugInfo
SetDebugInfo(*CommandDebugInfo)
}
type BaseCommand struct {
Type string
StepName string
Description string
Requires string
CallsAfter string
Ectx *ExecutorContext
debugInfo *CommandDebugInfo
}
func (r *BaseCommand) DebugInfo() *CommandDebugInfo {
return r.debugInfo
}
func (r *BaseCommand) SetDebugInfo(di *CommandDebugInfo) {
r.debugInfo = di
}
func (r *BaseCommand) GetRequires() string {
return r.Requires
}
func (r *BaseCommand) GetStepName() string {
if r.StepName == "" && r.debugInfo != nil && r.debugInfo.ID > 0 {
return fmt.Sprintf("__step_no_%03d", r.debugInfo.ID)
}
return r.StepName
}
func (r *BaseCommand) GetHookAfter() string {
return r.CallsAfter
}
func (r *BaseCommand) GetDescription(variables map[string]any) string {
if desc, ok := MaybeEvalValue(r.Description, variables).(string); ok {
return desc
}
return ""
}
type ExecutorContext struct {
Fs afero.Fs
Stdout io.Writer
Stderr io.Writer
Executor *Executor
Logger Logger
}
// RawScenario describes a top-level YAML/JSON scenario document.
//
// Supported shape:
// - `commands: [...]`
// - optional `meta.experiments: ["expr", "-expr"]`
type RawScenario struct {
Meta *RawScenarioMeta `json:"meta,omitempty"`
Commands []json.RawMessage `json:"commands"`
}
// RawScenarioMeta contains top-level scenario metadata.
type RawScenarioMeta struct {
Experiments []string `json:"experiments,omitempty"`
}
type Executor struct {
ectx *ExecutorContext
commands []Command
hooksAfter HooksAfter
experiments map[string]bool
evaluatorFunctions evaluatorFunctionRegistry
govaluateEvaluatorFunctions map[string]govaluate.ExpressionFunction
commandTypes map[string]func(ectx *ExecutorContext) Command
beforeCommandExecuteCallback BeforeCommandExecuteCallback
stepNameSuffix string
}
type Option func(*Executor)
func New(opts ...Option) *Executor {
ectx := &ExecutorContext{
Fs: afero.NewOsFs(),
Stdout: os.Stdout,
Stderr: os.Stderr,
Logger: &logger.Logger{},
}
ex := &Executor{
ectx: ectx,
experiments: make(map[string]bool),
evaluatorFunctions: newEvaluatorFunctionRegistry(),
beforeCommandExecuteCallback: func(Command, map[string]any) {},
hooksAfter: make(HooksAfter),
commandTypes: registeredCommands,
}
ex.ectx.Executor = ex
for _, opt := range opts {
opt(ex)
}
return ex
}
func NewWithScenario(scenario string, opts ...Option) (*Executor, error) {
ex := New(opts...)
err := ex.AppendScenario(scenario)
if err != nil {
return nil, err
}
return ex, nil
}
func WithCommands(cmds []Command) func(ex *Executor) {
return func(ex *Executor) {
ex.commands = cmds
}
}
func WithStepNameSuffix(suffix string) func(ex *Executor) {
return func(ex *Executor) {
ex.stepNameSuffix = suffix
}
}
func WithHookAfter(name string, hook func(variables map[string]any) error) func(ex *Executor) {
return func(ex *Executor) {
ex.hooksAfter[name] = hook
}
}
func WithHooksAfter(hooks HooksAfter) func(ex *Executor) {
return func(ex *Executor) {
ex.hooksAfter = hooks
}
}
func WithStdout(stdout io.Writer) func(ex *Executor) {
return func(ex *Executor) {
ex.ectx.Stdout = stdout
}
}
func WithStderr(stderr io.Writer) func(ex *Executor) {
return func(ex *Executor) {
ex.ectx.Stderr = stderr
}
}
func WithFS(fs afero.Fs) func(ex *Executor) {
return func(ex *Executor) {
ex.ectx.Fs = fs
}
}
func WithCommandTypes(types map[string]func(ectx *ExecutorContext) Command) func(ex *Executor) {
return func(ex *Executor) {
ex.commandTypes = types
}
}
func WithRegisteredCommandTypes() func(ex *Executor) {
return WithCommandTypes(GetRegisteredCommands())
}
func WithLogger(log Logger) func(ex *Executor) {
return func(ex *Executor) {
ex.ectx.Logger = log
}
}
func withExperiments(experiments map[string]bool) func(ex *Executor) {
return func(ex *Executor) {
ex.experiments = copyExperiments(experiments)
}
}
// WithDefaultEvaluatorFunctions registers value evaluator functions.
//
// There are 3 of them available:
// - `file_exists(filename string) (bool, error)` - returns true if file exists
// - `strlen(str string) (float64, error)` - returns the length of the string as a number
// - `shell_escape(str string) (string, error)` - returns the shell-escaped version of the string
func WithDefaultEvaluatorFunctions() func(ex *Executor) {
return func(ex *Executor) {
ex.RegisterEvaluatorFunction("file_exists", func(args ...any) (any, error) {
if len(args) != 1 {
return false, errors.New("invalid number of arguments")
}
fname, ok := args[0].(string)
if !ok {
return false, errors.New("filename must be a string")
}
exists, err := fileExists(ex.ectx.Fs, fname)
return exists, err
})
ex.RegisterEvaluatorFunction("strlen", func(args ...any) (any, error) {
if len(args) != 1 {
return false, errors.New("invalid number of arguments")
}
length := len(args[0].(string))
return (float64)(length), nil
})
ex.RegisterEvaluatorFunction("shell_escape", func(args ...any) (any, error) {
if len(args) != 1 {
return false, errors.New("invalid number of arguments")
}
result := escapeArgs([]string{args[0].(string)})
return result, nil
})
}
}
func (ex *Executor) AppendScenario(scenario string) error {
data, err := toJSON([]byte(scenario))
if err != nil {
return err
}
cmds := &RawScenario{}
err = json.Unmarshal(data, cmds)
if err != nil {
return err
}
ex.applyScenarioMeta(cmds.Meta)
for id, rawCmd := range cmds.Commands {
var tq struct{ Type string }
err := json.Unmarshal(rawCmd, &tq)
if err != nil {
return err
}
fn := ex.commandTypes[tq.Type]
if fn == nil {
return errors.Errorf("invalid command type: %q", tq.Type)
}
cmd := fn(ex.ectx)
err = json.Unmarshal(rawCmd, cmd)
if err != nil {
return err
}
if dicmd, ok := cmd.(DebugInfoer); ok {
dicmd.SetDebugInfo(&CommandDebugInfo{
ID: id + 1,
Contents: rawCmd,
})
}
ex.commands = append(ex.commands, cmd)
}
return nil
}
// Execute runs installation script commands/actions according to the
// provided params map.
func (ex *Executor) Execute(variables map[string]any) (err error) {
for _, cmd := range ex.commands {
ex.beforeCommandExecuteCallback(cmd, variables)
skip, err := ex.checkRequires(cmd, variables)
if err != nil {
return NewCommandAwareError(err, cmd, variables)
}
stepName := cmd.GetStepName() + ex.stepNameSuffix
variables["__step:"+stepName+":skipped"] = skip
if skip {
continue
}
desc := cmd.GetDescription(variables)
if desc != "" {
ex.ectx.Logger.Info(desc)
}
err = cmd.Execute(variables)
if err != nil {
return NewCommandAwareError(err, cmd, variables)
}
hookName := cmd.GetHookAfter()
if hookName == "" {
continue
}
if hook := ex.hooksAfter[hookName]; hook != nil {
err := hook(variables)
if err != nil {
return NewCommandAwareError(err, cmd, variables)
}
}
}
return nil
}
func (ex *Executor) SetBeforeCommandExecuteCallback(cb BeforeCommandExecuteCallback) *Executor {
ex.beforeCommandExecuteCallback = cb
return ex
}
func (ex *Executor) WithScenario(scenario string, opts ...Option) (*Executor, error) {
newOpts := []Option{
WithHooksAfter(ex.hooksAfter),
WithStdout(ex.ectx.Stdout),
WithStderr(ex.ectx.Stderr),
WithFS(ex.ectx.Fs),
WithCommandTypes(ex.commandTypes),
WithLogger(ex.ectx.Logger),
withExperiments(ex.experiments),
WithRegisteredEvaluatorFunctions(ex.evaluatorFunctions.clone()),
}
newOpts = append(newOpts, opts...)
result, err := NewWithScenario(scenario, newOpts...)
if err != nil {
return nil, err
}
return result, nil
}
func (ex *Executor) WithCommands(cmds []Command, opts ...Option) *Executor {
newOpts := []Option{
WithCommands(cmds),
WithHooksAfter(ex.hooksAfter),
WithStdout(ex.ectx.Stdout),
WithStderr(ex.ectx.Stderr),
WithFS(ex.ectx.Fs),
WithCommandTypes(ex.commandTypes),
WithLogger(ex.ectx.Logger),
withExperiments(ex.experiments),
WithRegisteredEvaluatorFunctions(ex.evaluatorFunctions.clone()),
}
newOpts = append(newOpts, opts...)
result := New(newOpts...)
return result
}
func (ex *Executor) CommandTypes() map[string]func(ectx *ExecutorContext) Command {
result := make(map[string]func(ectx *ExecutorContext) Command, len(ex.commandTypes))
for k, v := range ex.commandTypes {
result[k] = v
}
return result
}
func (ex *Executor) CommandTypeFn(typ string) (func(ectx *ExecutorContext) Command, bool) {
cmd, ok := ex.commandTypes[typ]
return cmd, ok
}
// RegisterEvaluatorFunction registers an evaluator function.
func (ex *Executor) RegisterEvaluatorFunction(name string, fn EvaluatorFunction) *Executor {
ex.evaluatorFunctions.register(name, fn)
ex.rebuildGovaluateEvaluatorFunctionCache()
return ex
}
// RegisterEvaluatorFunctions registers evaluator functions.
func (ex *Executor) RegisterEvaluatorFunctions(funcs map[string]EvaluatorFunction) *Executor {
ex.evaluatorFunctions.registerAll(funcs)
ex.rebuildGovaluateEvaluatorFunctionCache()
return ex
}
func (ex *Executor) rebuildGovaluateEvaluatorFunctionCache() {
ex.govaluateEvaluatorFunctions = ex.evaluatorFunctions.govaluateFunctions()
}
func (ex *Executor) experimentEnabled(name string) bool {
if ex == nil {
return false
}
return ex.experiments[name]
}
func (ex *Executor) applyScenarioMeta(meta *RawScenarioMeta) {
if meta == nil {
return
}
for _, flag := range meta.Experiments {
name, enabled := parseExperimentFlag(flag)
if name == "" {
continue
}
if !isKnownExperiment(name) {
ex.ectx.Logger.Warnf("unknown experiment %q", name)
continue
}
ex.experiments[name] = enabled
}
}
func copyExperiments(experiments map[string]bool) map[string]bool {
if len(experiments) == 0 {
return make(map[string]bool)
}
result := make(map[string]bool, len(experiments))
for name, enabled := range experiments {
result[name] = enabled
}
return result
}
func parseExperimentFlag(flag string) (name string, enabled bool) {
trimmed := strings.TrimSpace(flag)
if strings.HasPrefix(trimmed, "-") {
return strings.TrimSpace(strings.TrimPrefix(trimmed, "-")), false
}
return trimmed, true
}
func isKnownExperiment(name string) bool {
switch name {
case experimentExpr:
return true
default:
return false
}
}
func (ex *Executor) checkRequires(cmd Command, variables map[string]any) (skip bool, err error) {
reqs := cmd.GetRequires()
if reqs == "" {
return false, nil
}
reqresi, err := ex.evaluateRequires(reqs, variables)
if err != nil {
return false, err
}
reqres, ok := reqresi.(bool)
if !ok {
return false, fmt.Errorf("Requires return type must be bool, got %T", reqresi)
}
if !reqres {
ex.ectx.Logger.Tracef("requirements not met, skipping %q", cmd.GetStepName())
variables[cmd.GetStepName()] = nil
return true, err
}
return false, nil
}
func (ex *Executor) evaluateRequires(reqs string, variables map[string]any) (any, error) {
if ex.experimentEnabled(experimentExpr) {
return ex.evaluateRequiresExpr(reqs, variables)
}
return ex.evaluateRequiresGovaluate(reqs, variables)
}
func (ex *Executor) evaluateRequiresGovaluate(reqs string, variables map[string]any) (any, error) {
expression, err := govaluate.NewEvaluableExpressionWithFunctions(reqs, ex.govaluateEvaluatorFunctions)
if err != nil {
return nil, err
}
return expression.Evaluate(variables)
}
func (ex *Executor) evaluateRequiresExpr(reqs string, variables map[string]any) (any, error) {
options := []expr.Option{
expr.Env(make(map[string]any)),
expr.AllowUndefinedVariables(),
expr.DisableAllBuiltins(),
}
options = append(options, ex.evaluatorFunctions.exprOptions()...)
program, err := expr.Compile(reqs, options...)
if err != nil {
return nil, err
}
return expr.Run(program, variables)
}