-
Notifications
You must be signed in to change notification settings - Fork 1
/
yaml_script.go
1267 lines (1177 loc) · 32.6 KB
/
yaml_script.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 main
import (
//"bytes"
"errors"
"fmt"
"log/slog"
"reflect"
"strings"
"text/template"
"gopkg.in/yaml.v3"
)
type YAMLScript struct {
// name string `yaml:"name"`
Actions ActionsList `yaml:"actions" json:"actions,omitempty"`
UntilLimit int `yaml:"until_limit" json:"until_limit,omitempty"`
name string
customTemplate *template.Template
metricsActions []*MetricsAction
setStatsActions []*SetStatsAction
}
// type DumpYAMLScript struct {
// Actions ActionsList `yaml:"actions" json:"actions,omitempty"`
// UntilLimit int `yaml:"until_limit,omitempty" json:"until_limit,omitempty"`
// }
//******************************************************************
//**
//******************************************************************
const (
base_action = iota
set_fact_action = iota
actions_action = iota
debug_action = iota
query_action = iota
metrics_action = iota
metric_action = iota
play_script_action = iota
set_stats = iota
)
type GetMetricsRes struct {
mc []*MetricConfig
maprefix string
}
type Action interface {
BaseAction
Type() int
setBasicElement(nameField *Field, vars [][]any, with []any, loopVar string, when []*exporterTemplate, until []*exporterTemplate) error
PlayAction(script *YAMLScript, symtab map[string]any, logger *slog.Logger) error
CustomAction(script *YAMLScript, symtab map[string]any, logger *slog.Logger) error
// only for MetricsAction
GetMetrics() []*GetMetricsRes
// only for MetricAction
GetMetric() *MetricConfig
SetMetricFamily(*MetricFamily)
// only for PlayAction
SetPlayAction(scripts map[string]*YAMLScript) error
AddCustomTemplate(customTemplate *exporterTemplate) error
}
type ActionsList []Action
func (sc *YAMLScript) Play(symtab map[string]any, ignore_errors bool, logger *slog.Logger) error {
symtab["__name__"] = sc.name
for _, ac := range sc.Actions {
err := ac.PlayAction(sc, symtab, logger)
if !ignore_errors && err != nil {
return err
}
}
return nil
}
func (sc *YAMLScript) AddCustomTemplate(customTemplate *exporterTemplate) error {
for _, ac := range sc.Actions {
err := ac.AddCustomTemplate(customTemplate)
if err != nil {
return err
}
}
return nil
}
func CollectorId(symtab map[string]any, logger *slog.Logger) string {
raw_id, ok := symtab["__collector_id"]
if !ok {
logger.Warn("invalid collector id")
return ""
}
str, ok := raw_id.(string)
if !ok {
logger.Warn("invalid collector id")
return ""
}
return str
}
func ScriptName(symtab map[string]any, logger *slog.Logger) string {
raw_name, ok := symtab["__name__"]
if !ok {
logger.Warn("invalid script name")
return ""
}
str, ok := raw_name.(string)
if !ok {
logger.Warn("invalid script name type")
return ""
}
return str
}
func Name(name *Field, symtab map[string]any, logger *slog.Logger) string {
str, err := name.GetValueString(symtab, nil, false)
if err != nil {
logger.Warn(fmt.Sprintf("invalid action name: %v", err))
return ""
}
return str
}
type BaseAction interface {
GetName(symtab map[string]any, logger *slog.Logger) string
GetNameField() *Field
SetNameField(*Field)
GetWidh() []any
SetWidth([]any)
GetWhen() []*exporterTemplate
SetWhen([]*exporterTemplate)
GetLoopVar() string
SetLoopVar(string)
GetVars() [][]any
SetVars([][]any)
GetUntil() []*exporterTemplate
SetUntil([]*exporterTemplate)
}
func setBasicElement(
ba BaseAction,
nameField *Field,
vars [][]any,
with []any,
loopVar string,
when []*exporterTemplate,
until []*exporterTemplate) error {
if nameField != nil {
ba.SetNameField(nameField)
}
if len(vars) > 0 {
ba.SetVars(vars)
}
if len(with) > 0 {
// have to check every element in the slide
// build a Field for each.
baWith := make([]any, len(with))
for idx, elmt := range with {
switch curval := elmt.(type) {
case string:
tt := strings.LastIndex(curval, "}}")
if tt != -1 {
curval = curval[:tt] + " | toRawJson " + curval[tt:]
}
field, err := NewField(curval, nil)
if err != nil {
return err
}
baWith[idx] = field
case map[any]any:
baWith[idx] = elmt
case int:
tmp := fmt.Sprintf("%d", curval)
field, err := NewField(tmp, nil)
if err != nil {
return err
}
baWith[idx] = field
case *Field:
baWith[idx] = curval
default:
return fmt.Errorf("with_items: invalid type: '%s'", reflect.TypeOf(elmt))
}
}
ba.SetWidth(baWith)
if loopVar != "" {
ba.SetLoopVar(loopVar)
}
// ba.With = with
}
if len(when) > 0 {
ba.SetWhen(when)
}
if len(until) > 0 {
ba.SetUntil(until)
}
return nil
}
func AddCustomTemplateElement(item any, customTemplate *exporterTemplate) error {
switch curval := item.(type) {
case *Field:
if curval != nil {
if err := curval.AddDefaultTemplate(customTemplate); err != nil {
return err
}
}
case map[any]any:
if curval == nil {
return nil
}
for r_key, r_value := range curval {
if err := AddCustomTemplateElement(r_key, customTemplate); err != nil {
return err
}
if err := AddCustomTemplateElement(r_value, customTemplate); err != nil {
return err
}
}
case []any:
if curval == nil {
return nil
}
for _, r_value := range curval {
if err := AddCustomTemplateElement(r_value, customTemplate); err != nil {
return err
}
}
default:
// value is a constant 1 float or bool... nothing to do
}
return nil
}
func AddCustomTemplate(ba BaseAction, customTemplate *exporterTemplate) error {
name := ba.GetNameField()
if name != nil {
if err := name.AddDefaultTemplate(customTemplate); err != nil {
return err
}
}
baWith := ba.GetWidh()
for idx, with := range baWith {
if err := AddCustomTemplateElement(with, customTemplate); err != nil {
return fmt.Errorf("error in with[%d]: %s", idx, err)
}
}
baUntil := ba.GetUntil()
for idx, until_tmpl := range baUntil {
if tmpl, err := AddDefaultTemplate(until_tmpl, customTemplate); err != nil {
return fmt.Errorf("error in until[%d]: %s", idx, err)
} else {
baUntil[idx] = tmpl
}
}
baWhen := ba.GetWhen()
for idx, when_tmpl := range baWhen {
if tmpl, err := AddDefaultTemplate(when_tmpl, customTemplate); err != nil {
return fmt.Errorf("error in when[%d]: %s", idx, err)
} else {
baWhen[idx] = tmpl
}
}
return nil
}
// ********************************************************************************
func ValorizeValue(symtab map[string]any, item any, logger *slog.Logger, action_name string, cur_level int) (any, error) {
var data any
var err error
switch curval := item.(type) {
case *Field:
check_value := false
if cur_level == 0 {
// this is a template populate list with var from symtab
data, err = curval.GetValueObject(symtab)
if err != nil {
return data, err
}
if data == nil {
check_value = true
} else if r_data, ok := data.([]any); ok {
if r_data == nil {
check_value = true
}
} else if s_data, ok := data.(string); ok {
if s_data == "" {
data = nil
}
}
} else {
check_value = true
}
if check_value {
data, err = curval.GetValueString(symtab, nil, false)
}
return data, err
case map[any]any:
ldata := make(map[string]any, len(curval))
for r_key, r_value := range curval {
key, err := ValorizeValue(symtab, r_key, logger, action_name, cur_level+1)
if err != nil {
logger.Warn(
fmt.Sprintf("error building map key: %v", r_key),
"errmsg", err,
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", action_name)
continue
}
key_val := ""
if r_key_val, ok := key.(string); ok {
key_val = r_key_val
} else {
continue
}
value, err := ValorizeValue(symtab, r_value, logger, action_name, cur_level+1)
if err != nil {
logger.Warn(
fmt.Sprintf("error building map value for key '%s'", key_val),
"errmsg", err,
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", action_name)
continue
}
if err := SetSymTab(ldata, key_val, value); err != nil {
logger.Warn(
fmt.Sprintf("error setting map value for key '%s'", key_val),
"errmsg", err,
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", action_name)
continue
}
}
data = ldata
case []any:
ldata := make([]any, len(curval))
for idx, r_value := range curval {
values, err := ValorizeValue(symtab, r_value, logger, action_name, cur_level+1)
if err != nil {
logger.Warn(
fmt.Sprintf("error building list value for index: %d", idx),
"errmsg", err,
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", action_name)
continue
}
ldata[idx] = values
}
data = ldata
default:
// do nothing on value: bool, int64, float64, string
data = curval
}
return data, nil
}
func DeleteSymtab(symtab map[string]any, key_name string) error {
var err error
tmp_symtab := symtab
scope := key_name
if scope[0] == '.' {
scope = scope[1:]
}
vars := strings.Split(scope, ".")
last_elmt := len(vars) - 1
for i, var_name := range vars {
if raw_value, ok := tmp_symtab[var_name]; ok {
switch cur_value := raw_value.(type) {
case map[string]any:
if i == last_elmt {
delete(tmp_symtab, var_name)
break
}
tmp_symtab = cur_value
default:
if i != last_elmt {
err = fmt.Errorf("can't set scope: '%s' has invalid type", var_name)
break
}
}
} else {
break
}
}
return err
}
func SetSymTab(symtab map[string]any, key_name string, value any) error {
var err error
tmp_symtab := symtab
scope := key_name
if scope[0] == '.' {
scope = scope[1:]
}
vars := strings.Split(scope, ".")
last_elmt := len(vars) - 1
for i, var_name := range vars {
if i == last_elmt {
tmp_symtab[var_name] = value
break
}
if raw_value, ok := tmp_symtab[var_name]; ok {
switch cur_value := raw_value.(type) {
case map[string]any:
tmp_symtab = cur_value
default:
if i != last_elmt {
err = fmt.Errorf("can't set scope: '%s' has invalid type", var_name)
break
}
}
} else {
// key doesn't exist currently: add it
cur_value := make(map[string]any)
tmp_symtab[var_name] = cur_value
tmp_symtab = cur_value
}
}
return err
}
func preserve_sym_tab(symtab map[string]any, old_values map[string]any, key string, val any) error {
if old_val, ok := symtab[key]; ok {
if err := SetSymTab(old_values, key, old_val); err != nil {
return err
}
} else {
if err := SetSymTab(old_values, key, "_"); err != nil {
return err
}
}
if err := SetSymTab(symtab, key, val); err != nil {
return err
}
return nil
}
func evalCond(symtab map[string]any, condTpl *exporterTemplate) (cond bool, err error) {
cond = false
defer func() {
// res and err are named out parameters, so if we set value for them in defer
// set the returned values
ok := false
if r := recover(); r != nil {
if err, ok = r.(error); !ok {
err = errors.New("panic in evalCond template with undefined error")
}
}
}()
tmp_res := new(strings.Builder)
err = ((*template.Template)(condTpl)).Execute(tmp_res, &symtab)
if err != nil {
return false, err
}
if tmp_res.String() == "true" {
cond = true
}
return cond, nil
}
func PlayBaseAction(script *YAMLScript, symtab map[string]any, logger *slog.Logger, ba Action, customAction func(*YAMLScript, map[string]any, *slog.Logger) error) error {
// to preverse values from symtab
old_values := make(map[string]any)
defer func() {
for key, val := range old_values {
if val == "_" {
delete(symtab, key)
} else {
symtab[key] = val
}
}
}()
// add the local vars from the action to symbols table
baVars := ba.GetVars()
if len(baVars) > 0 {
for _, pair := range baVars {
if pair == nil {
logger.Warn(
"invalid key value pair for vars",
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
continue
}
if key, ok := pair[0].(*Field); ok {
key_name, err := key.GetValueString(symtab, nil, false)
if err == nil {
value, err := ValorizeValue(symtab, pair[1], logger, ba.GetName(symtab, logger), 0)
if err == nil {
if value != nil {
add_symbol := true
if s_value, ok := value.(string); ok {
if s_value == "_" {
DeleteSymtab(symtab, key_name)
logger.Debug(
fmt.Sprintf("vars(%s) has '_' value (removed)", key_name),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
add_symbol = false
}
}
if add_symbol {
if err := preserve_sym_tab(symtab, old_values, key_name, value); err != nil {
logger.Warn(
fmt.Sprintf("error preserve symtab (%s): %s", key_name, err),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
}
}
} else {
DeleteSymtab(symtab, key_name)
logger.Debug(
fmt.Sprintf("vars(%s) has nil value (removed)", key_name),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
}
} else {
logger.Warn(
fmt.Sprintf("no data found for vars(%s): %s", key, err),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
}
} else {
logger.Warn(
fmt.Sprintf("no data found for vars: %s", err),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
}
}
}
}
var items []any
var loop_var string
do_loop := false
set_loops_var := false
final_items := make([]any, 0)
baWith := ba.GetWidh()
if len(baWith) > 0 {
// build a list of element from ba.With list of Field
items = baWith
for _, item := range items {
data, err := ValorizeValue(symtab, item, logger, ba.GetName(symtab, logger), 0)
if err == nil {
if data != nil {
if l_data, ok := data.([]any); ok {
if len(l_data) > 0 {
final_items = append(final_items, l_data...)
} else {
logger.Warn(
"with_items list empty.",
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
}
} else {
if s_data, ok := data.(string); ok {
if s_data != "null" {
final_items = append(final_items, data)
}
} else {
final_items = append(final_items, data)
}
}
}
} else {
logger.Warn(
fmt.Sprintf("no data found for with_items: %s", err),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
}
}
items = final_items
baLoopVar := ba.GetLoopVar()
if baLoopVar != "" {
loop_var = baLoopVar
} else {
loop_var = "item"
}
set_loops_var = true
} else if len(ba.GetUntil()) > 0 {
do_loop = true
} else {
items = make([]any, 1)
items[0] = 0
}
if !do_loop {
// loop on items
for idx, item := range items {
if set_loops_var {
if err := preserve_sym_tab(symtab, old_values, loop_var, item); err != nil {
logger.Warn(
fmt.Sprintf("error preserve symtab (%s): %s", loop_var, err),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
}
preserve_sym_tab(symtab, old_values, "loop_var_idx", idx)
preserve_sym_tab(symtab, old_values, "loop_var", loop_var)
}
// check if there are condition on the "item" loop;
// if one is false break item the loop on next.
baWhen := ba.GetWhen()
if len(baWhen) > 0 {
valid_value := true
for i, condTpl := range baWhen {
cond, err := evalCond(symtab, condTpl)
if err != nil {
return fmt.Errorf("invalid template value for 'when' %s: %s", baWhen[i].Tree.Root.String(), err)
}
if !cond {
logger.Debug(
fmt.Sprintf("skipped: when condition false: '%s'", baWhen[i].Tree.Root.String()),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
valid_value = false
break
}
}
if !valid_value {
continue
}
}
err := customAction(script, symtab, logger)
if err != nil {
return err
}
}
} else {
idx := 0
for {
if set_loops_var {
preserve_sym_tab(symtab, old_values, "loop_var_idx", idx)
// symtab["loop_var_idx"] = idx
}
valid_value := true
baUntil := ba.GetUntil()
for i, condTpl := range baUntil {
cond, err := evalCond(symtab, condTpl)
if err != nil {
err := fmt.Errorf("invalid template value for 'until' %s: %s", baUntil[i].Tree.Root.String(), err)
logger.Warn(
err.Error(),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
return err
}
if !cond {
logger.Debug(
fmt.Sprintf("Name: '%s' until limit cond reached : '%s'", ba.GetName(symtab, logger), baUntil[i].Tree.Root.String()),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
valid_value = false
break
}
}
if !valid_value || idx >= script.UntilLimit {
if idx >= script.UntilLimit {
logger.Warn(
fmt.Sprintf("max iteration reached for until action (%d)", script.UntilLimit),
"collid", CollectorId(symtab, logger),
"script", ScriptName(symtab, logger),
"name", ba.GetName(symtab, logger))
}
break
}
idx += 1
err := customAction(script, symtab, logger)
if err != nil {
return err
}
}
}
return nil
}
// ***************************************************************************************
// ***************************************************************************************
// yaml script parser
// ***************************************************************************************
// ***************************************************************************************
// parse all possible actions in a yaml script.
//
// * debug: msg: test{{ go template}}
//
// * set_fact: vars to set in symbols table
//
// * query: play url to the target and set resulting json obj the sybols table
//
// * metrics: define a list of metric (metric_name) to generate for the exporter
//
// * actions: define a list of subaction to play: query, metrics...
//
// * play_script: play the script
//
// * metric_name: a metric definition
type tmpActions []map[string]yaml.Node
func build_WithItems(raw yaml.Node) ([]any, error) {
var listElmt []any
if raw.Tag == "!!str" {
with_field, err := NewField(raw.Value, nil)
if err != nil {
return nil, fmt.Errorf("invalid template for var name (set_fact) %q: %s", raw.Value, err)
}
listElmt = make([]any, 1)
listElmt[0] = with_field
} else if raw.Tag == "!!map" {
var (
raw_mapElmt map[string]any
mapElmt map[any]any
err error
)
if err = raw.Decode(&raw_mapElmt); err != nil {
return nil, err
}
if mapElmt, err = buildMapField(raw_mapElmt); err != nil {
return nil, err
}
listElmt = make([]any, 1)
listElmt[0] = mapElmt
} else if raw.Tag == "!!seq" {
var (
str_listElmt []any
err error
)
if err = raw.Decode(&str_listElmt); err != nil {
return nil, err
}
if listElmt, err = buildSliceField(str_listElmt); err != nil {
return nil, err
}
} else {
listElmt = make([]any, 0)
}
return listElmt, nil
}
func build_Cond(script *YAMLScript, raw yaml.Node) ([]*exporterTemplate, error) {
var listElmt []string
var when []*exporterTemplate
if raw.Tag == "!!str" {
listElmt = make([]string, 1)
listElmt[0] = raw.Value
} else if raw.Tag == "!!seq" {
if err := raw.Decode(&listElmt); err != nil {
return nil, err
}
} else {
listElmt = make([]string, 0)
}
if len(listElmt) > 0 {
when = make([]*exporterTemplate, len(listElmt))
for i, cond := range listElmt {
var tmpl *template.Template
var err error
if !strings.Contains(cond, "{{") {
cond = "{{ " + cond + " }}"
}
// alter the when conditions to add custom templates/funcs if exist
if script.customTemplate != nil {
tmpl, err = script.customTemplate.Clone()
if err != nil {
return nil, fmt.Errorf("for script %s template clone error: %s", script.name, err)
}
} else {
tmpl = template.New("cond").Funcs(mymap())
}
tmpl, err = tmpl.Parse(cond)
if err != nil {
return nil, fmt.Errorf("for script %s template %s is invalid: %s", script.name, cond, err)
}
when[i] = (*exporterTemplate)(tmpl)
}
}
return when, nil
}
func buildMapField(raw_maps map[string]any) (map[any]any, error) {
var err error
final_res := make(map[any]any)
for key, r_value := range raw_maps {
res, err := buildFields(key, r_value)
if err != nil {
return nil, fmt.Errorf("invalid template for var key %s: %s", key, err)
}
for key, val := range res {
final_res[key] = val
}
}
return final_res, err
}
func buildSliceField(raw_slice []any) ([]any, error) {
var err error
final_res := make([]any, len(raw_slice))
for idx, r_value := range raw_slice {
res, err := buildValueField(r_value)
if err != nil {
return nil, fmt.Errorf("invalid template for var key %q: %s", res, err)
}
final_res[idx] = res
}
return final_res, err
}
func buildFields(key string, val any) (map[any]any, error) {
var err error
var key_field *Field
var value_field any
// Check required fields
res := make(map[any]any)
key_field, err = NewField(key, nil)
if err != nil {
return nil, fmt.Errorf("invalid template for var name (set_fact) %q: %s", key, err)
}
value_field, err = buildValueField(val)
if err != nil {
return nil, fmt.Errorf("invalid template for var name (set_fact) %q: %s", key, err)
}
res[key_field] = value_field
return res, nil
}
func buildValueField(val any) (any, error) {
switch curval := val.(type) {
case string:
value_field, err := NewField(curval, nil)
if err != nil {
return nil, fmt.Errorf("invalid template for var value (set_fact) %q: %s", curval, err)
}
return value_field, nil
// value is a map
case map[string]any:
tmp, err := buildMapField(curval)
if err != nil {
return nil, fmt.Errorf("invalid template for map value (set_fact) %q: %s", curval, err)
}
return tmp, nil
// value is a slice
case []any:
tmp, err := buildSliceField(curval)
if err != nil {
return nil, fmt.Errorf("invalid template for map value (set_fact) %q: %s", curval, err)
}
return tmp, nil
// a value int float... what else ?
default:
return curval, nil
}
}
// UnmarshalYAML implements the yaml.Unmarshaler interface for YAMLScript.
func (script *YAMLScript) UnmarshalYAML(value *yaml.Node) error {
var tmp tmpActions
if err := value.Decode(&tmp); err != nil {
return err
}
actions, err := ActionsListDecode(script, make(ActionsList, 0, len(tmp)), tmp, value)
if err != nil {
return err
}
script.Actions = actions
script.UntilLimit = 20
return nil
}
func ActionsListDecode(script *YAMLScript, actions ActionsList, tmp tmpActions, parentNode *yaml.Node) (ActionsList, error) {
main_checker := map[string]bool{
"name": true,
"loop": true,
"loop_var": true,
"vars": true,
"until": true,
"when": true,
"with_items": true,
}
for i := range tmp {
var name *Field
var nameVal, loopVar string
var with_items []any
var until, when []*exporterTemplate
var vars [][]any
var err error
checker := main_checker
skip_checker := false
cur_act := tmp[i]
// parse name
if raw, ok := cur_act["name"]; ok {
nameVal = raw.Value
name, err = NewField(nameVal, nil)
if err != nil {
return nil, fmt.Errorf("name for action invalid %q: %s", raw.Value, err)
}
}
// parse vars
if raw, ok := cur_act["vars"]; ok {
if raw.Tag == "!!map" {
var tmp_vars map[string]any
if err := raw.Decode(&tmp_vars); err != nil {
return nil, err
}
idx := 0
vars = make([][]any, len(tmp_vars))
for key, val := range tmp_vars {
// Check required fields
vars[idx] = make([]any, 2)
if new_map, err := buildFields(key, val); err != nil {
return nil, err
} else {
for key, val := range new_map {
vars[idx][0] = key
vars[idx][1] = val
}
}
idx++
}
}
}
// parse with_items
if raw, ok := cur_act["with_items"]; ok {
listElmt, err := build_WithItems(raw)
if err != nil {
return nil, err
}
with_items = listElmt
} else if raw, ok := cur_act["loop"]; ok {
listElmt, err := build_WithItems(raw)
if err != nil {
return nil, err
}
with_items = listElmt
}
if with_items != nil {
// parse loop_var
if raw, ok := cur_act["loop_var"]; ok {
loopVar = raw.Value
}
}
// parse when
if raw, ok := cur_act["when"]; ok {
cond, err := build_Cond(script, raw)
if err != nil {
return nil, err
}