-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
664 lines (628 loc) · 22.5 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
package common
import (
"encoding/json"
"fmt"
"io"
"reflect"
"regexp"
"strings"
"github.com/argoproj/argo/errors"
wfv1 "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
"github.com/valyala/fasttemplate"
)
// wfValidationCtx is the context for validating a workflow spec
type wfValidationCtx struct {
wf *wfv1.Workflow
// 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
}
const (
// placeholderValue is an arbitrary string to perform mock substitution of variables
placeholderValue = "placeholder"
// 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.*"
)
// ValidateWorkflow accepts a workflow and performs validation against it. If lint is specified as
// true, will skip some validations which is permissible during linting but not submission
func ValidateWorkflow(wf *wfv1.Workflow, lint ...bool) error {
ctx := wfValidationCtx{
wf: wf,
globalParams: make(map[string]string),
results: make(map[string]bool),
}
linting := len(lint) > 0 && lint[0]
err := validateWorkflowFieldNames(wf.Spec.Templates)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "spec.templates%s", err.Error())
}
if linting {
// 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.", wf.Spec.Arguments)
} else {
err = validateArguments("spec.arguments.", wf.Spec.Arguments)
}
if err != nil {
return err
}
ctx.globalParams[GlobalVarWorkflowName] = placeholderValue
ctx.globalParams[GlobalVarWorkflowNamespace] = placeholderValue
ctx.globalParams[GlobalVarWorkflowUID] = placeholderValue
for _, param := range ctx.wf.Spec.Arguments.Parameters {
ctx.globalParams["workflow.parameters."+param.Name] = placeholderValue
}
if ctx.wf.Spec.Entrypoint == "" {
return errors.New(errors.CodeBadRequest, "spec.entrypoint is required")
}
entryTmpl := ctx.wf.GetTemplate(ctx.wf.Spec.Entrypoint)
if entryTmpl == nil {
return errors.Errorf(errors.CodeBadRequest, "spec.entrypoint template '%s' undefined", ctx.wf.Spec.Entrypoint)
}
err = ctx.validateTemplate(entryTmpl, ctx.wf.Spec.Arguments)
if err != nil {
return err
}
if ctx.wf.Spec.OnExit != "" {
exitTmpl := ctx.wf.GetTemplate(ctx.wf.Spec.OnExit)
if exitTmpl == nil {
return errors.Errorf(errors.CodeBadRequest, "spec.onExit template '%s' undefined", ctx.wf.Spec.OnExit)
}
// now when validating onExit, {{workflow.status}} is now available as a global
ctx.globalParams[GlobalVarWorkflowStatus] = placeholderValue
err = ctx.validateTemplate(exitTmpl, ctx.wf.Spec.Arguments)
if err != nil {
return err
}
}
return nil
}
func (ctx *wfValidationCtx) validateTemplate(tmpl *wfv1.Template, args wfv1.Arguments) error {
_, ok := ctx.results[tmpl.Name]
if ok {
// we already processed this template
return nil
}
ctx.results[tmpl.Name] = true
if err := validateTemplateType(tmpl); err != nil {
return err
}
scope, err := validateInputs(tmpl)
if err != nil {
return err
}
localParams := make(map[string]string)
if tmpl.IsPodType() {
localParams["pod.name"] = placeholderValue
scope["pod.name"] = placeholderValue
}
_, err = ProcessArgs(tmpl, args, ctx.globalParams, localParams, true)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s %s", tmpl.Name, err)
}
for globalVar, val := range ctx.globalParams {
scope[globalVar] = val
}
switch tmpl.GetType() {
case wfv1.TemplateTypeSteps:
err = ctx.validateSteps(scope, tmpl)
case wfv1.TemplateTypeDAG:
err = ctx.validateDAG(scope, tmpl)
default:
err = validateLeaf(scope, tmpl)
}
if err != nil {
return err
}
err = validateOutputs(scope, tmpl)
if err != nil {
return err
}
return nil
}
// validateTemplateType validates that only one template type is defined
func validateTemplateType(tmpl *wfv1.Template) error {
numTypes := 0
for _, tmplType := range []interface{}{tmpl.Container, tmpl.Steps, tmpl.Script, tmpl.Resource, tmpl.DAG, tmpl.Suspend} {
if !reflect.ValueOf(tmplType).IsNil() {
numTypes++
}
}
switch numTypes {
case 0:
return errors.New(errors.CodeBadRequest, "template type unspecified. choose one of: container, steps, script, resource, dag, suspend")
case 1:
default:
return errors.New(errors.CodeBadRequest, "multiple template types specified. choose one of: container, steps, script, resource, dag, suspend")
}
return nil
}
func validateInputs(tmpl *wfv1.Template) (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 _, param := range tmpl.Inputs.Parameters {
scope[fmt.Sprintf("inputs.parameters.%s", param.Name)] = true
}
isLeaf := tmpl.Container != nil || tmpl.Script != nil
for _, art := range tmpl.Inputs.Artifacts {
artRef := fmt.Sprintf("inputs.artifacts.%s", art.Name)
scope[artRef] = true
if isLeaf {
if art.Path == "" {
return nil, errors.Errorf(errors.CodeBadRequest, "templates.%s.%s.path not specified", tmpl.Name, artRef)
}
} 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)
if err != nil {
return nil, err
}
}
return scope, nil
}
func validateArtifactLocation(errPrefix string, art wfv1.Artifact) error {
if art.Git != nil {
if art.Git.Repo == "" {
return errors.Errorf(errors.CodeBadRequest, "%s.git.repo is required", errPrefix)
}
}
// 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
fstTmpl := fasttemplate.New(tmplStr, "{{", "}}")
fstTmpl.ExecuteFuncString(func(w io.Writer, tag string) (int, error) {
_, 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 {
unresolvedErr = fmt.Errorf("failed to resolve {{%s}}", tag)
}
}
return 0, nil
})
return unresolvedErr
}
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)
}
if tmpl.RetryStrategy != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.retryStrategy is only valid for container templates", tmpl.Name)
}
return nil
}
func 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.ActiveDeadlineSeconds != nil {
if *tmpl.ActiveDeadlineSeconds <= 0 {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.activeDeadlineSeconds must be a positive integer > 0", tmpl.Name)
}
}
if tmpl.Parallelism != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.parallelism is only valid for steps and dag templates", 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, "%svalue is required", prefix)
}
}
for _, art := range arguments.Artifacts {
if art.From == "" && !art.HasLocation() {
return errors.Errorf(errors.CodeBadRequest, "%sfrom or artifact location is required", prefix)
}
}
return nil
}
func (ctx *wfValidationCtx) validateSteps(scope map[string]interface{}, tmpl *wfv1.Template) error {
err := validateNonLeaf(tmpl)
if err != nil {
return err
}
stepNames := make(map[string]bool)
for i, stepGroup := range tmpl.Steps {
for _, step := range stepGroup {
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
err := addItemsToScope(&step, scope)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps[%d].%s %s", tmpl.Name, i, step.Name, err.Error())
}
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[%d].%s %s", tmpl.Name, i, step.Name, err.Error())
}
childTmpl := ctx.wf.GetTemplate(step.Template)
if childTmpl == nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.steps[%d].%s.template '%s' undefined", tmpl.Name, i, step.Name, step.Template)
}
err = validateArguments(fmt.Sprintf("templates.%s.steps[%d].%s.arguments.", tmpl.Name, i, step.Name), step.Arguments)
if err != nil {
return err
}
err = ctx.validateTemplate(childTmpl, step.Arguments)
if err != nil {
return err
}
}
for _, step := range stepGroup {
ctx.addOutputsToScope(step.Template, fmt.Sprintf("steps.%s", step.Name), scope)
}
}
return nil
}
func addItemsToScope(step *wfv1.WorkflowStep, scope map[string]interface{}) error {
if len(step.WithItems) > 0 && step.WithParam != "" {
return fmt.Errorf("only one of withItems or withParam can be specified")
}
if len(step.WithItems) > 0 {
for i := range step.WithItems {
switch val := step.WithItems[i].Value.(type) {
case string, int32, int64, float32, float64, bool:
scope["item"] = true
case map[string]interface{}:
for itemKey := range val {
scope[fmt.Sprintf("item.%s", itemKey)] = true
}
default:
return fmt.Errorf("unsupported withItems type: %v", val)
}
}
} else if step.WithParam != "" {
scope["item"] = true
// 'item.*' is magic placeholder value which resolveAllVariables() will look for
// when considering if all variables are resolveable.
scope[anyItemMagicValue] = true
}
return nil
}
func (ctx *wfValidationCtx) addOutputsToScope(templateName string, prefix string, scope map[string]interface{}) {
tmpl := ctx.wf.GetTemplate(templateName)
if tmpl.Daemon != nil && *tmpl.Daemon {
scope[fmt.Sprintf("%s.ip", prefix)] = true
}
if tmpl.Script != nil {
scope[fmt.Sprintf("%s.outputs.result", prefix)] = true
}
for _, param := range tmpl.Outputs.Parameters {
scope[fmt.Sprintf("%s.outputs.parameters.%s", prefix, param.Name)] = true
if param.GlobalName != "" && !isParameter(param.GlobalName) {
globalParamName := fmt.Sprintf("workflow.outputs.parameters.%s", param.GlobalName)
scope[globalParamName] = true
ctx.globalParams[globalParamName] = placeholderValue
}
}
for _, art := range tmpl.Outputs.Artifacts {
scope[fmt.Sprintf("%s.outputs.artifacts.%s", prefix, art.Name)] = true
if art.GlobalName != "" && !isParameter(art.GlobalName) {
scope[fmt.Sprintf("workflow.outputs.artifacts.%s", art.GlobalName)] = 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())
}
isLeaf := tmpl.Container != nil || tmpl.Script != nil
for _, art := range tmpl.Outputs.Artifacts {
artRef := fmt.Sprintf("outputs.artifacts.%s", art.Name)
if 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 := IsValidWorkflowFieldName(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
}
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 := IsValidWorkflowFieldName(param.GlobalName)
if len(errs) > 0 {
return errors.Errorf(errors.CodeBadRequest, "%s.globalName: %s", paramRef, errs[0])
}
}
}
return nil
}
// validateOutputParameter verifies that only one of valueFrom is defined in an output
func validateOutputParameter(paramRef string, param *wfv1.Parameter) error {
if param.ValueFrom == nil {
return errors.Errorf(errors.CodeBadRequest, "%s.valueFrom not specified", paramRef)
}
paramTypes := 0
for _, value := range []string{param.ValueFrom.Path, param.ValueFrom.JQFilter, param.ValueFrom.JSONPath, param.ValueFrom.Parameter} {
if value != "" {
paramTypes++
}
}
switch paramTypes {
case 0:
return errors.New(errors.CodeBadRequest, "valueFrom type unspecified. choose one of: path, jqFilter, jsonPath, parameter")
case 1:
default:
return errors.New(errors.CodeBadRequest, "multiple valueFrom types specified. choose one of: path, jqFilter, jsonPath, parameter")
}
return nil
}
// validateWorkflowFieldNames accepts a slice of structs and
// verifies that the Name field of the structs are:
// * unique
// * non-empty
// * matches matches our regex requirements
func validateWorkflowFieldNames(slice interface{}) error {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
return errors.InternalErrorf("validateWorkflowFieldNames given a non-slice type")
}
items := make([]interface{}, s.Len())
for i := 0; i < s.Len(); i++ {
items[i] = s.Index(i).Interface()
}
names := make(map[string]bool)
getNameFieldValue := func(val interface{}) (string, error) {
s := reflect.ValueOf(val)
for i := 0; i < s.NumField(); i++ {
typeField := s.Type().Field(i)
if typeField.Name == "Name" {
return s.Field(i).String(), nil
}
}
return "", errors.InternalError("No 'Name' field in struct")
}
for i, item := range items {
name, err := getNameFieldValue(item)
if err != nil {
return err
}
if name == "" {
return errors.Errorf(errors.CodeBadRequest, "[%d].name is required", i)
}
if errs := IsValidWorkflowFieldName(name); len(errs) != 0 {
return errors.Errorf(errors.CodeBadRequest, "[%d].name: '%s' is invalid: %s", i, name, strings.Join(errs, ";"))
}
_, ok := names[name]
if ok {
return errors.Errorf(errors.CodeBadRequest, "[%d].name '%s' is not unique", i, name)
}
names[name] = true
}
return nil
}
func (ctx *wfValidationCtx) validateDAG(scope map[string]interface{}, tmpl *wfv1.Template) error {
err := validateNonLeaf(tmpl)
if err != nil {
return err
}
err = validateWorkflowFieldNames(tmpl.DAG.Tasks)
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.tasks%s", tmpl.Name, err.Error())
}
nameToTask := make(map[string]wfv1.DAGTask)
for _, task := range tmpl.DAG.Tasks {
nameToTask[task.Name] = task
}
// Verify dependencies for all tasks can be resolved as well as template names
for _, task := range tmpl.DAG.Tasks {
if task.Template == "" {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.tasks.%s.template is required", tmpl.Name, task.Name)
}
taskTmpl := ctx.wf.GetTemplate(task.Template)
if taskTmpl == nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.tasks%s.template '%s' undefined", tmpl.Name, task.Name, task.Template)
}
dupDependencies := make(map[string]bool)
for j, depName := range task.Dependencies {
if _, ok := dupDependencies[depName]; ok {
return errors.Errorf(errors.CodeBadRequest,
"templates.%s.tasks.%s.dependencies[%d] dependency '%s' duplicated",
tmpl.Name, task.Name, j, depName)
}
dupDependencies[depName] = true
if _, ok := nameToTask[depName]; !ok {
return errors.Errorf(errors.CodeBadRequest,
"templates.%s.tasks.%s.dependencies[%d] dependency '%s' not defined",
tmpl.Name, task.Name, j, depName)
}
}
}
err = verifyNoCycles(tmpl, nameToTask)
if err != nil {
return err
}
for _, task := range tmpl.DAG.Tasks {
// add all tasks outputs to scope so that DAGs can have outputs
ctx.addOutputsToScope(task.Template, fmt.Sprintf("tasks.%s", task.Name), scope)
taskBytes, err := json.Marshal(task)
if err != nil {
return errors.InternalWrapError(err)
}
taskScope := make(map[string]interface{})
for k, v := range scope {
taskScope[k] = v
}
ancestry := GetTaskAncestry(task.Name, tmpl.DAG.Tasks)
for _, ancestor := range ancestry {
ctx.addOutputsToScope(nameToTask[ancestor].Template, fmt.Sprintf("tasks.%s", ancestor), taskScope)
}
err = resolveAllVariables(taskScope, string(taskBytes))
if err != nil {
return errors.Errorf(errors.CodeBadRequest, "templates.%s.tasks.%s %s", tmpl.Name, task.Name, err.Error())
}
err = validateArguments(fmt.Sprintf("templates.%s.tasks.%s.arguments.", tmpl.Name, task.Name), task.Arguments)
if err != nil {
return err
}
taskTmpl := ctx.wf.GetTemplate(task.Template)
err = ctx.validateTemplate(taskTmpl, task.Arguments)
if err != nil {
return err
}
}
return nil
}
// verifyNoCycles verifies there are no cycles in the DAG graph
func verifyNoCycles(tmpl *wfv1.Template, nameToTask map[string]wfv1.DAGTask) error {
visited := make(map[string]bool)
var noCyclesHelper func(taskName string, cycle []string) error
noCyclesHelper = func(taskName string, cycle []string) error {
if _, ok := visited[taskName]; ok {
return nil
}
task := nameToTask[taskName]
for _, depName := range task.Dependencies {
for _, name := range cycle {
if name == depName {
return errors.Errorf(errors.CodeBadRequest,
"templates.%s.tasks dependency cycle detected: %s->%s",
tmpl.Name, strings.Join(cycle, "->"), name)
}
}
cycle = append(cycle, depName)
err := noCyclesHelper(depName, cycle)
if err != nil {
return err
}
cycle = cycle[0 : len(cycle)-1]
}
visited[taskName] = true
return nil
}
for _, task := range tmpl.DAG.Tasks {
err := noCyclesHelper(task.Name, []string{})
if err != nil {
return err
}
}
return nil
}
var (
// paramRegex matches a parameter. e.g. {{inputs.parameters.blah}}
paramRegex = regexp.MustCompile(`{{[-a-zA-Z0-9]+(\.[-a-zA-Z0-9]+)*}}`)
)
func isParameter(p string) bool {
return paramRegex.MatchString(p)
}