forked from argoproj/argo-workflows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
1375 lines (1260 loc) · 49.7 KB
/
validate.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 validate
import (
"encoding/json"
"fmt"
"io"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/robfig/cron/v3"
"github.com/sirupsen/logrus"
"github.com/valyala/fasttemplate"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
apivalidation "k8s.io/apimachinery/pkg/util/validation"
"sigs.k8s.io/yaml"
"github.com/argoproj/argo/errors"
wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo/util"
"github.com/argoproj/argo/util/help"
"github.com/argoproj/argo/util/intstr"
"github.com/argoproj/argo/workflow/artifacts/hdfs"
"github.com/argoproj/argo/workflow/common"
"github.com/argoproj/argo/workflow/metrics"
"github.com/argoproj/argo/workflow/templateresolution"
)
// ValidateOpts provides options when linting
type ValidateOpts struct {
// Lint indicates if this is performing validation in the context of linting. If true, will
// skip some validations which is permissible during linting but not submission (e.g. missing
// input parameters to the workflow)
Lint bool
// ContainerRuntimeExecutor will trigger additional validation checks specific to different
// types of executors. For example, the inability of kubelet/k8s executors to copy artifacts
// out of the base image layer. If unspecified, will use docker executor validation
ContainerRuntimeExecutor string
// IgnoreEntrypoint indicates to skip/ignore the EntryPoint validation on workflow spec.
// Entrypoint is optional for WorkflowTemplate and ClusterWorkflowTemplate
IgnoreEntrypoint bool
// WorkflowTemplateValidation indicates that the current context is validating a WorkflowTemplate or ClusterWorkflowTemplate
WorkflowTemplateValidation bool
}
// templateValidationCtx is the context for validating a workflow spec
type templateValidationCtx struct {
ValidateOpts
// globalParams keeps track of variables which are available the global
// scope and can be referenced from anywhere.
globalParams map[string]string
// results tracks if validation has already been run on a template
results map[string]bool
// wf is the Workflow resource which is used to validate templates.
// It will be omitted in WorkflowTemplate validation.
wf *wfv1.Workflow
}
func newTemplateValidationCtx(wf *wfv1.Workflow, opts ValidateOpts) *templateValidationCtx {
globalParams := make(map[string]string)
globalParams[common.GlobalVarWorkflowName] = placeholderGenerator.NextPlaceholder()
globalParams[common.GlobalVarWorkflowNamespace] = placeholderGenerator.NextPlaceholder()
globalParams[common.GlobalVarWorkflowServiceAccountName] = placeholderGenerator.NextPlaceholder()
globalParams[common.GlobalVarWorkflowUID] = placeholderGenerator.NextPlaceholder()
return &templateValidationCtx{
ValidateOpts: opts,
globalParams: globalParams,
results: make(map[string]bool),
wf: wf,
}
}
const (
// anyItemMagicValue is a magic value set in addItemsToScope() and checked in
// resolveAllVariables() to determine if any {{item.name}} can be accepted during
// variable resolution (to support withParam)
anyItemMagicValue = "item.*"
anyWorkflowOutputParameterMagicValue = "workflow.outputs.parameters.*"
anyWorkflowOutputArtifactMagicValue = "workflow.outputs.artifacts.*"
)
var (
placeholderGenerator = common.NewPlaceholderGenerator()
)
type FakeArguments struct{}
func (args *FakeArguments) GetParameterByName(name string) *wfv1.Parameter {
s := placeholderGenerator.NextPlaceholder()
return &wfv1.Parameter{Name: name, Value: &s}
}
func (args *FakeArguments) GetArtifactByName(name string) *wfv1.Artifact {
return &wfv1.Artifact{Name: name}
}
var _ wfv1.ArgumentsProvider = &FakeArguments{}
// ValidateWorkflow accepts a workflow and performs validation against it.
func ValidateWorkflow(wftmplGetter templateresolution.WorkflowTemplateNamespacedGetter, cwftmplGetter templateresolution.ClusterWorkflowTemplateGetter, wf *wfv1.Workflow, opts ValidateOpts) (*wfv1.Conditions, error) {
wfConditions := &wfv1.Conditions{}
ctx := newTemplateValidationCtx(wf, opts)
tmplCtx := templateresolution.NewContext(wftmplGetter, cwftmplGetter, wf, wf)
var wfSpecHolder wfv1.WorkflowSpecHolder
var wfTmplRef *wfv1.TemplateRef
var err error
entrypoint := wf.Spec.Entrypoint
hasWorkflowTemplateRef := wf.Spec.WorkflowTemplateRef != nil
if hasWorkflowTemplateRef {
err := ValidateWorkflowTemplateRefFields(wf.Spec)
if err != nil {
return nil, err
}
if wf.Spec.WorkflowTemplateRef.ClusterScope {
wfSpecHolder, err = cwftmplGetter.Get(wf.Spec.WorkflowTemplateRef.Name)
} else {
wfSpecHolder, err = wftmplGetter.Get(wf.Spec.WorkflowTemplateRef.Name)
}
if err != nil {
return nil, err
}
if entrypoint == "" {
entrypoint = wfSpecHolder.GetWorkflowSpec().Entrypoint
}
wfTmplRef = wf.Spec.WorkflowTemplateRef.ToTemplateRef(entrypoint)
}
err = validateWorkflowFieldNames(wf.Spec.Templates)
wfArgs := wf.Spec.Arguments
if wf.Spec.WorkflowTemplateRef != nil {
wfArgs.Parameters = util.MergeParameters(wfArgs.Parameters, wfSpecHolder.GetWorkflowSpec().Arguments.Parameters)
}
if err != nil {
return nil, errors.Errorf(errors.CodeBadRequest, "spec.templates%s", err.Error())
}
if ctx.Lint {
// if we are just linting we don't care if spec.arguments.parameters.XXX doesn't have an
// explicit value. workflows without a default value is a desired use case
err = validateArgumentsFieldNames("spec.arguments.", wfArgs)
} else {
err = validateArguments("spec.arguments.", wfArgs)
}
if err != nil {
return nil, err
}
if len(wfArgs.Parameters) > 0 {
ctx.globalParams[common.GlobalVarWorkflowParameters] = placeholderGenerator.NextPlaceholder()
}
for _, param := range wfArgs.Parameters {
if param.Name != "" {
if param.Value != nil {
ctx.globalParams["workflow.parameters."+param.Name] = *param.Value
} else {
ctx.globalParams["workflow.parameters."+param.Name] = placeholderGenerator.NextPlaceholder()
}
}
}
for k := range wf.ObjectMeta.Annotations {
ctx.globalParams["workflow.annotations."+k] = placeholderGenerator.NextPlaceholder()
}
for k := range wf.ObjectMeta.Labels {
ctx.globalParams["workflow.labels."+k] = placeholderGenerator.NextPlaceholder()
}
if wf.Spec.Priority != nil {
ctx.globalParams[common.GlobalVarWorkflowPriority] = strconv.Itoa(int(*wf.Spec.Priority))
}
if !opts.IgnoreEntrypoint && entrypoint == "" {
return nil, errors.New(errors.CodeBadRequest, "spec.entrypoint is required")
}
// Make sure that templates are not defined with deprecated fields
for _, template := range wf.Spec.Templates {
if !template.Arguments.IsEmpty() {
logrus.Warn("template.arguments is deprecated and its contents are ignored")
wfConditions.UpsertConditionMessage(wfv1.Condition{
Type: wfv1.ConditionTypeSpecWarning,
Status: v1.ConditionTrue,
Message: fmt.Sprintf(`template.arguments is deprecated and its contents are ignored. See more: %s`, help.WorkflowTemplatesReferencingOtherTemplates),
})
}
if template.TemplateRef != nil {
logrus.Warn(getTemplateRefHelpString(&template))
wfConditions.UpsertConditionMessage(wfv1.Condition{
Type: wfv1.ConditionTypeSpecWarning,
Status: v1.ConditionTrue,
Message: fmt.Sprintf(`Referencing/calling other templates directly on a "template" is deprecated; they should be referenced in a "steps" or a "dag" template. See more: %s`, help.WorkflowTemplatesReferencingOtherTemplates),
})
}
if template.Template != "" {
logrus.Warn(getTemplateRefHelpString(&template))
wfConditions.UpsertConditionMessage(wfv1.Condition{
Type: wfv1.ConditionTypeSpecWarning,
Status: v1.ConditionTrue,
Message: fmt.Sprintf(`Referencing/calling other templates directly on a "template" is deprecated; they should be referenced in a "steps" or a "dag" template. See more: %s`, help.WorkflowTemplatesReferencingOtherTemplates),
})
}
}
if !opts.IgnoreEntrypoint {
var args wfv1.ArgumentsProvider
args = &wfArgs
if opts.WorkflowTemplateValidation {
args = &FakeArguments{}
}
tmpl := &wfv1.WorkflowStep{Template: entrypoint}
if hasWorkflowTemplateRef {
tmpl = &wfv1.WorkflowStep{TemplateRef: wfTmplRef}
}
_, err = ctx.validateTemplateHolder(tmpl, tmplCtx, args, map[string]interface{}{})
if err != nil {
return nil, err
}
}
if wf.Spec.OnExit != "" {
// now when validating onExit, {{workflow.status}} is now available as a global
ctx.globalParams[common.GlobalVarWorkflowStatus] = placeholderGenerator.NextPlaceholder()
ctx.globalParams[common.GlobalVarWorkflowFailures] = placeholderGenerator.NextPlaceholder()
_, err = ctx.validateTemplateHolder(&wfv1.WorkflowStep{Template: wf.Spec.OnExit}, tmplCtx, &wf.Spec.Arguments, map[string]interface{}{})
if err != nil {
return nil, err
}
}
if wf.Spec.PodGC != nil {
switch wf.Spec.PodGC.Strategy {
case wfv1.PodGCOnPodCompletion, wfv1.PodGCOnPodSuccess, wfv1.PodGCOnWorkflowCompletion, wfv1.PodGCOnWorkflowSuccess:
default:
return nil, errors.Errorf(errors.CodeBadRequest, "podGC.strategy unknown strategy '%s'", wf.Spec.PodGC.Strategy)
}
}
// Check if all templates can be resolved.
for _, template := range wf.Spec.Templates {
_, err := ctx.validateTemplateHolder(&wfv1.WorkflowStep{Template: template.Name}, tmplCtx, &FakeArguments{}, map[string]interface{}{})
if err != nil {
return nil, errors.Errorf(errors.CodeBadRequest, "templates.%s %s", template.Name, err.Error())
}
}
return wfConditions, nil
}
func ValidateWorkflowTemplateRefFields(wfSpec wfv1.WorkflowSpec) error {
if len(wfSpec.Templates) > 0 {
return errors.Errorf(errors.CodeBadRequest, "Templates is invalid field in spec if workflow referred WorkflowTemplate reference")
}
return nil
}
// ValidateWorkflowTemplate accepts a workflow template and performs validation against it.
func ValidateWorkflowTemplate(wftmplGetter templateresolution.WorkflowTemplateNamespacedGetter, cwftmplGetter templateresolution.ClusterWorkflowTemplateGetter, wftmpl *wfv1.WorkflowTemplate) (*wfv1.Conditions, error) {
wf := &wfv1.Workflow{
ObjectMeta: v1.ObjectMeta{
Labels: wftmpl.ObjectMeta.Labels,
Annotations: wftmpl.ObjectMeta.Annotations,
},
Spec: wftmpl.Spec.WorkflowSpec,
}
return ValidateWorkflow(wftmplGetter, cwftmplGetter, wf, ValidateOpts{IgnoreEntrypoint: wf.Spec.Entrypoint == "", WorkflowTemplateValidation: true})
}
// ValidateClusterWorkflowTemplate accepts a cluster workflow template and performs validation against it.
func ValidateClusterWorkflowTemplate(wftmplGetter templateresolution.WorkflowTemplateNamespacedGetter, cwftmplGetter templateresolution.ClusterWorkflowTemplateGetter, cwftmpl *wfv1.ClusterWorkflowTemplate) (*wfv1.Conditions, error) {
wf := &wfv1.Workflow{
ObjectMeta: v1.ObjectMeta{
Labels: cwftmpl.ObjectMeta.Labels,
Annotations: cwftmpl.ObjectMeta.Annotations,
},
Spec: cwftmpl.Spec.WorkflowSpec,
}
return ValidateWorkflow(wftmplGetter, cwftmplGetter, wf, ValidateOpts{IgnoreEntrypoint: wf.Spec.Entrypoint == "", WorkflowTemplateValidation: true})
}
// ValidateCronWorkflow validates a CronWorkflow
func ValidateCronWorkflow(wftmplGetter templateresolution.WorkflowTemplateNamespacedGetter, cwftmplGetter templateresolution.ClusterWorkflowTemplateGetter, cronWf *wfv1.CronWorkflow) error {
if _, err := cron.ParseStandard(cronWf.Spec.Schedule); err != nil {
return errors.Errorf(errors.CodeBadRequest, "cron schedule is malformed: %s", err)
}
switch cronWf.Spec.ConcurrencyPolicy {
case wfv1.AllowConcurrent, wfv1.ForbidConcurrent, wfv1.ReplaceConcurrent, "":
// Do nothing
default:
return errors.Errorf(errors.CodeBadRequest, "'%s' is not a valid concurrencyPolicy", cronWf.Spec.ConcurrencyPolicy)
}
if cronWf.Spec.StartingDeadlineSeconds != nil && *cronWf.Spec.StartingDeadlineSeconds < 0 {
return errors.Errorf(errors.CodeBadRequest, "startingDeadlineSeconds must be positive")
}
wf := common.ConvertCronWorkflowToWorkflow(cronWf)
_, err := ValidateWorkflow(wftmplGetter, cwftmplGetter, wf, ValidateOpts{})
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "cannot validate Workflow: %s", err)
}
return nil
}
func getTemplateRefHelpString(tmpl *wfv1.Template) string {
out := `Referencing/calling other templates directly on a "template" is deprecated, no longer supported, and will be removed in a future version.
Templates should be referenced from within a "steps" or a "dag" template. Here is how you would reference this on a "steps" template:
- name: %s
steps:
- - name: call-%s`
if tmpl.TemplateRef != nil {
out += `
templateRef:
name: %s
template: %s`
out = fmt.Sprintf(out, tmpl.Name, tmpl.TemplateRef.Template, tmpl.TemplateRef.Name, tmpl.TemplateRef.Template)
if tmpl.TemplateRef.RuntimeResolution {
out += `
runtimeResolution: %t`
out = fmt.Sprintf(out, tmpl.TemplateRef.RuntimeResolution)
}
} else if tmpl.Template != "" {
out += `
template: %s`
out = fmt.Sprintf(out, tmpl.Name, tmpl.Template, tmpl.Template)
}
if !tmpl.Inputs.IsEmpty() {
out += `
arguments: # Inputs should be converted to arguments`
inputBytes, err := yaml.Marshal(tmpl.Inputs)
if err != nil {
panic(err)
}
for _, line := range strings.Split(string(inputBytes), "\n") {
out += `
` + line
}
}
out += `
For more information, see: %s
`
out = fmt.Sprintf(out, help.WorkflowTemplatesReferencingOtherTemplates)
return out
}
func (ctx *templateValidationCtx) validateTemplate(tmpl *wfv1.Template, tmplCtx *templateresolution.Context, args wfv1.ArgumentsProvider, extraScope map[string]interface{}) error {
if err := validateTemplateType(tmpl); err != nil {
return err
}
scope, err := validateInputs(tmpl, extraScope)
if err != nil {
return err
}
localParams := make(map[string]string)
if tmpl.IsPodType() {
localParams[common.LocalVarPodName] = placeholderGenerator.NextPlaceholder()
scope[common.LocalVarPodName] = placeholderGenerator.NextPlaceholder()
}
if tmpl.RetryStrategy != nil {
localParams[common.LocalVarRetries] = placeholderGenerator.NextPlaceholder()
scope[common.LocalVarRetries] = placeholderGenerator.NextPlaceholder()
}
if tmpl.IsLeaf() {
for _, art := range tmpl.Outputs.Artifacts {
if art.Path != "" {
scope[fmt.Sprintf("outputs.artifacts.%s.path", art.Name)] = true
}
}
for _, param := range tmpl.Outputs.Parameters {
if param.ValueFrom != nil && param.ValueFrom.Path != "" {
scope[fmt.Sprintf("outputs.parameters.%s.path", param.Name)] = true
}
}
}
newTmpl, err := common.ProcessArgs(tmpl, args, ctx.globalParams, localParams, true)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s %s", tmpl.Name, err)
}
if newTmpl.Timeout != "" {
if !newTmpl.IsLeaf() {
return fmt.Errorf("%s template doesn't support timeout field.", newTmpl.GetType())
}
// Check timeout should not be a whole number
_, err := strconv.Atoi(newTmpl.Timeout)
if err == nil {
return fmt.Errorf("%s has invalid duration format in timeout.", newTmpl.Name)
}
}
tmplID := getTemplateID(tmpl)
_, ok := ctx.results[tmplID]
if ok {
// we can skip the rest since it has been validated.
return nil
}
ctx.results[tmplID] = true
for globalVar, val := range ctx.globalParams {
scope[globalVar] = val
}
switch newTmpl.GetType() {
case wfv1.TemplateTypeSteps:
err = ctx.validateSteps(scope, tmplCtx, newTmpl)
case wfv1.TemplateTypeDAG:
err = ctx.validateDAG(scope, tmplCtx, newTmpl)
default:
err = ctx.validateLeaf(scope, newTmpl)
}
if err != nil {
return err
}
err = validateOutputs(scope, newTmpl)
if err != nil {
return err
}
err = ctx.validateBaseImageOutputs(newTmpl)
if err != nil {
return err
}
if newTmpl.ArchiveLocation != nil {
errPrefix := fmt.Sprintf("templates.%s.archiveLocation", newTmpl.Name)
err = validateArtifactLocation(errPrefix, *newTmpl.ArchiveLocation)
if err != nil {
return err
}
}
if newTmpl.Metrics != nil {
for _, metric := range newTmpl.Metrics.Prometheus {
if !metrics.IsValidMetricName(metric.Name) {
return errors.Errorf(errors.CodeBadRequest, "templates.%s metric name '%s' is invalid. Metric names must contain alphanumeric characters, '_', or ':'", tmpl.Name, metric.Name)
}
if metric.Help == "" {
return errors.Errorf(errors.CodeBadRequest, "templates.%s metric '%s' must contain a help string under 'help: ' field", tmpl.Name, metric.Name)
}
}
}
return nil
}
// validateTemplateHolder validates a template holder and returns the validated template.
func (ctx *templateValidationCtx) validateTemplateHolder(tmplHolder wfv1.TemplateReferenceHolder, tmplCtx *templateresolution.Context, args wfv1.ArgumentsProvider, extraScope map[string]interface{}) (*wfv1.Template, error) {
tmplRef := tmplHolder.GetTemplateRef()
tmplName := tmplHolder.GetTemplateName()
if tmplRef != nil {
if tmplName != "" {
return nil, errors.New(errors.CodeBadRequest, "template name cannot be specified with templateRef.")
}
if tmplRef.Name == "" {
return nil, errors.New(errors.CodeBadRequest, "resource name is required")
}
if tmplRef.Template == "" {
return nil, errors.New(errors.CodeBadRequest, "template name is required")
}
if tmplRef.RuntimeResolution {
// Let's see if the template exists at runtime.
return nil, nil
}
} else if tmplName != "" {
_, err := tmplCtx.GetTemplateByName(tmplName)
if err != nil {
if argoerr, ok := err.(errors.ArgoError); ok && argoerr.Code() == errors.CodeNotFound {
return nil, errors.Errorf(errors.CodeBadRequest, "template name '%s' undefined", tmplName)
}
return nil, err
}
} else {
if tmpl, ok := tmplHolder.(*wfv1.Template); ok {
if tmpl.GetType() != wfv1.TemplateTypeUnknown {
return nil, errors.New(errors.CodeBadRequest, "template ref can not be used with template type.")
}
}
}
tmplCtx, resolvedTmpl, _, err := tmplCtx.ResolveTemplate(tmplHolder)
if err != nil {
if argoerr, ok := err.(errors.ArgoError); ok && argoerr.Code() == errors.CodeNotFound {
if tmplRef != nil {
return nil, errors.Errorf(errors.CodeBadRequest, "template reference %s.%s not found", tmplRef.Name, tmplRef.Template)
}
// this error should not occur.
return nil, errors.InternalWrapError(err)
}
return nil, err
}
// Validate retryStrategy
if resolvedTmpl.RetryStrategy != nil {
switch resolvedTmpl.RetryStrategy.RetryPolicy {
case wfv1.RetryPolicyAlways, wfv1.RetryPolicyOnError, wfv1.RetryPolicyOnFailure, "":
// Passes validation
default:
return nil, fmt.Errorf("%s is not a valid RetryPolicy", resolvedTmpl.RetryStrategy.RetryPolicy)
}
}
return resolvedTmpl, ctx.validateTemplate(resolvedTmpl, tmplCtx, args, extraScope)
}
// validateTemplateType validates that only one template type is defined
func validateTemplateType(tmpl *wfv1.Template) error {
numTypes := 0
for _, tmplType := range []interface{}{tmpl.TemplateRef, tmpl.Container, tmpl.Steps, tmpl.Script, tmpl.Resource, tmpl.DAG, tmpl.Suspend} {
if !reflect.ValueOf(tmplType).IsNil() {
numTypes++
}
}
if tmpl.Template != "" {
numTypes++
}
switch numTypes {
case 0:
return errors.Errorf(errors.CodeBadRequest, "templates.%s template type unspecified. choose one of: container, steps, script, resource, dag, suspend, template, template ref", tmpl.Name)
case 1:
// Do nothing
default:
return errors.Errorf(errors.CodeBadRequest, "templates.%s multiple template types specified. choose one of: container, steps, script, resource, dag, suspend, template, template ref", tmpl.Name)
}
return nil
}
func validateInputs(tmpl *wfv1.Template, extraScope map[string]interface{}) (map[string]interface{}, error) {
err := validateWorkflowFieldNames(tmpl.Inputs.Parameters)
if err != nil {
return nil, errors.Errorf(errors.CodeBadRequest, "templates.%s.inputs.parameters%s", tmpl.Name, err.Error())
}
err = validateWorkflowFieldNames(tmpl.Inputs.Artifacts)
if err != nil {
return nil, errors.Errorf(errors.CodeBadRequest, "templates.%s.inputs.artifacts%s", tmpl.Name, err.Error())
}
scope := make(map[string]interface{})
for name, value := range extraScope {
scope[name] = value
}
for _, param := range tmpl.Inputs.Parameters {
scope[fmt.Sprintf("inputs.parameters.%s", param.Name)] = true
}
if len(tmpl.Inputs.Parameters) > 0 {
scope["inputs.parameters"] = true
}
for _, art := range tmpl.Inputs.Artifacts {
artRef := fmt.Sprintf("inputs.artifacts.%s", art.Name)
scope[artRef] = true
if tmpl.IsLeaf() {
if art.Path == "" {
return nil, errors.Errorf(errors.CodeBadRequest, "templates.%s.%s.path not specified", tmpl.Name, artRef)
}
scope[fmt.Sprintf("inputs.artifacts.%s.path", art.Name)] = true
} else {
if art.Path != "" {
return nil, errors.Errorf(errors.CodeBadRequest, "templates.%s.%s.path only valid in container/script templates", tmpl.Name, artRef)
}
}
if art.From != "" {
return nil, errors.Errorf(errors.CodeBadRequest, "templates.%s.%s.from not valid in inputs", tmpl.Name, artRef)
}
errPrefix := fmt.Sprintf("templates.%s.%s", tmpl.Name, artRef)
err = validateArtifactLocation(errPrefix, art.ArtifactLocation)
if err != nil {
return nil, err
}
}
return scope, nil
}
func validateArtifactLocation(errPrefix string, art wfv1.ArtifactLocation) error {
if art.Git != nil {
if art.Git.Repo == "" {
return errors.Errorf(errors.CodeBadRequest, "%s.git.repo is required", errPrefix)
}
}
if art.HDFS != nil {
err := hdfs.ValidateArtifact(fmt.Sprintf("%s.hdfs", errPrefix), art.HDFS)
if err != nil {
return err
}
}
// TODO: validate other artifact locations
return nil
}
// resolveAllVariables is a helper to ensure all {{variables}} are resolveable from current scope
func resolveAllVariables(scope map[string]interface{}, tmplStr string) error {
var unresolvedErr error
_, allowAllItemRefs := scope[anyItemMagicValue] // 'item.*' is a magic placeholder value set by addItemsToScope
_, allowAllWorkflowOutputParameterRefs := scope[anyWorkflowOutputParameterMagicValue]
_, allowAllWorkflowOutputArtifactRefs := scope[anyWorkflowOutputArtifactMagicValue]
fstTmpl, err := fasttemplate.NewTemplate(tmplStr, "{{", "}}")
if err != nil {
return fmt.Errorf("unable to parse argo varaible: %w", err)
}
fstTmpl.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
// Skip the custom variable references
if !checkValidWorkflowVariablePrefix(tag) {
return 0, nil
}
_, ok := scope[tag]
if !ok && unresolvedErr == nil {
if (tag == "item" || strings.HasPrefix(tag, "item.")) && allowAllItemRefs {
// we are *probably* referencing a undetermined item using withParam
// NOTE: this is far from foolproof.
} else if strings.HasPrefix(tag, "workflow.outputs.parameters.") && allowAllWorkflowOutputParameterRefs {
// Allow runtime resolution of workflow output parameter names
} else if strings.HasPrefix(tag, "workflow.outputs.artifacts.") && allowAllWorkflowOutputArtifactRefs {
// Allow runtime resolution of workflow output artifact names
} else if strings.HasPrefix(tag, "outputs.") {
// We are self referencing for metric emission, allow it.
} else if strings.HasPrefix(tag, common.GlobalVarWorkflowCreationTimestamp) {
} else {
unresolvedErr = fmt.Errorf("failed to resolve {{%s}}", tag)
}
}
return 0, nil
})
return unresolvedErr
}
// checkValidWorkflowVariablePrefix is a helper methood check variable starts workflow root elements
func checkValidWorkflowVariablePrefix(tag string) bool {
for _, rootTag := range common.GlobalVarValidWorkflowVariablePrefix {
if strings.HasPrefix(tag, rootTag) {
return true
}
}
return false
}
func validateNonLeaf(tmpl *wfv1.Template) error {
if tmpl.ActiveDeadlineSeconds != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.activeDeadlineSeconds is only valid for leaf templates", tmpl.Name)
}
return nil
}
func (ctx *templateValidationCtx) validateLeaf(scope map[string]interface{}, tmpl *wfv1.Template) error {
tmplBytes, err := json.Marshal(tmpl)
if err != nil {
return errors.InternalWrapError(err)
}
err = resolveAllVariables(scope, string(tmplBytes))
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s: %s", tmpl.Name, err.Error())
}
if tmpl.Container != nil {
// Ensure there are no collisions with volume mountPaths and artifact load paths
mountPaths := make(map[string]string)
for i, volMount := range tmpl.Container.VolumeMounts {
if prev, ok := mountPaths[volMount.MountPath]; ok {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.container.volumeMounts[%d].mountPath '%s' already mounted in %s", tmpl.Name, i, volMount.MountPath, prev)
}
mountPaths[volMount.MountPath] = fmt.Sprintf("container.volumeMounts.%s", volMount.Name)
}
for i, art := range tmpl.Inputs.Artifacts {
if prev, ok := mountPaths[art.Path]; ok {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.inputs.artifacts[%d].path '%s' already mounted in %s", tmpl.Name, i, art.Path, prev)
}
mountPaths[art.Path] = fmt.Sprintf("inputs.artifacts.%s", art.Name)
}
if tmpl.Container.Image == "" {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.container.image may not be empty", tmpl.Name)
}
}
if tmpl.Resource != nil {
if !placeholderGenerator.IsPlaceholder(tmpl.Resource.Action) {
switch tmpl.Resource.Action {
case "get", "create", "apply", "delete", "replace", "patch":
// OK
default:
return errors.Errorf(errors.CodeBadRequest, "templates.%s.resource.action must be one of: get, create, apply, delete, replace, patch", tmpl.Name)
}
}
if !placeholderGenerator.IsPlaceholder(tmpl.Resource.Manifest) {
// Try to unmarshal the given manifest.
obj := unstructured.Unstructured{}
err := yaml.Unmarshal([]byte(tmpl.Resource.Manifest), &obj)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.resource.manifest must be a valid yaml", tmpl.Name)
}
}
}
if tmpl.Script != nil {
if tmpl.Script.Image == "" {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.script.image may not be empty", tmpl.Name)
}
}
if tmpl.ActiveDeadlineSeconds != nil {
if !intstr.IsValidIntOrArgoVariable(tmpl.ActiveDeadlineSeconds) {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.activeDeadlineSeconds must be a positive integer > 0 or an argo variable", tmpl.Name)
}
if i, err := intstr.Int(tmpl.ActiveDeadlineSeconds); err == nil && *i < 0 {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.activeDeadlineSeconds must be a positive integer > 0 or an argo variable", tmpl.Name)
}
}
if tmpl.Parallelism != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.parallelism is only valid for steps and dag templates", tmpl.Name)
}
var automountServiceAccountToken *bool
if tmpl.AutomountServiceAccountToken != nil {
automountServiceAccountToken = tmpl.AutomountServiceAccountToken
} else if ctx.wf != nil && ctx.wf.Spec.AutomountServiceAccountToken != nil {
automountServiceAccountToken = ctx.wf.Spec.AutomountServiceAccountToken
}
executorServiceAccountName := ""
if tmpl.Executor != nil && tmpl.Executor.ServiceAccountName != "" {
executorServiceAccountName = tmpl.Executor.ServiceAccountName
} else if ctx.wf != nil && ctx.wf.Spec.Executor != nil && ctx.wf.Spec.Executor.ServiceAccountName != "" {
executorServiceAccountName = ctx.wf.Spec.Executor.ServiceAccountName
}
if automountServiceAccountToken != nil && !*automountServiceAccountToken && executorServiceAccountName == "" {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.executor.serviceAccountName must not be empty if automountServiceAccountToken is false", tmpl.Name)
}
return nil
}
func validateArguments(prefix string, arguments wfv1.Arguments) error {
err := validateArgumentsFieldNames(prefix, arguments)
if err != nil {
return err
}
return validateArgumentsValues(prefix, arguments)
}
func validateArgumentsFieldNames(prefix string, arguments wfv1.Arguments) error {
fieldToSlices := map[string]interface{}{
"parameters": arguments.Parameters,
"artifacts": arguments.Artifacts,
}
for fieldName, lst := range fieldToSlices {
err := validateWorkflowFieldNames(lst)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "%s%s%s", prefix, fieldName, err.Error())
}
}
return nil
}
// validateArgumentsValues ensures that all arguments have parameter values or artifact locations
func validateArgumentsValues(prefix string, arguments wfv1.Arguments) error {
for _, param := range arguments.Parameters {
if param.Value == nil {
return errors.Errorf(errors.CodeBadRequest, "%s%s.value is required", prefix, param.Name)
}
}
for _, art := range arguments.Artifacts {
if art.From == "" && !art.HasLocation() {
return errors.Errorf(errors.CodeBadRequest, "%s%s.from or artifact location is required", prefix, art.Name)
}
}
return nil
}
func (ctx *templateValidationCtx) validateSteps(scope map[string]interface{}, tmplCtx *templateresolution.Context, tmpl *wfv1.Template) error {
err := validateNonLeaf(tmpl)
if err != nil {
return err
}
stepNames := make(map[string]bool)
resolvedTemplates := make(map[string]*wfv1.Template)
for i, stepGroup := range tmpl.Steps {
for _, step := range stepGroup.Steps {
if step.Name == "" {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps[%d].name is required", tmpl.Name, i)
}
_, ok := stepNames[step.Name]
if ok {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps[%d].name '%s' is not unique", tmpl.Name, i, step.Name)
}
if errs := isValidWorkflowFieldName(step.Name); len(errs) != 0 {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps[%d].name '%s' is invalid: %s", tmpl.Name, i, step.Name, strings.Join(errs, ";"))
}
stepNames[step.Name] = true
prefix := fmt.Sprintf("steps.%s", step.Name)
scope[fmt.Sprintf("%s.status", prefix)] = true
err := addItemsToScope(prefix, step.WithItems, step.WithParam, step.WithSequence, scope)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps[%d].%s %s", tmpl.Name, i, step.Name, err.Error())
}
err = validateArguments(fmt.Sprintf("templates.%s.steps[%d].%s.arguments.", tmpl.Name, i, step.Name), step.Arguments)
if err != nil {
return err
}
resolvedTmpl, err := ctx.validateTemplateHolder(&step, tmplCtx, &FakeArguments{}, scope)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps[%d].%s %s", tmpl.Name, i, step.Name, err.Error())
}
resolvedTemplates[step.Name] = resolvedTmpl
}
stepBytes, err := json.Marshal(stepGroup)
if err != nil {
return errors.InternalWrapError(err)
}
err = resolveAllVariables(scope, string(stepBytes))
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps %s", tmpl.Name, err.Error())
}
for _, step := range stepGroup.Steps {
aggregate := len(step.WithItems) > 0 || step.WithParam != ""
resolvedTmpl := resolvedTemplates[step.Name]
ctx.addOutputsToScope(resolvedTmpl, fmt.Sprintf("steps.%s", step.Name), scope, aggregate, false)
// Validate the template again with actual arguments.
_, err = ctx.validateTemplateHolder(&step, tmplCtx, &step.Arguments, scope)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps[%d].%s %s", tmpl.Name, i, step.Name, err.Error())
}
}
}
return nil
}
func addItemsToScope(prefix string, withItems []wfv1.Item, withParam string, withSequence *wfv1.Sequence, scope map[string]interface{}) error {
defined := 0
if len(withItems) > 0 {
defined++
}
if withParam != "" {
defined++
}
if withSequence != nil {
defined++
}
if defined > 1 {
return fmt.Errorf("only one of withItems, withParam, withSequence can be specified")
}
if len(withItems) > 0 {
for i := range withItems {
val := withItems[i]
switch val.GetType() {
case wfv1.String, wfv1.Number, wfv1.Bool:
scope["item"] = true
case wfv1.List:
for i := range val.GetListVal() {
scope[fmt.Sprintf("item.[%v]", i)] = true
}
case wfv1.Map:
for itemKey := range val.GetMapVal() {
scope[fmt.Sprintf("item.%s", itemKey)] = true
}
default:
return fmt.Errorf("unsupported withItems type: %v", val)
}
}
} else if withParam != "" {
scope["item"] = true
// 'item.*' is magic placeholder value which resolveAllVariables() will look for
// when considering if all variables are resolveable.
scope[anyItemMagicValue] = true
} else if withSequence != nil {
if withSequence.Count != nil && withSequence.End != nil {
return errors.New(errors.CodeBadRequest, "only one of count or end can be defined in withSequence")
}
scope["item"] = true
}
return nil
}
func (ctx *templateValidationCtx) addOutputsToScope(tmpl *wfv1.Template, prefix string, scope map[string]interface{}, aggregate bool, isAncestor bool) {
if tmpl.Daemon != nil && *tmpl.Daemon {
scope[fmt.Sprintf("%s.ip", prefix)] = true
}
if tmpl.Script != nil || tmpl.Container != nil {
scope[fmt.Sprintf("%s.outputs.result", prefix)] = true
scope[fmt.Sprintf("%s.exitCode", prefix)] = true
}
for _, param := range tmpl.Outputs.Parameters {
scope[fmt.Sprintf("%s.outputs.parameters.%s", prefix, param.Name)] = true
if param.GlobalName != "" {
if !isParameter(param.GlobalName) {
globalParamName := fmt.Sprintf("workflow.outputs.parameters.%s", param.GlobalName)
scope[globalParamName] = true
ctx.globalParams[globalParamName] = placeholderGenerator.NextPlaceholder()
} else {
logrus.Warnf("GlobalName '%s' is a parameter and won't be validated until runtime", param.GlobalName)
scope[anyWorkflowOutputParameterMagicValue] = true
}
}
}
for _, art := range tmpl.Outputs.Artifacts {
scope[fmt.Sprintf("%s.outputs.artifacts.%s", prefix, art.Name)] = true
if art.GlobalName != "" {
if !isParameter(art.GlobalName) {
globalArtName := fmt.Sprintf("workflow.outputs.artifacts.%s", art.GlobalName)
scope[globalArtName] = true
ctx.globalParams[globalArtName] = placeholderGenerator.NextPlaceholder()
} else {
logrus.Warnf("GlobalName '%s' is a parameter and won't be validated until runtime", art.GlobalName)
scope[anyWorkflowOutputArtifactMagicValue] = true
}
}
}
if aggregate {
switch tmpl.GetType() {
// Not that we don't also include TemplateTypeContainer here, even though it uses `outputs.result` it uses
// `outputs.parameters` as its aggregator.
case wfv1.TemplateTypeScript:
scope[fmt.Sprintf("%s.outputs.result", prefix)] = true
scope[fmt.Sprintf("%s.exitCode", prefix)] = true
default:
scope[fmt.Sprintf("%s.outputs.parameters", prefix)] = true
}
}
if isAncestor {
scope[fmt.Sprintf("%s.status", prefix)] = true
}
}
func validateOutputs(scope map[string]interface{}, tmpl *wfv1.Template) error {
err := validateWorkflowFieldNames(tmpl.Outputs.Parameters)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.outputs.parameters %s", tmpl.Name, err.Error())
}
err = validateWorkflowFieldNames(tmpl.Outputs.Artifacts)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.outputs.artifacts %s", tmpl.Name, err.Error())
}
outputBytes, err := json.Marshal(tmpl.Outputs)
if err != nil {
return errors.InternalWrapError(err)
}
err = resolveAllVariables(scope, string(outputBytes))
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.outputs %s", tmpl.Name, err.Error())
}
for _, art := range tmpl.Outputs.Artifacts {
artRef := fmt.Sprintf("outputs.artifacts.%s", art.Name)
if tmpl.IsLeaf() {
if art.Path == "" {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.%s.path not specified", tmpl.Name, artRef)
}
} else {
if art.Path != "" {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.%s.path only valid in container/script templates", tmpl.Name, artRef)
}
}
if art.GlobalName != "" && !isParameter(art.GlobalName) {
errs := isValidParamOrArtifactName(art.GlobalName)
if len(errs) > 0 {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.%s.globalName: %s", tmpl.Name, artRef, errs[0])
}
}
}
for _, param := range tmpl.Outputs.Parameters {
paramRef := fmt.Sprintf("templates.%s.outputs.parameters.%s", tmpl.Name, param.Name)
err = validateOutputParameter(paramRef, ¶m)
if err != nil {
return err
}
if param.ValueFrom != nil {
tmplType := tmpl.GetType()
switch tmplType {
case wfv1.TemplateTypeContainer, wfv1.TemplateTypeScript:
if param.ValueFrom.Path == "" {
return errors.Errorf(errors.CodeBadRequest, "%s.path must be specified for %s templates", paramRef, tmplType)
}
case wfv1.TemplateTypeResource:
if param.ValueFrom.JQFilter == "" && param.ValueFrom.JSONPath == "" {
return errors.Errorf(errors.CodeBadRequest, "%s .jqFilter or jsonPath must be specified for %s templates", paramRef, tmplType)
}
case wfv1.TemplateTypeDAG, wfv1.TemplateTypeSteps:
if param.ValueFrom.Parameter == "" {
return errors.Errorf(errors.CodeBadRequest, "%s.parameter must be specified for %s templates", paramRef, tmplType)
}
}
}
if param.GlobalName != "" && !isParameter(param.GlobalName) {
errs := isValidParamOrArtifactName(param.GlobalName)
if len(errs) > 0 {
return errors.Errorf(errors.CodeBadRequest, "%s.globalName: %s", paramRef, errs[0])
}
}
}