-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
operator.go
2128 lines (1992 loc) · 50.5 KB
/
operator.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
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package runn
import (
"context"
ejson "encoding/json"
"errors"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"os"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/k1LoW/concgroup"
"github.com/k1LoW/donegroup"
"github.com/k1LoW/maskedio"
"github.com/k1LoW/runn/exprtrace"
"github.com/k1LoW/runn/internal/deprecation"
"github.com/k1LoW/stopw"
"github.com/k1LoW/waitmap"
"github.com/ryo-yamaoka/otchkiss"
"github.com/samber/lo"
"github.com/spf13/cast"
)
var errStepSkipped = errors.New("step skipped")
var ErrFailFast = errors.New("fail fast")
var _ otchkiss.Requester = (*operatorN)(nil)
type need struct {
path string
op *operator
}
type deferredOpAndStep struct {
op *operator
step *step
}
type deferredOpAndSteps struct {
steps []*deferredOpAndStep
}
type operator struct {
id string
httpRunners map[string]*httpRunner
dbRunners map[string]*dbRunner
grpcRunners map[string]*grpcRunner
cdpRunners map[string]*cdpRunner
sshRunners map[string]*sshRunner
includeRunners map[string]*includeRunner
steps []*step
deferred *deferredOpAndSteps
store *store
desc string
needs map[string]*need // Map of `needs:` in runbook. key is the operator.bookPath.
nm *waitmap.WaitMap[string, *store] // Map of runbook result stores. key is the operator.bookPath.
labels []string
useMap bool // Use map syntax in `steps:`.
debug bool // Enable debug mode
profile bool
interval time.Duration
loop *Loop
loopIndex *int // Index of the loop is dynamically recorded at runtime
concurrency []string
root string // Root directory of runbook ( rubbook path or working directory )
t *testing.T
thisT *testing.T
parent *step
force bool
trace bool // Enable tracing ( e.g. add trace header to HTTP request )
waitTimeout time.Duration
included bool
ifCond string
skipTest bool
skipped bool
stdout *maskedio.Writer
stderr *maskedio.Writer
newOnly bool // Skip some errors for `runn list`
bookPath string
numberOfSteps int // Number of steps for `runn list`
beforeFuncs []func(*RunResult) error
afterFuncs []func(*RunResult) error
sw *stopw.Span
capturers capturers
runResult *RunResult
dbg *dbg
hasRunnerRunner bool
maskRule *maskedio.Rule
mu sync.Mutex
}
// ID returns id of current runbook.
func (op *operator) ID() string {
return op.id
}
// runbookID returns id of the root runbook.
func (op *operator) runbookID() string { //nolint:unused
return op.trails().runbookID()
}
// Desc returns `desc:` of runbook.
func (op *operator) Desc() string {
return op.desc
}
// If returns `if:` of runbook.
func (op *operator) If() string {
return op.ifCond
}
// BookPath returns path of runbook.
func (op *operator) BookPath() string {
return op.bookPath
}
// NumberOfSteps returns number of steps.
func (op *operator) NumberOfSteps() int {
return op.numberOfSteps
}
// Store returns stored values.
// Deprecated: Use Result().Store() instead.
func (op *operator) Store() map[string]any {
deprecation.AddWarning("operator.Store", "Use Result().Store() instead.")
return op.Result().Store()
}
// Close runners.
func (op *operator) Close(force bool) {
for _, r := range op.grpcRunners {
if !force && r.target == "" {
continue
}
_ = r.Close()
}
for _, r := range op.cdpRunners {
_ = r.Close()
}
for _, r := range op.sshRunners {
_ = r.Close()
}
for _, r := range op.dbRunners {
if !force && r.dsn == "" {
continue
}
_ = r.Close()
}
}
func (op *operator) runStep(ctx context.Context, s *step) error {
idx := s.idx
if op.t != nil {
op.t.Helper()
}
if err := op.dbg.attach(ctx, s); err != nil {
return err
}
trs := s.trails()
defer op.sw.Start(trs.toProfileIDs()...).Stop()
op.capturers.setCurrentTrails(trs)
if idx != 0 {
// interval:
time.Sleep(op.interval)
op.Debugln("")
}
if s.ifCond != "" {
tf, err := op.expandCondBeforeRecord(s.ifCond, s)
if err != nil {
return err
}
if !tf {
if s.desc != "" {
op.Debugf(yellow("Skip %q on %s\n"), s.desc, op.stepName(idx))
} else if s.runnerKey != "" {
op.Debugf(yellow("Skip %q on %s\n"), s.runnerKey, op.stepName(idx))
} else {
op.Debugf(yellow("Skip on %s\n"), op.stepName(idx))
}
return errStepSkipped
}
}
if s.desc != "" {
op.Debugf(cyan("Run %q on %s\n"), s.desc, op.stepName(idx))
} else if s.runnerKey != "" {
op.Debugf(cyan("Run %q on %s\n"), s.runnerKey, op.stepName(idx))
}
stepFn := func(t *testing.T) error {
s.clearResult()
if t != nil {
t.Helper()
}
run := false
if s.notYetDetectedRunner() {
if r, ok := op.httpRunners[s.runnerKey]; ok {
s.httpRunner = r
s.httpRequest = s.runnerValues
}
if r, ok := op.dbRunners[s.runnerKey]; ok {
s.dbRunner = r
s.dbQuery = s.runnerValues
}
if r, ok := op.grpcRunners[s.runnerKey]; ok {
s.grpcRunner = r
s.grpcRequest = s.runnerValues
}
if r, ok := op.cdpRunners[s.runnerKey]; ok {
s.cdpRunner = r
s.cdpActions = s.runnerValues
}
if r, ok := op.sshRunners[s.runnerKey]; ok {
s.sshRunner = r
s.sshCommand = s.runnerValues
}
}
switch {
case s.httpRunner != nil && s.httpRequest != nil:
if err := s.httpRunner.Run(ctx, s); err != nil {
return fmt.Errorf("http request failed on %s: %w", op.stepName(idx), err)
}
run = true
case s.dbRunner != nil && s.dbQuery != nil:
if err := s.dbRunner.Run(ctx, s); err != nil {
return fmt.Errorf("db query failed on %s: %w", op.stepName(idx), err)
}
run = true
case s.grpcRunner != nil && s.grpcRequest != nil:
if err := s.grpcRunner.Run(ctx, s); err != nil {
return fmt.Errorf("gRPC request failed on %s: %w", op.stepName(idx), err)
}
run = true
case s.cdpRunner != nil && s.cdpActions != nil:
if err := s.cdpRunner.Run(ctx, s); err != nil {
return fmt.Errorf("cdp action failed on %s: %w", op.stepName(idx), err)
}
run = true
case s.sshRunner != nil && s.sshCommand != nil:
if err := s.sshRunner.Run(ctx, s); err != nil {
return fmt.Errorf("ssh command failed on %s: %w", op.stepName(idx), err)
}
run = true
case s.execRunner != nil && s.execCommand != nil:
if err := s.execRunner.Run(ctx, s); err != nil {
return fmt.Errorf("exec command failed on %s: %w", op.stepName(idx), err)
}
run = true
case s.includeRunner != nil && s.includeConfig != nil:
if err := s.includeRunner.Run(ctx, s); err != nil {
return fmt.Errorf("include failed on %s: %w", op.stepName(idx), err)
}
run = true
case s.runnerRunner != nil && s.runnerDefinition != nil:
if err := s.runnerRunner.Run(ctx, s); err != nil {
return fmt.Errorf("runner definition failed on %s: %w", op.stepName(idx), err)
}
run = true
}
// dump runner
if s.dumpRunner != nil && s.dumpRequest != nil {
op.Debugf(cyan("Run %q on %s\n"), dumpRunnerKey, op.stepName(idx))
if err := s.dumpRunner.Run(ctx, s, !run); err != nil {
return fmt.Errorf("dump failed on %s: %w", op.stepName(idx), err)
}
run = true
}
// bind runner
if s.bindRunner != nil && s.bindCond != nil {
op.Debugf(cyan("Run %q on %s\n"), bindRunnerKey, op.stepName(idx))
if err := s.bindRunner.Run(ctx, s, !run); err != nil {
return fmt.Errorf("bind failed on %s: %w", op.stepName(idx), err)
}
run = true
}
// test runner
if s.testRunner != nil && s.testCond != "" {
if op.skipTest {
op.Debugf(yellow("Skip %q on %s\n"), testRunnerKey, op.stepName(idx))
if !run {
return errStepSkipped
}
return nil
}
op.Debugf(cyan("Run %q on %s\n"), testRunnerKey, op.stepName(idx))
if err := s.testRunner.Run(ctx, s, !run); err != nil {
if s.desc != "" {
return fmt.Errorf("test failed on %s %q: %w", op.stepName(idx), s.desc, err)
} else {
return fmt.Errorf("test failed on %s: %w", op.stepName(idx), err)
}
}
run = true
}
if !run {
return fmt.Errorf("invalid runner: %v", op.stepName(idx))
}
return nil
}
// loop
if s.loop != nil {
defer func() {
op.store.loopIndex = nil
s.loopIndex = nil
s.loop.Clear()
}()
retrySuccess := false
if s.loop.Until == "" {
retrySuccess = true
}
var (
bt string
j int
)
c, err := EvalCount(s.loop.Count, op.store.toMap())
if err != nil {
return err
}
for s.loop.Loop(ctx) {
if j >= c {
break
}
jj := j
op.store.loopIndex = &jj
s.loopIndex = &jj
trs := s.trails()
op.capturers.setCurrentTrails(trs)
sw := op.sw.Start(trs.toProfileIDs()...)
if err := stepFn(op.thisT); err != nil {
sw.Stop()
return fmt.Errorf("loop failed: %w", err)
}
sw.Stop()
if s.loop.Until != "" {
store := op.store.toMap()
store[storeRootKeyIncluded] = op.included
if !s.deferred {
store[storeRootKeyPrevious] = op.store.previous()
}
store[storeRootKeyCurrent] = op.store.latest()
tf, err := EvalWithTrace(s.loop.Until, store)
if err != nil {
return fmt.Errorf("loop failed on %s: %w", op.stepName(idx), err)
}
if tf.OutputAsBool() {
retrySuccess = true
break
} else {
bt, err = tf.FormatTraceTree()
if err != nil {
return fmt.Errorf("loop failed on %s: %w", op.stepName(idx), err)
}
}
}
j++
}
if !retrySuccess {
err := fmt.Errorf("(%s) is not true\n%s", s.loop.Until, bt)
if s.loop.interval != nil {
return fmt.Errorf("retry loop failed on %s.loop (count: %d, interval: %v): %w", op.stepName(idx), c, *s.loop.interval, err)
} else {
return fmt.Errorf("retry loop failed on %s.loop (count: %d, minInterval: %v, maxInterval: %v): %w", op.stepName(idx), c, *s.loop.minInterval, *s.loop.maxInterval, err)
}
}
} else {
if err := stepFn(op.thisT); err != nil {
return err
}
}
return nil
}
// Record that it has not been run.
func (op *operator) recordNotRun(idx int) {
v := map[string]any{}
op.store.record(idx, v)
}
func (op *operator) record(idx int, v map[string]any) {
if v == nil {
v = map[string]any{}
}
op.store.record(idx, v)
}
func (op *operator) recordResult(idx int, v result) error {
r := op.Result()
r.StepResults = op.StepResults()
op.capturers.captureResultByStep(op.trails(), r)
return op.store.recordTo(idx, storeStepKeyOutcome, v)
}
func (op *operator) recordCookie(cookies []*http.Cookie) {
op.store.recordCookie(cookies)
}
func (op *operator) generateTrail() Trail {
return Trail{
Type: TrailTypeRunbook,
Desc: op.desc,
RunbookID: op.id,
RunbookPath: op.bookPath,
}
}
func (op *operator) trails() Trails {
var trs Trails
if op.parent != nil {
trs = op.parent.trails()
}
trs = append(trs, op.generateTrail())
if op.loopIndex != nil {
trs = append(trs, Trail{
Type: TrailTypeLoop,
LoopIndex: op.loopIndex,
RunbookID: op.id,
})
}
return trs
}
// New returns *operator.
func New(opts ...Option) (*operator, error) {
bk := newBook()
if err := bk.applyOptions(opts...); err != nil {
return nil, err
}
id, err := generateRandomID()
if err != nil {
return nil, err
}
st := newStore(bk.vars, bk.funcs, bk.secrets, bk.useMap, bk.stepKeys)
op := &operator{
id: id,
httpRunners: map[string]*httpRunner{},
dbRunners: map[string]*dbRunner{},
grpcRunners: map[string]*grpcRunner{},
cdpRunners: map[string]*cdpRunner{},
sshRunners: map[string]*sshRunner{},
includeRunners: map[string]*includeRunner{},
deferred: &deferredOpAndSteps{},
store: st,
useMap: bk.useMap,
desc: bk.desc,
labels: bk.labels,
debug: bk.debug,
nm: waitmap.New[string, *store](),
profile: bk.profile,
interval: bk.interval,
loop: bk.loop,
concurrency: bk.concurrency,
t: bk.t,
thisT: bk.t,
force: bk.force,
trace: bk.trace,
waitTimeout: bk.waitTimeout,
included: bk.included,
ifCond: bk.ifCond,
skipTest: bk.skipTest,
stdout: st.maskRule().NewWriter(bk.stdout),
stderr: st.maskRule().NewWriter(bk.stderr),
newOnly: bk.loadOnly,
bookPath: bk.path,
beforeFuncs: bk.beforeFuncs,
afterFuncs: bk.afterFuncs,
sw: stopw.New(),
capturers: bk.capturers,
runResult: newRunResult(bk.desc, bk.labels, bk.path, bk.included, st),
dbg: newDBG(bk.attach),
maskRule: st.maskRule(),
}
if op.debug {
op.capturers = append(op.capturers, NewDebugger(op.stderr))
}
root, err := bk.generateOperatorRoot()
if err != nil {
return nil, fmt.Errorf("failed to generate root path (%s): %w", bk.path, err)
}
op.root = root
var loErr error
op.needs = lo.MapEntries(bk.needs, func(key string, path string) (string, *need) {
p, err := fp(path, op.root)
if err != nil {
loErr = errors.Join(loErr, err)
}
return key, &need{
path: p,
}
})
if loErr != nil {
return nil, loErr
}
// The host rules specified by the option take precedence.
hostRules := append(bk.hostRulesFromOpts, bk.hostRules...)
for k, v := range bk.httpRunners {
if _, ok := v.validator.(*nopValidator); ok {
for _, l := range bk.openAPI3DocLocations {
key, p := splitKeyAndPath(l)
if key != "" && key != k {
continue
}
runner, ok := bk.runners[k].(map[string]any)
if !ok {
return nil, fmt.Errorf("invalid type: %v", bk.runners[k])
}
c := &httpRunnerConfig{
OpenAPI3DocLocation: p,
}
c.SkipValidateRequest, _ = runner["skipValidateRequest"].(bool)
c.SkipValidateResponse, _ = runner["skipValidateResponse"].(bool)
val, err := newHttpValidator(c)
if err != nil {
return nil, err
}
v.validator = val
break
}
}
if len(hostRules) > 0 {
tp, ok := v.client.Transport.(*http.Transport)
if !ok {
return nil, fmt.Errorf("failed to cast: %v", v.client.Transport)
}
tp.DialContext = hostRules.dialContextFunc()
}
op.httpRunners[k] = v
}
for k, v := range bk.dbRunners {
if len(hostRules) > 0 {
v.hostRules = hostRules
if err := v.Renew(); err != nil {
return nil, err
}
}
if v.operatorID == "" {
v.operatorID = op.id
}
op.dbRunners[k] = v
}
for k, v := range bk.grpcRunners {
if bk.grpcNoTLS {
useTLS := false
v.tls = &useTLS
}
for _, proto := range bk.grpcProtos {
key, p := splitKeyAndPath(proto)
if key != "" && key != k {
continue
}
v.protos = append(v.protos, p)
}
for _, ip := range bk.grpcImportPaths {
key, p := splitKeyAndPath(ip)
if key != "" && key != k {
continue
}
v.importPaths = append(v.importPaths, p)
}
v.bufDirs = unique(append(v.bufDirs, bk.grpcBufDirs...))
v.bufLocks = unique(append(v.bufLocks, bk.grpcBufLocks...))
v.bufConfigs = unique(append(v.bufConfigs, bk.grpcBufConfigs...))
v.bufModules = unique(append(v.bufModules, bk.grpcBufModules...))
if len(hostRules) > 0 {
v.hostRules = hostRules
if err := v.Renew(); err != nil {
return nil, err
}
}
if v.operatorID == "" {
v.operatorID = op.id
}
op.grpcRunners[k] = v
}
for k, v := range bk.cdpRunners {
if len(hostRules) > 0 {
v.opts = append(v.opts, hostRules.chromedpOpt())
}
if err := v.Renew(); err != nil {
return nil, err
}
if v.operatorID == "" {
v.operatorID = op.id
}
op.cdpRunners[k] = v
}
for k, v := range bk.sshRunners {
if len(hostRules) > 0 {
v.hostRules = hostRules
if err := v.Renew(); err != nil {
return nil, err
}
}
if v.operatorID == "" {
v.operatorID = op.id
}
op.sshRunners[k] = v
}
for k, v := range bk.includeRunners {
op.includeRunners[k] = v
}
keys := map[string]struct{}{}
for k := range op.httpRunners {
keys[k] = struct{}{}
}
for k := range op.dbRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", op.bookPath, k)
}
keys[k] = struct{}{}
}
for k := range op.grpcRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", op.bookPath, k)
}
keys[k] = struct{}{}
}
for k := range op.cdpRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", op.bookPath, k)
}
keys[k] = struct{}{}
}
for k := range op.sshRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", op.bookPath, k)
}
keys[k] = struct{}{}
}
for k := range op.includeRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", op.bookPath, k)
}
keys[k] = struct{}{}
}
var errs error
for k, err := range bk.runnerErrs {
errs = errors.Join(errs, fmt.Errorf("runner %s error: %w", k, err))
}
if errs != nil && !op.newOnly {
return nil, fmt.Errorf("failed to add runners (%s): %w", op.bookPath, errs)
}
op.numberOfSteps = len(bk.rawSteps)
for i, s := range bk.rawSteps {
key := fmt.Sprintf("%d", i)
if op.useMap {
key = bk.stepKeys[i]
}
if err := op.appendStep(i, key, s); err != nil {
if op.newOnly {
continue
}
return nil, fmt.Errorf("failed to append step (%s): %w", op.bookPath, err)
}
}
return op, nil
}
// appendStep appends step.
func (op *operator) appendStep(idx int, key string, s map[string]any) error {
if op.t != nil {
op.t.Helper()
}
st := newStep(idx, key, op, s)
// if section
if v, ok := s[ifSectionKey]; ok {
st.ifCond, ok = v.(string)
if !ok {
return fmt.Errorf("invalid if condition: %v", v)
}
delete(s, ifSectionKey)
}
// desc section
if v, ok := s[descSectionKey]; ok {
st.desc, ok = v.(string)
if !ok {
return fmt.Errorf("invalid desc: %v", v)
}
delete(s, descSectionKey)
}
// defer section
if v, ok := s[deferSectionKey]; ok {
st.deferred, ok = v.(bool)
if !ok {
return fmt.Errorf("invalid defer: %v", v)
}
delete(s, deferSectionKey)
}
// loop section
if v, ok := s[loopSectionKey]; ok {
r, err := newLoop(v)
if err != nil {
return fmt.Errorf("invalid loop: %w\n%v", err, v)
}
st.loop = r
delete(s, loopSectionKey)
}
// test runner
if v, ok := s[testRunnerKey]; ok {
st.testRunner = newTestRunner()
switch vv := v.(type) {
case bool:
if vv {
st.testCond = "true"
} else {
st.testCond = "false"
}
case string:
st.testCond = vv
default:
return fmt.Errorf("invalid test condition: %v", v)
}
delete(s, testRunnerKey)
}
// dump runner
if v, ok := s[dumpRunnerKey]; ok {
st.dumpRunner = newDumpRunner()
switch vv := v.(type) {
case string:
st.dumpRequest = &dumpRequest{
expr: vv,
}
case map[string]any:
expr, ok := vv["expr"]
if !ok {
return fmt.Errorf("invalid dump request: %v", vv)
}
out, ok := vv["out"]
if !ok {
out = "" // default: op.stdout
}
disableNL, ok := vv["disableTrailingNewline"]
if !ok {
disableNL = false
}
disableMask, ok := vv["disableMaskingSecrets"]
if !ok {
disableMask = false
}
st.dumpRequest = &dumpRequest{
expr: cast.ToString(expr),
out: cast.ToString(out),
disableTrailingNewline: cast.ToBool(disableNL),
disableMaskingSecrets: cast.ToBool(disableMask),
}
default:
return fmt.Errorf("invalid dump request: %v", vv)
}
delete(s, dumpRunnerKey)
}
// bind runner
if v, ok := s[bindRunnerKey]; ok {
st.bindRunner = newBindRunner()
cond, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid bind condition: %v", v)
}
st.bindCond = cond
delete(s, bindRunnerKey)
}
k, v, ok := pop(s)
if ok {
st.runnerKey = k
switch {
case k == includeRunnerKey:
ir, err := newIncludeRunner()
if err != nil {
return err
}
st.includeRunner = ir
c, err := parseIncludeConfig(v)
if err != nil {
return err
}
c.step = st
st.includeConfig = c
case k == execRunnerKey:
st.execRunner = newExecRunner()
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid exec command: %v", v)
}
st.execCommand = vv
case k == runnerRunnerKey:
st.runnerRunner = newRunnerRunner()
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid runner runner: %v", v)
}
st.runnerDefinition = vv
op.hasRunnerRunner = true
default:
detected := false
h, ok := op.httpRunners[k]
if ok {
st.httpRunner = h
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid http request: %v", v)
}
st.httpRequest = vv
detected = true
}
db, ok := op.dbRunners[k]
if ok && !detected {
st.dbRunner = db
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid db query: %v", v)
}
st.dbQuery = vv
detected = true
}
gc, ok := op.grpcRunners[k]
if ok && !detected {
st.grpcRunner = gc
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid gRPC request: %v", v)
}
st.grpcRequest = vv
detected = true
}
cc, ok := op.cdpRunners[k]
if ok && !detected {
st.cdpRunner = cc
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid CDP actions: %v", v)
}
st.cdpActions = vv
detected = true
}
sc, ok := op.sshRunners[k]
if ok && !detected {
st.sshRunner = sc
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid SSH command: %v", v)
}
st.sshCommand = vv
detected = true
}
ic, ok := op.includeRunners[k]
if ok && !detected {
st.includeRunner = ic
c := &includeConfig{
step: st,
}
st.includeConfig = c
detected = true
}
if !detected {
if !op.hasRunnerRunner {
return fmt.Errorf("cannot find client: %s", k)
}
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid runner values: %v", v)
}
st.runnerValues = vv
}
}
}
op.steps = append(op.steps, st)
return nil
}
// Run runbook.
func (op *operator) Run(ctx context.Context) (err error) {
defer deprecation.PrintWarnings()
cctx, cancel := donegroup.WithCancel(ctx)
defer func() {
cancel()
var errr error
if op.waitTimeout > 0 {
errr = donegroup.WaitWithTimeout(cctx, op.waitTimeout)
} else {
errr = donegroup.Wait(cctx)
}
err = errors.Join(err, errr)
op.nm.Close()
}()
if op.t != nil {
op.t.Helper()
}
if !op.profile {
op.sw.Disable()
}
opn := op.toOperatorN()
result, err := opn.runN(cctx)
opn.mu.Lock()
opn.results = append(opn.results, result)
opn.mu.Unlock()
if err != nil {
if !errors.Is(err, ErrFailFast) {
return err
}
}
return result.RunResults[len(result.RunResults)-1].Err
}
// DumpProfile write run time profile.
func (op *operator) DumpProfile(w io.Writer) error {
r := op.sw.Result()
if r == nil {
return errors.New("no profile")
}
// Use encoding/json because goccy/go-json got a SIGSEGV error due to the increase in Trail fields.
enc := ejson.NewEncoder(w)
if err := enc.Encode(r); err != nil {
return err
}
return nil
}
// Result returns run result.
func (op *operator) Result() *RunResult {
op.runResult.ID = op.runbookID()
r := op.sw.Result()
if r != nil {
if err := setElasped(op.runResult, r); err != nil {
panic(err)
}
}
return op.runResult
}
func (op *operator) clearResult() {
op.runResult = newRunResult(op.desc, op.labels, op.bookPathOrID(), op.included, op.store)
op.runResult.ID = op.runbookID()
for _, s := range op.steps {
s.clearResult()
}
}
// run - Minimum unit to run one runbook.
func (op *operator) run(ctx context.Context) error {
defer op.sw.Start(op.trails().toProfileIDs()...).Stop()
defer func() {
// Results for `needs:` are not overwritten.
_ = op.nm.TrySet(op.bookPathOrID(), op.runResult.store)
}()
if op.newOnly {
return errors.New("this runbook is not allowed to run")
}
for k, n := range op.needs {
select {
case <-ctx.Done():
case v := <-op.nm.Chan(n.path):
if len(v.bindVars) > 0 {
op.store.needsVars[k] = v.bindVars
} else {
op.store.needsVars[k] = nil
}
}
}
var err error
if op.t != nil {
// As test helper
op.t.Helper()
op.t.Run(op.testName(), func(t *testing.T) {
t.Helper()
op.thisT = t
if op.loop != nil {
err = op.runLoop(ctx)
} else {
err = op.runInternal(ctx)
}
if err != nil {
// Skip parent runner t.Error if there is an error in the included runbook
if !errors.Is(&includedRunErr{}, err) {
paths, indexes, errs := failedRunbookPathsAndErrors(op.runResult)
for ii, p := range paths {
last := p[len(p)-1]
b, err := readFile(last)
if err != nil {