-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
operator.go
1500 lines (1408 loc) · 33.9 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"
"errors"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/goccy/go-json"
"github.com/k1LoW/concgroup"
"github.com/k1LoW/stopw"
"github.com/ryo-yamaoka/otchkiss"
"github.com/samber/lo"
"go.uber.org/multierr"
)
var errStepSkiped = errors.New("step skipped")
var _ otchkiss.Requester = (*operators)(nil)
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
steps []*step
store store
desc string
useMap bool // Use map syntax in `steps:`.
debug bool
profile bool
interval time.Duration
loop *Loop
concurrency string
// Root directory of runbook ( rubbook path or working directory )
root string
t *testing.T
thisT *testing.T
parent *step
force bool
failFast bool
included bool
ifCond string
skipTest bool
skipped bool
stdout io.Writer
stderr io.Writer
// Skip some errors for `runn list`
newOnly bool
bookPath string
// Number of steps for `runn list`
numberOfSteps int
beforeFuncs []func(*RunResult) error
afterFuncs []func(*RunResult) error
sw *stopw.Span
capturers capturers
runResult *RunResult
mu sync.Mutex
}
// ID returns id of runbook.
func (o *operator) ID() string {
return o.id
}
// Desc returns `desc:` of runbook.
func (o *operator) Desc() string {
return o.desc
}
// If returns `if:` of runbook.
func (o *operator) If() string {
return o.ifCond
}
// BookPath returns path of runbook.
func (o *operator) BookPath() string {
return o.bookPath
}
// NumberOfSteps returns number of steps.
func (o *operator) NumberOfSteps() int {
return o.numberOfSteps
}
// Close runners.
func (o *operator) Close(force bool) {
for _, r := range o.grpcRunners {
if !force && r.target == "" {
continue
}
_ = r.Close()
}
for _, r := range o.cdpRunners {
_ = r.Close()
}
for _, r := range o.sshRunners {
_ = r.Close()
}
for _, r := range o.dbRunners {
if !force && r.dsn == "" {
continue
}
_ = r.Close()
}
}
func (o *operator) runStep(ctx context.Context, i int, s *step) error {
if o.t != nil {
o.t.Helper()
}
ids := s.trails()
o.capturers.setCurrentTrails(ids)
defer o.sw.Start(ids.toInterfaceSlice()...).Stop()
if i != 0 {
// interval:
time.Sleep(o.interval)
o.Debugln("")
}
if s.ifCond != "" {
tf, err := o.expandCondBeforeRecord(s.ifCond)
if err != nil {
return err
}
if !tf {
if s.desc != "" {
o.Debugf(yellow("Skip %q on %s\n"), s.desc, o.stepName(i))
} else if s.runnerKey != "" {
o.Debugf(yellow("Skip %q on %s\n"), s.runnerKey, o.stepName(i))
} else {
o.Debugf(yellow("Skip on %s\n"), o.stepName(i))
}
return errStepSkiped
}
}
if s.desc != "" {
o.Debugf(cyan("Run %q on %s\n"), s.desc, o.stepName(i))
} else if s.runnerKey != "" {
o.Debugf(cyan("Run %q on %s\n"), s.runnerKey, o.stepName(i))
}
stepFn := func(t *testing.T) error {
if t != nil {
t.Helper()
}
run := false
switch {
case s.httpRunner != nil && s.httpRequest != nil:
e, err := o.expandBeforeRecord(s.httpRequest)
if err != nil {
return err
}
r, ok := e.(map[string]any)
if !ok {
return fmt.Errorf("invalid %s: %v", o.stepName(i), e)
}
req, err := parseHTTPRequest(r)
if err != nil {
return err
}
if err := s.httpRunner.Run(ctx, req); err != nil {
return fmt.Errorf("http request failed on %s: %w", o.stepName(i), err)
}
run = true
case s.dbRunner != nil && s.dbQuery != nil:
e, err := o.expandBeforeRecord(s.dbQuery)
if err != nil {
return err
}
q, ok := e.(map[string]any)
if !ok {
return fmt.Errorf("invalid %s: %v", o.stepName(i), e)
}
query, err := parseDBQuery(q)
if err != nil {
return fmt.Errorf("invalid %s: %v: %w", o.stepName(i), q, err)
}
if err := s.dbRunner.Run(ctx, query); err != nil {
return fmt.Errorf("db query failed on %s: %w", o.stepName(i), err)
}
run = true
case s.grpcRunner != nil && s.grpcRequest != nil:
req, err := parseGrpcRequest(s.grpcRequest, o.expandBeforeRecord)
if err != nil {
return fmt.Errorf("invalid %s: %v: %w", o.stepName(i), s.grpcRequest, err)
}
if err := s.grpcRunner.Run(ctx, req); err != nil {
return fmt.Errorf("gRPC request failed on %s: %w", o.stepName(i), err)
}
run = true
case s.cdpRunner != nil && s.cdpActions != nil:
cas, err := parseCDPActions(s.cdpActions, o.expandBeforeRecord)
if err != nil {
return fmt.Errorf("invalid %s: %w", o.stepName(i), err)
}
if err := s.cdpRunner.Run(ctx, cas); err != nil {
return fmt.Errorf("cdp action failed on %s: %w", o.stepName(i), err)
}
run = true
case s.sshRunner != nil && s.sshCommand != nil:
cmd, err := parseSSHCommand(s.sshCommand, o.expandBeforeRecord)
if err != nil {
return fmt.Errorf("invalid %s: %w", o.stepName(i), err)
}
if err := s.sshRunner.Run(ctx, cmd); err != nil {
return fmt.Errorf("ssh command failed on %s: %w", o.stepName(i), err)
}
run = true
case s.execRunner != nil && s.execCommand != nil:
e, err := o.expandBeforeRecord(s.execCommand)
if err != nil {
return err
}
cmd, ok := e.(map[string]any)
if !ok {
return fmt.Errorf("invalid %s: %v", o.stepName(i), e)
}
command, err := parseExecCommand(cmd)
if err != nil {
return fmt.Errorf("invalid %s: %v", o.stepName(i), cmd)
}
if err := s.execRunner.Run(ctx, command); err != nil {
return fmt.Errorf("exec command failed on %s: %w", o.stepName(i), err)
}
run = true
case s.includeRunner != nil && s.includeConfig != nil:
if err := s.includeRunner.Run(ctx, s.includeConfig); err != nil {
return fmt.Errorf("include failed on %s: %w", o.stepName(i), err)
}
run = true
}
// dump runner
if s.dumpRunner != nil && s.dumpRequest != nil {
o.Debugf(cyan("Run %q on %s\n"), dumpRunnerKey, o.stepName(i))
if err := s.dumpRunner.Run(ctx, s.dumpRequest, !run); err != nil {
return fmt.Errorf("dump failed on %s: %w", o.stepName(i), err)
}
run = true
}
// bind runner
if s.bindRunner != nil && s.bindCond != nil {
o.Debugf(cyan("Run %q on %s\n"), bindRunnerKey, o.stepName(i))
if err := s.bindRunner.Run(ctx, s.bindCond, !run); err != nil {
return fmt.Errorf("bind failed on %s: %w", o.stepName(i), err)
}
run = true
}
// test runner
if s.testRunner != nil && s.testCond != "" {
if o.skipTest {
o.Debugf(yellow("Skip %q on %s\n"), testRunnerKey, o.stepName(i))
if !run {
return errStepSkiped
}
return nil
}
o.Debugf(cyan("Run %q on %s\n"), testRunnerKey, o.stepName(i))
if err := s.testRunner.Run(ctx, s.testCond, !run); err != nil {
if s.desc != "" {
return fmt.Errorf("test failed on %s %q: %w", o.stepName(i), s.desc, err)
} else {
return fmt.Errorf("test failed on %s: %w", o.stepName(i), err)
}
}
run = true
}
if !run {
return fmt.Errorf("invalid runner: %v", o.stepName(i))
}
return nil
}
// loop
if s.loop != nil {
defer func() {
o.store.loopIndex = nil
}()
retrySuccess := false
if s.loop.Until == "" {
retrySuccess = true
}
var (
bt string
j int
)
c, err := EvalCount(s.loop.Count, o.store.toMap())
if err != nil {
return err
}
for s.loop.Loop(ctx) {
if j >= c {
break
}
jj := j
o.store.loopIndex = &jj
if err := stepFn(o.thisT); err != nil {
return fmt.Errorf("loop failed: %w", err)
}
if s.loop.Until != "" {
store := o.store.toMap()
store[storeIncludedKey] = o.included
store[storePreviousKey] = o.store.previous()
store[storeCurrentKey] = o.store.latest()
bt, err = buildTree(s.loop.Until, store)
if err != nil {
return fmt.Errorf("loop failed on %s: %w", o.stepName(i), err)
}
tf, err := EvalCond(s.loop.Until, store)
if err != nil {
return fmt.Errorf("loop failed on %s: %w", o.stepName(i), err)
}
if tf {
retrySuccess = true
break
}
}
j++
}
if !retrySuccess {
err := fmt.Errorf("(%s) is not true\n%s", s.loop.Until, bt)
o.store.loopIndex = nil
if s.loop.interval != nil {
return fmt.Errorf("retry loop failed on %s.loop (count: %d, interval: %v): %w", o.stepName(i), c, *s.loop.interval, err)
} else {
return fmt.Errorf("retry loop failed on %s.loop (count: %d, minInterval: %v, maxInterval: %v): %w", o.stepName(i), c, *s.loop.minInterval, *s.loop.maxInterval, err)
}
}
} else {
if err := stepFn(o.thisT); err != nil {
return err
}
}
return nil
}
// Record that it has not been run.
func (o *operator) recordNotRun(i int) {
if o.store.length() == i+1 {
return
}
v := map[string]any{}
v[storeStepRunKey] = false
if o.useMap {
o.recordAsMapped(v)
return
}
o.recordAsListed(v)
}
func (o *operator) record(v map[string]any) {
if v == nil {
v = map[string]any{}
}
v[storeStepRunKey] = true
if o.useMap {
o.recordAsMapped(v)
return
}
o.recordAsListed(v)
}
func (o *operator) recordAsListed(v map[string]any) {
if o.store.loopIndex != nil && *o.store.loopIndex > 0 {
// delete values of prevous loop
o.store.steps = o.store.steps[:o.store.length()-1]
}
o.store.recordAsListed(v)
}
func (o *operator) recordAsMapped(v map[string]any) {
if o.store.loopIndex != nil && *o.store.loopIndex > 0 {
// delete values of prevous loop
o.store.removeLatestAsMapped()
}
// Get next key
k := o.steps[o.store.length()].key
o.store.recordAsMapped(k, v)
}
func (o *operator) recordToLatest(key string, value any) error {
return o.store.recordToLatest(key, value)
}
func (o *operator) recordToCookie(cookies []*http.Cookie) {
o.store.recordToCookie(cookies)
}
func (o *operator) generateTrail() Trail {
return Trail{
Type: TrailTypeRunbook,
Desc: o.desc,
RunbookID: o.id,
RunbookPath: o.bookPath,
}
}
func (o *operator) trails() Trails {
var trs Trails
if o.parent != nil {
trs = o.parent.trails()
}
trs = append(trs, o.generateTrail())
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 := generateID(bk.path)
if err != nil {
return nil, err
}
o := &operator{
id: id,
httpRunners: map[string]*httpRunner{},
dbRunners: map[string]*dbRunner{},
grpcRunners: map[string]*grpcRunner{},
cdpRunners: map[string]*cdpRunner{},
sshRunners: map[string]*sshRunner{},
store: store{
steps: []map[string]any{},
stepMap: map[string]map[string]any{},
vars: bk.vars,
funcs: bk.funcs,
bindVars: map[string]any{},
useMap: bk.useMap,
},
useMap: bk.useMap,
desc: bk.desc,
debug: bk.debug,
profile: bk.profile,
interval: bk.interval,
loop: bk.loop,
concurrency: bk.concurrency,
t: bk.t,
thisT: bk.t,
force: bk.force,
failFast: bk.failFast,
included: bk.included,
ifCond: bk.ifCond,
skipTest: bk.skipTest,
stdout: bk.stdout,
stderr: 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.path),
}
if o.debug {
o.capturers = append(o.capturers, NewDebugger(o.stderr))
}
if o.concurrency == "" {
o.concurrency = o.id
}
root, err := bk.generateOperatorRoot()
if err != nil {
return nil, fmt.Errorf("failed to generate root path (%s): %w", bk.path, err)
}
o.root = root
for k, v := range bk.httpRunners {
v.operator = o
o.httpRunners[k] = v
}
for k, v := range bk.dbRunners {
v.operator = o
o.dbRunners[k] = v
}
for k, v := range bk.grpcRunners {
v.operator = o
if bk.grpcNoTLS {
useTLS := false
v.tls = &useTLS
}
v.protos = append(v.protos, bk.grpcProtos...)
v.importPaths = append(v.importPaths, bk.grpcImportPaths...)
o.grpcRunners[k] = v
}
for k, v := range bk.cdpRunners {
v.operator = o
o.cdpRunners[k] = v
}
for k, v := range bk.sshRunners {
v.operator = o
o.sshRunners[k] = v
}
keys := map[string]struct{}{}
for k := range o.httpRunners {
keys[k] = struct{}{}
}
for k := range o.dbRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", o.bookPath, k)
}
keys[k] = struct{}{}
}
for k := range o.grpcRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", o.bookPath, k)
}
keys[k] = struct{}{}
}
for k := range o.cdpRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", o.bookPath, k)
}
keys[k] = struct{}{}
}
for k := range o.sshRunners {
if _, ok := keys[k]; ok {
return nil, fmt.Errorf("duplicate runner names (%s): %s", o.bookPath, k)
}
keys[k] = struct{}{}
}
var merr error
for k, err := range bk.runnerErrs {
merr = multierr.Append(merr, fmt.Errorf("runner %s error: %w", k, err))
}
if merr != nil && !o.newOnly {
return nil, fmt.Errorf("failed to add runners (%s): %w", o.bookPath, merr)
}
o.numberOfSteps = len(bk.rawSteps)
for i, s := range bk.rawSteps {
key := fmt.Sprintf("%d", i)
if o.useMap {
key = bk.stepKeys[i]
}
if err := o.AppendStep(key, s); err != nil {
if o.newOnly {
continue
}
return nil, fmt.Errorf("failed to append step (%s): %w", o.bookPath, err)
}
}
return o, nil
}
// AppendStep appends step.
func (o *operator) AppendStep(key string, s map[string]any) error {
if o.t != nil {
o.t.Helper()
}
step := newStep(key, o)
// if section
if v, ok := s[ifSectionKey]; ok {
step.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 {
step.desc, ok = v.(string)
if !ok {
return fmt.Errorf("invalid desc: %v", v)
}
delete(s, descSectionKey)
}
// 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)
}
step.loop = r
delete(s, loopSectionKey)
}
// test runner
if v, ok := s[testRunnerKey]; ok {
tr, err := newTestRunner(o)
if err != nil {
return err
}
step.testRunner = tr
switch vv := v.(type) {
case bool:
if vv {
step.testCond = "true"
} else {
step.testCond = "false"
}
case string:
step.testCond = vv
default:
return fmt.Errorf("invalid test condition: %v", v)
}
delete(s, testRunnerKey)
}
// dump runner
if v, ok := s[dumpRunnerKey]; ok {
dr, err := newDumpRunner(o)
if err != nil {
return err
}
step.dumpRunner = dr
switch vv := v.(type) {
case string:
step.dumpRequest = &dumpRequest{
expr: vv,
}
case map[string]any:
expr, ok := vv["expr"]
if !ok {
return fmt.Errorf("invalid dump request: %v", vv)
}
out := vv["out"]
step.dumpRequest = &dumpRequest{
expr: expr.(string),
out: out.(string),
}
default:
return fmt.Errorf("invalid dump request: %v", vv)
}
delete(s, dumpRunnerKey)
}
// bind runner
if v, ok := s[bindRunnerKey]; ok {
br, err := newBindRunner(o)
if err != nil {
return err
}
step.bindRunner = br
cond, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid bind condition: %v", v)
}
step.bindCond = cond
delete(s, bindRunnerKey)
}
k, v, ok := pop(s)
if ok {
step.runnerKey = k
switch {
case k == includeRunnerKey:
ir, err := newIncludeRunner(o)
if err != nil {
return err
}
step.includeRunner = ir
c, err := parseIncludeConfig(v)
if err != nil {
return err
}
c.step = step
step.includeConfig = c
case k == execRunnerKey:
er, err := newExecRunner(o)
if err != nil {
return err
}
step.execRunner = er
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid exec command: %v", v)
}
step.execCommand = vv
default:
detected := false
h, ok := o.httpRunners[k]
if ok {
step.httpRunner = h
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid http request: %v", v)
}
step.httpRequest = vv
detected = true
}
db, ok := o.dbRunners[k]
if ok && !detected {
step.dbRunner = db
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid db query: %v", v)
}
step.dbQuery = vv
detected = true
}
gc, ok := o.grpcRunners[k]
if ok && !detected {
step.grpcRunner = gc
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid gRPC request: %v", v)
}
step.grpcRequest = vv
detected = true
}
cc, ok := o.cdpRunners[k]
if ok && !detected {
step.cdpRunner = cc
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid CDP actions: %v", v)
}
step.cdpActions = vv
detected = true
}
sc, ok := o.sshRunners[k]
if ok && !detected {
step.sshRunner = sc
vv, ok := v.(map[string]any)
if !ok {
return fmt.Errorf("invalid SSH command: %v", v)
}
step.sshCommand = vv
detected = true
}
if !detected {
return fmt.Errorf("cannot find client: %s", k)
}
}
}
o.steps = append(o.steps, step)
return nil
}
// Run runbook.
func (o *operator) Run(ctx context.Context) error {
cctx, cancel := context.WithCancel(ctx)
defer cancel()
o.clearResult()
if o.t != nil {
o.t.Helper()
}
if !o.profile {
o.sw.Disable()
}
defer o.sw.Start().Stop()
o.capturers.captureStart(o.trails(), o.bookPath, o.desc)
defer o.capturers.captureEnd(o.trails(), o.bookPath, o.desc)
defer o.Close(true)
if err := o.run(cctx); err != nil {
o.capturers.captureResult(o.trails(), o.Result())
return err
}
o.capturers.captureResult(o.trails(), o.Result())
return nil
}
// DumpProfile write run time profile.
func (o *operator) DumpProfile(w io.Writer) error {
r := o.sw.Result()
if r == nil {
return errors.New("no profile")
}
enc := json.NewEncoder(w)
if err := enc.Encode(r); err != nil {
return err
}
return nil
}
// Result returns run result.
func (o *operator) Result() *RunResult {
o.runResult.ID = o.id
return o.runResult
}
func (o *operator) clearResult() {
o.runResult = newRunResult(o.desc, o.bookPathOrID())
o.runResult.ID = o.id
for _, s := range o.steps {
s.clearResult()
}
}
func (o *operator) run(ctx context.Context) error {
defer o.sw.Start(o.trails().toInterfaceSlice()...).Stop()
if o.newOnly {
return errors.New("this runbook is not allowed to run")
}
var err error
if o.t != nil {
// As test helper
o.t.Helper()
o.t.Run(o.testName(), func(t *testing.T) {
t.Helper()
o.thisT = t
if o.loop != nil {
err = o.runLoop(ctx)
} else {
err = o.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(o.runResult)
for ii, p := range paths {
last := p[len(p)-1]
b, err := readFile(last)
if err != nil {
t.Error(errs[ii])
continue
}
idx := indexes[ii]
var fs string
if idx >= 0 {
picked, err := pickStepYAML(string(b), idx)
if err != nil {
t.Error(errs[ii])
continue
}
fs = fmt.Sprintf("Failure step (%s):\n%s\n\n", last, picked)
}
if !strings.HasSuffix(errs[ii].Error(), "\n") {
fs = "\n" + fs
}
t.Errorf("%s%s\n", red(errs[ii]), fs)
}
}
}
})
o.thisT = o.t
if err != nil {
return fmt.Errorf("failed to run %s: %w", o.bookPathOrID(), err)
}
return nil
}
if o.loop != nil {
err = o.runLoop(ctx)
} else {
err = o.runInternal(ctx)
}
if err != nil {
return fmt.Errorf("failed to run %s: %w", o.bookPathOrID(), err)
}
return nil
}
func (o *operator) runLoop(ctx context.Context) error {
if o.loop == nil {
panic("invalid usage")
}
retrySuccess := false
if o.loop.Until == "" {
retrySuccess = true
}
var (
err error
outcome result
bt string
j int
)
c, err := EvalCount(o.loop.Count, o.store.toMap())
if err != nil {
return err
}
var looperr error
for o.loop.Loop(ctx) {
if j >= c {
break
}
if j > 0 {
// Renew runners
for _, r := range o.cdpRunners {
if err := r.Renew(); err != nil {
return err
}
}
}
err = o.runInternal(ctx)
if err != nil {
looperr = multierr.Append(looperr, fmt.Errorf("loop[%d]: %w", j, err))
outcome = resultFailure
} else {
if o.Skipped() {
outcome = resultSkipped
} else {
outcome = resultSuccess
}
}
if o.loop.Until != "" {
store := o.store.toMap()
store[storeOutcomeKey] = string(outcome)
bt, err = buildTree(o.loop.Until, store)
if err != nil {
return fmt.Errorf("loop failed on %s: %w", o.bookPathOrID(), err)
}
tf, err := EvalCond(o.loop.Until, store)
if err != nil {
return fmt.Errorf("loop failed on %s: %w", o.bookPathOrID(), err)
}
if tf {
retrySuccess = true
break
}
}
j++
}
if !retrySuccess {
err := fmt.Errorf("(%s) is not true\n%s", o.loop.Until, bt)
if o.loop.interval != nil {
return fmt.Errorf("retry loop failed on %s.loop (count: %d, interval: %v): %w", o.bookPathOrID(), c, *o.loop.interval, err)
} else {
return fmt.Errorf("retry loop failed on %s.loop (count: %d, minInterval: %v, maxInterval: %v): %w", o.bookPathOrID(), c, *o.loop.minInterval, *o.loop.maxInterval, err)
}
}
if o.loop.Until == "" && looperr != nil {
// simple count
return fmt.Errorf("loop failed on %s: %w", o.bookPathOrID(), looperr)
}
return nil
}
func (o *operator) runInternal(ctx context.Context) (rerr error) {
o.mu.Lock()
defer o.mu.Unlock()
if o.t != nil {
o.t.Helper()
}
o.clearResult()
o.store.clearSteps()
defer func() {
// set run error and skipped
o.runResult.Err = rerr
o.runResult.Skipped = o.Skipped()
o.runResult.Store = o.store.toMap()
o.runResult.StepResults = o.StepResults()
if o.Skipped() {
// If the scenario is skipped, beforeFuncs/afterFuncs are not executed
return
}
// afterFuncs
for i, fn := range o.afterFuncs {
trs := append(o.trails(), Trail{
Type: TrailTypeAfterFunc,
FuncIndex: i,
})
trsi := trs.toInterfaceSlice()
o.sw.Start(trsi...)
if aferr := fn(o.runResult); aferr != nil {
rerr = newAfterFuncError(aferr)
o.runResult.Err = rerr
}
o.sw.Stop(trsi...)
}
}()
// if
if o.ifCond != "" {
tf, err := o.expandCondBeforeRecord(o.ifCond)
if err != nil {
rerr = err
return
}
if !tf {
if err := o.skip(); err != nil {
rerr = err
return
}
return nil
}
}
// beforeFuncs
o.runResult.Store = o.store.toMap()
for i, fn := range o.beforeFuncs {
trs := append(o.trails(), Trail{
Type: TrailTypeBeforeFunc,
FuncIndex: i,
})
trsi := trs.toInterfaceSlice()
o.sw.Start(trsi...)
if err := fn(o.runResult); err != nil {
o.sw.Stop(trsi...)