forked from tektoncd/pipeline
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpipeline_validation.go
919 lines (841 loc) · 37.8 KB
/
pipeline_validation.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
/*
Copyright 2022 The Tekton Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1
import (
"context"
"fmt"
"strings"
"github.com/tektoncd/pipeline/pkg/apis/config"
"github.com/tektoncd/pipeline/pkg/apis/validate"
"github.com/tektoncd/pipeline/pkg/reconciler/pipeline/dag"
"github.com/tektoncd/pipeline/pkg/substitution"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"knative.dev/pkg/apis"
"knative.dev/pkg/webhook/resourcesemantics"
)
var _ apis.Validatable = (*Pipeline)(nil)
var _ resourcesemantics.VerbLimited = (*Pipeline)(nil)
const (
taskRef = "taskRef"
taskSpec = "taskSpec"
pipelineRef = "pipelineRef"
pipelineSpec = "pipelineSpec"
)
// SupportedVerbs returns the operations that validation should be called for
func (p *Pipeline) SupportedVerbs() []admissionregistrationv1.OperationType {
return []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update}
}
// Validate checks that the Pipeline structure is valid but does not validate
// that any references resources exist, that is done at run time.
func (p *Pipeline) Validate(ctx context.Context) *apis.FieldError {
errs := validate.ObjectMetadata(p.GetObjectMeta()).ViaField("metadata")
errs = errs.Also(p.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec"))
// When a Pipeline is created directly, instead of declared inline in a PipelineRun,
// we do not support propagated parameters and workspaces.
// Validate that all params and workspaces it uses are declared.
errs = errs.Also(p.Spec.validatePipelineParameterUsage(ctx).ViaField("spec"))
errs = errs.Also(p.Spec.validatePipelineWorkspacesUsage().ViaField("spec"))
return errs
}
// Validate checks that taskNames in the Pipeline are valid and that the graph
// of Tasks expressed in the Pipeline makes sense.
func (ps *PipelineSpec) Validate(ctx context.Context) (errs *apis.FieldError) {
errs = errs.Also(ps.ValidateBetaFields(ctx))
if equality.Semantic.DeepEqual(ps, &PipelineSpec{}) {
errs = errs.Also(apis.ErrGeneric("expected at least one, got none", "description", "params", "resources", "tasks", "workspaces"))
}
// PipelineTask must have a valid unique label and at least one of taskRef or taskSpec should be specified
errs = errs.Also(ValidatePipelineTasks(ctx, ps.Tasks, ps.Finally))
// Validate the pipeline task graph
errs = errs.Also(validateGraph(ps.Tasks))
// The parameter variables should be valid
errs = errs.Also(ValidatePipelineParameterVariables(ctx, ps.Tasks, ps.Params).ViaField("tasks"))
errs = errs.Also(ValidatePipelineParameterVariables(ctx, ps.Finally, ps.Params).ViaField("finally"))
errs = errs.Also(validatePipelineContextVariables(ps.Tasks).ViaField("tasks"))
errs = errs.Also(validatePipelineContextVariables(ps.Finally).ViaField("finally"))
errs = errs.Also(validateExecutionStatusVariables(ps.Tasks, ps.Finally))
// Validate the pipeline's workspaces.
errs = errs.Also(validatePipelineWorkspacesDeclarations(ps.Workspaces))
// Validate the pipeline's results
errs = errs.Also(validatePipelineResults(ps.Results, ps.Tasks, ps.Finally))
errs = errs.Also(validateTasksAndFinallySection(ps))
errs = errs.Also(validateFinalTasks(ps.Tasks, ps.Finally))
errs = errs.Also(validateWhenExpressions(ctx, ps.Tasks, ps.Finally))
errs = errs.Also(validateMatrix(ctx, ps.Tasks).ViaField("tasks"))
errs = errs.Also(validateMatrix(ctx, ps.Finally).ViaField("finally"))
return errs
}
// ValidateBetaFields returns an error if the Pipeline spec uses beta features but does not
// have "enable-api-fields" set to "alpha" or "beta".
func (ps *PipelineSpec) ValidateBetaFields(ctx context.Context) *apis.FieldError {
var errs *apis.FieldError
// Object parameters
for i, p := range ps.Params {
if p.Type == ParamTypeObject {
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "object type parameter", config.BetaAPIFields).ViaFieldIndex("params", i))
}
}
// Indexing into array parameters
arrayParamIndexingRefs := ps.GetIndexingReferencesToArrayParams()
if len(arrayParamIndexingRefs) != 0 {
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "indexing into array parameters", config.BetaAPIFields))
}
// array and object results
for i, result := range ps.Results {
switch result.Type {
case ResultsTypeObject:
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "object results", config.BetaAPIFields).ViaFieldIndex("results", i))
case ResultsTypeArray:
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "array results", config.BetaAPIFields).ViaFieldIndex("results", i))
case ResultsTypeString:
default:
}
}
for i, pt := range ps.Tasks {
errs = errs.Also(pt.validateBetaFields(ctx).ViaFieldIndex("tasks", i))
}
for i, pt := range ps.Finally {
errs = errs.Also(pt.validateBetaFields(ctx).ViaFieldIndex("tasks", i))
}
return errs
}
// validateBetaFields returns an error if the PipelineTask uses beta features but does not
// have "enable-api-fields" set to "alpha" or "beta".
func (pt *PipelineTask) validateBetaFields(ctx context.Context) *apis.FieldError {
var errs *apis.FieldError
if pt.TaskRef != nil {
// Resolvers
if pt.TaskRef.Resolver != "" {
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "taskref.resolver", config.BetaAPIFields))
}
if len(pt.TaskRef.Params) > 0 {
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "taskref.params", config.BetaAPIFields))
}
} else if pt.TaskSpec != nil {
errs = errs.Also(pt.TaskSpec.ValidateBetaFields(ctx))
}
return errs
}
// ValidatePipelineTasks ensures that pipeline tasks has unique label, pipeline tasks has specified one of
// taskRef or taskSpec, and in case of a pipeline task with taskRef, it has a reference to a valid task (task name)
func ValidatePipelineTasks(ctx context.Context, tasks []PipelineTask, finalTasks []PipelineTask) *apis.FieldError {
taskNames := sets.NewString()
var errs *apis.FieldError
errs = errs.Also(PipelineTaskList(tasks).Validate(ctx, taskNames, "tasks"))
errs = errs.Also(PipelineTaskList(finalTasks).Validate(ctx, taskNames, "finally"))
return errs
}
// Validate a list of pipeline tasks including custom task
func (l PipelineTaskList) Validate(ctx context.Context, taskNames sets.String, path string) (errs *apis.FieldError) {
for i, t := range l {
// validate pipeline task name
errs = errs.Also(t.ValidateName().ViaFieldIndex(path, i))
// names cannot be duplicated - checking that pipelineTask names are unique
if _, ok := taskNames[t.Name]; ok {
errs = errs.Also(apis.ErrMultipleOneOf("name").ViaFieldIndex(path, i))
}
taskNames.Insert(t.Name)
// validate custom task, dag, or final task
errs = errs.Also(t.Validate(ctx).ViaFieldIndex(path, i))
}
return errs
}
// validateUsageOfDeclaredPipelineTaskParameters validates that all parameters referenced in the pipeline Task are declared by the pipeline Task.
func (l PipelineTaskList) validateUsageOfDeclaredPipelineTaskParameters(ctx context.Context, path string) (errs *apis.FieldError) {
for i, t := range l {
if t.TaskSpec != nil {
errs = errs.Also(ValidateUsageOfDeclaredParameters(ctx, t.TaskSpec.Steps, t.TaskSpec.Params).ViaFieldIndex(path, i))
}
}
return errs
}
// ValidateName checks whether the PipelineTask's name is a valid DNS label
func (pt PipelineTask) ValidateName() *apis.FieldError {
if err := validation.IsDNS1123Label(pt.Name); len(err) > 0 {
return &apis.FieldError{
Message: fmt.Sprintf("invalid value %q", pt.Name),
Paths: []string{"name"},
Details: "Pipeline Task name must be a valid DNS Label." +
"For more info refer to https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names",
}
}
return nil
}
// Validate classifies whether a task is a custom task or a regular task(dag/final)
// calls the validation routine based on the type of the task
func (pt PipelineTask) Validate(ctx context.Context) (errs *apis.FieldError) {
errs = errs.Also(pt.validateRefOrSpec(ctx))
errs = errs.Also(pt.validateEmbeddedOrType())
// taskKinds contains the kinds when the apiVersion is not set, they are not custom tasks,
// if apiVersion is set they are custom tasks.
taskKinds := map[TaskKind]bool{
"": true,
NamespacedTaskKind: true,
ClusterTaskRefKind: true,
}
if pt.OnError != "" {
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "OnError", config.AlphaAPIFields))
if pt.OnError != PipelineTaskContinue && pt.OnError != PipelineTaskStopAndFail {
errs = errs.Also(apis.ErrInvalidValue(pt.OnError, "OnError", "PipelineTask OnError must be either \"continue\" or \"stopAndFail\""))
}
if pt.OnError == PipelineTaskContinue && pt.Retries > 0 {
errs = errs.Also(apis.ErrGeneric("PipelineTask OnError cannot be set to \"continue\" when Retries is greater than 0"))
}
}
// Pipeline task having taskRef/taskSpec with APIVersion is classified as custom task
switch {
case pt.TaskRef != nil && !taskKinds[pt.TaskRef.Kind]:
errs = errs.Also(pt.validateCustomTask())
case pt.TaskRef != nil && pt.TaskRef.APIVersion != "":
errs = errs.Also(pt.validateCustomTask())
case pt.TaskSpec != nil && !taskKinds[TaskKind(pt.TaskSpec.Kind)]:
errs = errs.Also(pt.validateCustomTask())
case pt.TaskSpec != nil && pt.TaskSpec.APIVersion != "":
errs = errs.Also(pt.validateCustomTask())
default:
errs = errs.Also(pt.validateTask(ctx))
}
return errs
}
func (pt *PipelineTask) validateMatrix(ctx context.Context) (errs *apis.FieldError) {
if pt.IsMatrixed() {
// This is a beta feature and will fail validation if it's used in a pipeline spec
// when the enable-api-fields feature gate is set to "stable".
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, "matrix", config.BetaAPIFields))
errs = errs.Also(pt.Matrix.validateCombinationsCount(ctx))
errs = errs.Also(pt.Matrix.validateUniqueParams())
}
errs = errs.Also(pt.Matrix.validateParameterInOneOfMatrixOrParams(pt.Params))
return errs
}
func (pt PipelineTask) validateEmbeddedOrType() (errs *apis.FieldError) {
// Reject cases where APIVersion and/or Kind are specified alongside an embedded Task.
// We determine if this is an embedded Task by checking of TaskSpec.TaskSpec.Steps has items.
if pt.TaskSpec != nil && len(pt.TaskSpec.TaskSpec.Steps) > 0 {
if pt.TaskSpec.APIVersion != "" {
errs = errs.Also(&apis.FieldError{
Message: "taskSpec.apiVersion cannot be specified when using taskSpec.steps",
Paths: []string{"taskSpec.apiVersion"},
})
}
if pt.TaskSpec.Kind != "" {
errs = errs.Also(&apis.FieldError{
Message: "taskSpec.kind cannot be specified when using taskSpec.steps",
Paths: []string{"taskSpec.kind"},
})
}
}
return
}
func (pt *PipelineTask) validateWorkspaces(workspaceNames sets.String) (errs *apis.FieldError) {
workspaceBindingNames := sets.NewString()
for i, ws := range pt.Workspaces {
if workspaceBindingNames.Has(ws.Name) {
errs = errs.Also(apis.ErrGeneric(
fmt.Sprintf("workspace name %q must be unique", ws.Name), "").ViaFieldIndex("workspaces", i))
}
if ws.Workspace == "" {
if !workspaceNames.Has(ws.Name) {
errs = errs.Also(apis.ErrInvalidValue(
fmt.Sprintf("pipeline task %q expects workspace with name %q but none exists in pipeline spec", pt.Name, ws.Name),
"",
).ViaFieldIndex("workspaces", i))
}
} else if !workspaceNames.Has(ws.Workspace) {
errs = errs.Also(apis.ErrInvalidValue(
fmt.Sprintf("pipeline task %q expects workspace with name %q but none exists in pipeline spec", pt.Name, ws.Workspace),
"",
).ViaFieldIndex("workspaces", i))
}
workspaceBindingNames.Insert(ws.Name)
}
return errs
}
// validateRefOrSpec validates at least one of taskRef or taskSpec or pipelineRef or pipelineSpec is specified
func (pt PipelineTask) validateRefOrSpec(ctx context.Context) (errs *apis.FieldError) {
// collect all the specified specifications
nonNilFields := []string{}
if pt.TaskRef != nil {
nonNilFields = append(nonNilFields, taskRef)
}
if pt.TaskSpec != nil {
nonNilFields = append(nonNilFields, taskSpec)
}
if pt.PipelineRef != nil {
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, pipelineRef, config.AlphaAPIFields))
nonNilFields = append(nonNilFields, pipelineRef)
}
if pt.PipelineSpec != nil {
errs = errs.Also(config.ValidateEnabledAPIFields(ctx, pipelineSpec, config.AlphaAPIFields))
nonNilFields = append(nonNilFields, pipelineSpec)
}
// check the length of nonNilFields
// if one of taskRef or taskSpec or pipelineRef or pipelineSpec is specified,
// the length of nonNilFields should exactly be 1
if len(nonNilFields) > 1 {
errs = errs.Also(apis.ErrGeneric("expected exactly one, got multiple", nonNilFields...))
} else if len(nonNilFields) == 0 {
cfg := config.FromContextOrDefaults(ctx)
// check for TaskRef or TaskSpec or PipelineRef or PipelineSpec with alpha feature flag
if cfg.FeatureFlags.EnableAPIFields == config.AlphaAPIFields {
errs = errs.Also(apis.ErrMissingOneOf(taskRef, taskSpec, pipelineRef, pipelineSpec))
} else {
// check for taskRef and taskSpec with beta/stable feature flag
errs = errs.Also(apis.ErrMissingOneOf(taskRef, taskSpec))
}
}
return errs
}
// validateCustomTask validates custom task specifications - checking kind and fail if not yet supported features specified
func (pt PipelineTask) validateCustomTask() (errs *apis.FieldError) {
if pt.TaskRef != nil && pt.TaskRef.Kind == "" {
errs = errs.Also(apis.ErrInvalidValue("custom task ref must specify kind", "taskRef.kind"))
}
if pt.TaskSpec != nil && pt.TaskSpec.Kind == "" {
errs = errs.Also(apis.ErrInvalidValue("custom task spec must specify kind", "taskSpec.kind"))
}
if pt.TaskRef != nil && pt.TaskRef.APIVersion == "" {
errs = errs.Also(apis.ErrInvalidValue("custom task ref must specify apiVersion", "taskRef.apiVersion"))
}
if pt.TaskSpec != nil && pt.TaskSpec.APIVersion == "" {
errs = errs.Also(apis.ErrInvalidValue("custom task spec must specify apiVersion", "taskSpec.apiVersion"))
}
return errs
}
// validateTask validates a pipeline task or a final task for taskRef and taskSpec
func (pt PipelineTask) validateTask(ctx context.Context) (errs *apis.FieldError) {
// Validate TaskSpec if it's present
if pt.TaskSpec != nil {
errs = errs.Also(pt.TaskSpec.Validate(ctx).ViaField(taskSpec))
}
if pt.TaskRef != nil {
errs = errs.Also(pt.TaskRef.Validate(ctx).ViaField(taskRef))
}
if pt.PipelineRef != nil {
errs = errs.Also(pt.PipelineRef.Validate(ctx).ViaField(pipelineRef))
}
if pt.PipelineSpec != nil {
errs = errs.Also(pt.PipelineSpec.Validate(ctx).ViaField(pipelineSpec))
}
return errs
}
// validatePipelineWorkspacesDeclarations validates the specified workspaces, ensuring having unique name without any
// empty string,
func validatePipelineWorkspacesDeclarations(wss []PipelineWorkspaceDeclaration) (errs *apis.FieldError) {
// Workspace names must be non-empty and unique.
wsTable := sets.NewString()
for i, ws := range wss {
if ws.Name == "" {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("workspace %d has empty name", i),
"").ViaFieldIndex("workspaces", i))
}
if wsTable.Has(ws.Name) {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("workspace with name %q appears more than once", ws.Name),
"").ViaFieldIndex("workspaces", i))
}
wsTable.Insert(ws.Name)
}
return errs
}
// validatePipelineParameterUsage validates that parameters referenced in the Pipeline are declared by the Pipeline
func (ps *PipelineSpec) validatePipelineParameterUsage(ctx context.Context) (errs *apis.FieldError) {
errs = errs.Also(PipelineTaskList(ps.Tasks).validateUsageOfDeclaredPipelineTaskParameters(ctx, "tasks"))
errs = errs.Also(PipelineTaskList(ps.Finally).validateUsageOfDeclaredPipelineTaskParameters(ctx, "finally"))
errs = errs.Also(validatePipelineTaskParameterUsage(ps.Tasks, ps.Params).ViaField("tasks"))
errs = errs.Also(validatePipelineTaskParameterUsage(ps.Finally, ps.Params).ViaField("finally"))
return errs
}
// validatePipelineTaskParameterUsage validates that parameters referenced in the Pipeline Tasks are declared by the Pipeline
func validatePipelineTaskParameterUsage(tasks []PipelineTask, params ParamSpecs) (errs *apis.FieldError) {
allParamNames := sets.NewString(params.GetNames()...)
_, arrayParams, objectParams := params.SortByType()
arrayParamNames := sets.NewString(arrayParams.GetNames()...)
objectParameterNameKeys := map[string][]string{}
for _, p := range objectParams {
for k := range p.Properties {
objectParameterNameKeys[p.Name] = append(objectParameterNameKeys[p.Name], k)
}
}
errs = errs.Also(validatePipelineParametersVariables(tasks, "params", allParamNames, arrayParamNames, objectParameterNameKeys))
for i, task := range tasks {
errs = errs.Also(task.Params.validateDuplicateParameters().ViaFieldIndex("params", i))
}
return errs
}
// validatePipelineWorkspacesUsage validates that workspaces referenced in the Pipeline are declared by the Pipeline
func (ps *PipelineSpec) validatePipelineWorkspacesUsage() (errs *apis.FieldError) {
errs = errs.Also(validatePipelineTasksWorkspacesUsage(ps.Workspaces, ps.Tasks).ViaField("tasks"))
errs = errs.Also(validatePipelineTasksWorkspacesUsage(ps.Workspaces, ps.Finally).ViaField("finally"))
return errs
}
// validatePipelineTasksWorkspacesUsage validates that all the referenced workspaces (by pipeline tasks) are specified in
// the pipeline
func validatePipelineTasksWorkspacesUsage(wss []PipelineWorkspaceDeclaration, pts []PipelineTask) (errs *apis.FieldError) {
workspaceNames := sets.NewString()
for _, ws := range wss {
workspaceNames.Insert(ws.Name)
}
// Any workspaces used in PipelineTasks should have their name declared in the Pipeline's Workspaces list.
for i, pt := range pts {
errs = errs.Also(pt.validateWorkspaces(workspaceNames).ViaIndex(i))
}
return errs
}
// ValidatePipelineParameterVariables validates parameters with those specified by each pipeline task,
// (1) it validates the type of parameter is either string or array (2) parameter default value matches
// with the type of that param (3) no duplication, feature flag and allowed param type when using param enum
func ValidatePipelineParameterVariables(ctx context.Context, tasks []PipelineTask, params ParamSpecs) (errs *apis.FieldError) {
// validates all the types within a slice of ParamSpecs
errs = errs.Also(ValidateParameterTypes(ctx, params).ViaField("params"))
errs = errs.Also(params.ValidateNoDuplicateNames())
errs = errs.Also(params.validateParamEnums(ctx).ViaField("params"))
for i, task := range tasks {
errs = errs.Also(task.Params.validateDuplicateParameters().ViaField("params").ViaIndex(i))
}
return errs
}
func validatePipelineParametersVariables(tasks []PipelineTask, prefix string, paramNames sets.String, arrayParamNames sets.String, objectParamNameKeys map[string][]string) (errs *apis.FieldError) {
for idx, task := range tasks {
errs = errs.Also(validatePipelineParametersVariablesInTaskParameters(task.Params, prefix, paramNames, arrayParamNames, objectParamNameKeys).ViaIndex(idx))
if task.IsMatrixed() {
errs = errs.Also(task.Matrix.validatePipelineParametersVariablesInMatrixParameters(prefix, paramNames, arrayParamNames, objectParamNameKeys).ViaIndex(idx))
}
errs = errs.Also(task.When.validatePipelineParametersVariables(prefix, paramNames, arrayParamNames, objectParamNameKeys).ViaIndex(idx))
}
return errs
}
func validatePipelineContextVariables(tasks []PipelineTask) *apis.FieldError {
pipelineRunContextNames := sets.NewString().Insert(
"name",
"namespace",
"uid",
)
pipelineContextNames := sets.NewString().Insert(
"name",
)
pipelineTaskContextNames := sets.NewString().Insert(
"retries",
)
var paramValues []string
for _, task := range tasks {
paramValues = task.extractAllParams().extractValues()
}
errs := validatePipelineContextVariablesInParamValues(paramValues, "context\\.pipelineRun", pipelineRunContextNames).
Also(validatePipelineContextVariablesInParamValues(paramValues, "context\\.pipeline", pipelineContextNames)).
Also(validatePipelineContextVariablesInParamValues(paramValues, "context\\.pipelineTask", pipelineTaskContextNames))
return errs
}
// extractAllParams extracts all the parameters in a PipelineTask:
// - pt.Params
// - pt.Matrix.Params
// - pt.Matrix.Include.Params
func (pt *PipelineTask) extractAllParams() Params {
allParams := pt.Params
if pt.Matrix.HasParams() {
allParams = append(allParams, pt.Matrix.Params...)
}
if pt.Matrix.HasInclude() {
for _, include := range pt.Matrix.Include {
allParams = append(allParams, include.Params...)
}
}
return allParams
}
// GetVarSubstitutionExpressions extract all values between the parameters "$(" and ")" of steps and sidecars
func (pt *PipelineTask) GetVarSubstitutionExpressions() []string {
var allExpressions []string
if pt.TaskSpec != nil {
for _, step := range pt.TaskSpec.Steps {
stepExpressions := step.GetVarSubstitutionExpressions()
allExpressions = append(allExpressions, stepExpressions...)
}
for _, sidecar := range pt.TaskSpec.Sidecars {
sidecarExpressions := sidecar.GetVarSubstitutionExpressions()
allExpressions = append(allExpressions, sidecarExpressions...)
}
}
return allExpressions
}
func containsExecutionStatusRef(p string) bool {
if strings.HasPrefix(p, "tasks.") && strings.HasSuffix(p, ".status") {
return true
}
return false
}
func validateExecutionStatusVariables(tasks []PipelineTask, finallyTasks []PipelineTask) (errs *apis.FieldError) {
errs = errs.Also(validateExecutionStatusVariablesInTasks(tasks).ViaField("tasks"))
errs = errs.Also(validateExecutionStatusVariablesInFinally(PipelineTaskList(tasks).Names(), finallyTasks).ViaField("finally"))
return errs
}
// validate dag pipeline tasks, task params can not access execution status of any other task
// dag tasks cannot have param value as $(tasks.pipelineTask.status)
func validateExecutionStatusVariablesInTasks(tasks []PipelineTask) (errs *apis.FieldError) {
for idx, t := range tasks {
errs = errs.Also(t.validateExecutionStatusVariablesDisallowed()).ViaIndex(idx)
}
return errs
}
// validate finally tasks accessing execution status of a dag task specified in the pipeline
// $(tasks.pipelineTask.status) is invalid if pipelineTask is not defined as a dag task
func validateExecutionStatusVariablesInFinally(tasksNames sets.String, finally []PipelineTask) (errs *apis.FieldError) {
for idx, t := range finally {
errs = errs.Also(t.validateExecutionStatusVariablesAllowed(tasksNames).ViaIndex(idx))
}
return errs
}
func (pt *PipelineTask) validateExecutionStatusVariablesDisallowed() (errs *apis.FieldError) {
for _, param := range pt.Params {
if expressions, ok := param.GetVarSubstitutionExpressions(); ok {
errs = errs.Also(validateContainsExecutionStatusVariablesDisallowed(expressions, "value").
ViaFieldKey("params", param.Name))
}
}
for i, we := range pt.When {
if expressions, ok := we.GetVarSubstitutionExpressions(); ok {
errs = errs.Also(validateContainsExecutionStatusVariablesDisallowed(expressions, "").
ViaFieldIndex("when", i))
}
}
return errs
}
func (pt *PipelineTask) validateExecutionStatusVariablesAllowed(ptNames sets.String) (errs *apis.FieldError) {
for _, param := range pt.Params {
if expressions, ok := param.GetVarSubstitutionExpressions(); ok {
errs = errs.Also(validateExecutionStatusVariablesExpressions(expressions, ptNames, "value").
ViaFieldKey("params", param.Name))
}
}
for i, we := range pt.When {
if expressions, ok := we.GetVarSubstitutionExpressions(); ok {
errs = errs.Also(validateExecutionStatusVariablesExpressions(expressions, ptNames, "").
ViaFieldIndex("when", i))
}
}
return errs
}
func validateContainsExecutionStatusVariablesDisallowed(expressions []string, path string) (errs *apis.FieldError) {
if containsExecutionStatusReferences(expressions) {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("pipeline tasks can not refer to execution status"+
" of any other pipeline task or aggregate status of tasks"), path))
}
return errs
}
func containsExecutionStatusReferences(expressions []string) bool {
// validate tasks.pipelineTask.status/tasks.status if this expression is not a result reference
if !LooksLikeContainsResultRefs(expressions) {
for _, e := range expressions {
// check if it contains context variable accessing execution status - $(tasks.taskname.status)
// or an aggregate status - $(tasks.status)
if containsExecutionStatusRef(e) {
return true
}
}
}
return false
}
func validateExecutionStatusVariablesExpressions(expressions []string, ptNames sets.String, fieldPath string) (errs *apis.FieldError) {
// validate tasks.pipelineTask.status if this expression is not a result reference
if !LooksLikeContainsResultRefs(expressions) {
for _, expression := range expressions {
// its a reference to aggregate status of dag tasks - $(tasks.status)
if expression == PipelineTasksAggregateStatus {
continue
}
// check if it contains context variable accessing execution status - $(tasks.taskname.status)
if containsExecutionStatusRef(expression) {
// strip tasks. and .status from tasks.taskname.status to further verify task name
pt := strings.TrimSuffix(strings.TrimPrefix(expression, "tasks."), ".status")
// report an error if the task name does not exist in the list of dag tasks
if !ptNames.Has(pt) {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("pipeline task %s is not defined in the pipeline", pt), fieldPath))
}
}
}
}
return errs
}
func validatePipelineContextVariablesInParamValues(paramValues []string, prefix string, contextNames sets.String) (errs *apis.FieldError) {
for _, paramValue := range paramValues {
errs = errs.Also(substitution.ValidateNoReferencesToUnknownVariables(paramValue, prefix, contextNames).ViaField("value"))
}
return errs
}
func filter(arr []string, cond func(string) bool) []string {
result := []string{}
for i := range arr {
if cond(arr[i]) {
result = append(result, arr[i])
}
}
return result
}
// validatePipelineResults ensure that pipeline result variables are properly configured
func validatePipelineResults(results []PipelineResult, tasks []PipelineTask, finally []PipelineTask) (errs *apis.FieldError) {
pipelineTaskNames := getPipelineTasksNames(tasks)
pipelineFinallyTaskNames := getPipelineTasksNames(finally)
for idx, result := range results {
expressions, ok := result.GetVarSubstitutionExpressions()
if !ok {
errs = errs.Also(apis.ErrInvalidValue("expected pipeline results to be task result expressions but no expressions were found",
"value").ViaFieldIndex("results", idx))
}
if !LooksLikeContainsResultRefs(expressions) {
errs = errs.Also(apis.ErrInvalidValue("expected pipeline results to be task result expressions but an invalid expressions was found",
"value").ViaFieldIndex("results", idx))
}
expressions = filter(expressions, looksLikeResultRef)
resultRefs := NewResultRefs(expressions)
if len(expressions) != len(resultRefs) {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("expected all of the expressions %v to be result expressions but only %v were", expressions, resultRefs),
"value").ViaFieldIndex("results", idx))
}
if !taskContainsResult(result.Value.StringVal, pipelineTaskNames, pipelineFinallyTaskNames) {
errs = errs.Also(apis.ErrInvalidValue("referencing a nonexistent task",
"value").ViaFieldIndex("results", idx))
}
}
return errs
}
// put task names in a set
func getPipelineTasksNames(pipelineTasks []PipelineTask) sets.String {
pipelineTaskNames := make(sets.String)
for _, pipelineTask := range pipelineTasks {
pipelineTaskNames.Insert(pipelineTask.Name)
}
return pipelineTaskNames
}
// taskContainsResult ensures the result value is referenced within the
// task names
func taskContainsResult(resultExpression string, pipelineTaskNames sets.String, pipelineFinallyTaskNames sets.String) bool {
// split incase of multiple resultExpressions in the same result.Value string
// i.e "$(task.<task-name).result.<result-name>) - $(task2.<task2-name).result2.<result2-name>)"
split := strings.Split(resultExpression, "$")
for _, expression := range split {
if expression != "" {
value := stripVarSubExpression("$" + expression)
pipelineTaskName, _, _, _, err := parseExpression(value)
if err != nil {
return false
}
if strings.HasPrefix(value, "tasks") && !pipelineTaskNames.Has(pipelineTaskName) {
return false
}
if strings.HasPrefix(value, "finally") && !pipelineFinallyTaskNames.Has(pipelineTaskName) {
return false
}
}
}
return true
}
func validateTasksAndFinallySection(ps *PipelineSpec) *apis.FieldError {
if len(ps.Finally) != 0 && len(ps.Tasks) == 0 {
return apis.ErrInvalidValue(fmt.Sprintf("spec.tasks is empty but spec.finally has %d tasks", len(ps.Finally)), "finally")
}
return nil
}
func validateFinalTasks(tasks []PipelineTask, finalTasks []PipelineTask) (errs *apis.FieldError) {
for idx, f := range finalTasks {
if len(f.RunAfter) != 0 {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("no runAfter allowed under spec.finally, final task %s has runAfter specified", f.Name), "").ViaFieldIndex("finally", idx))
}
}
ts := PipelineTaskList(tasks).Names()
fts := PipelineTaskList(finalTasks).Names()
errs = errs.Also(validateTaskResultReferenceInFinallyTasks(finalTasks, ts, fts))
return errs
}
func validateTaskResultReferenceInFinallyTasks(finalTasks []PipelineTask, ts sets.String, fts sets.String) (errs *apis.FieldError) {
for idx, t := range finalTasks {
for _, p := range t.Params {
if expressions, ok := p.GetVarSubstitutionExpressions(); ok {
errs = errs.Also(validateResultsVariablesExpressionsInFinally(expressions, ts, fts, "value").ViaFieldKey(
"params", p.Name).ViaFieldIndex("finally", idx))
}
}
for i, we := range t.When {
if expressions, ok := we.GetVarSubstitutionExpressions(); ok {
errs = errs.Also(validateResultsVariablesExpressionsInFinally(expressions, ts, fts, "").ViaFieldIndex(
"when", i).ViaFieldIndex("finally", idx))
}
}
}
return errs
}
func validateResultsVariablesExpressionsInFinally(expressions []string, pipelineTasksNames sets.String, finalTasksNames sets.String, fieldPath string) (errs *apis.FieldError) {
if LooksLikeContainsResultRefs(expressions) {
resultRefs := NewResultRefs(expressions)
for _, resultRef := range resultRefs {
pt := resultRef.PipelineTask
if finalTasksNames.Has(pt) {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("invalid task result reference, "+
"final task has task result reference from a final task %s", pt), fieldPath))
} else if !pipelineTasksNames.Has(resultRef.PipelineTask) {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("invalid task result reference, "+
"final task has task result reference from a task %s which is not defined in the pipeline", pt), fieldPath))
}
}
}
return errs
}
func validateWhenExpressions(ctx context.Context, tasks []PipelineTask, finalTasks []PipelineTask) (errs *apis.FieldError) {
for i, t := range tasks {
errs = errs.Also(t.When.validate(ctx).ViaFieldIndex("tasks", i))
}
for i, t := range finalTasks {
errs = errs.Also(t.When.validate(ctx).ViaFieldIndex("finally", i))
}
return errs
}
// validateGraph ensures the Pipeline's dependency Graph (DAG) make sense: that there is no dependency
// cycle or that they rely on values from Tasks that ran previously.
func validateGraph(tasks []PipelineTask) (errs *apis.FieldError) {
if _, err := dag.Build(PipelineTaskList(tasks), PipelineTaskList(tasks).Deps()); err != nil {
errs = errs.Also(apis.ErrInvalidValue(err.Error(), "tasks"))
}
return errs
}
func validateMatrix(ctx context.Context, tasks []PipelineTask) (errs *apis.FieldError) {
for idx, task := range tasks {
errs = errs.Also(task.validateMatrix(ctx).ViaIndex(idx))
}
errs = errs.Also(validateTaskResultsFromMatrixedPipelineTasksConsumed(tasks))
return errs
}
// findAndValidateResultRefsForMatrix checks that any result references to Matrixed PipelineTasks if consumed
// by another PipelineTask that the entire array of results produced by a matrix is consumed in aggregate
// since consuming a singular result produced by a matrix is currently not supported
func findAndValidateResultRefsForMatrix(tasks []PipelineTask, taskMapping map[string]PipelineTask) (resultRefs []*ResultRef, errs *apis.FieldError) {
for _, t := range tasks {
for _, p := range t.Params {
if expressions, ok := p.GetVarSubstitutionExpressions(); ok {
if LooksLikeContainsResultRefs(expressions) {
resultRefs, errs = validateMatrixedPipelineTaskConsumed(expressions, taskMapping)
if errs != nil {
return nil, errs
}
}
}
}
}
return resultRefs, errs
}
// validateMatrixedPipelineTaskConsumed checks that any Matrixed Pipeline Task that the is being consumed is consumed in
// aggregate [*] since consuming a singular result produced by a matrix is currently not supported
func validateMatrixedPipelineTaskConsumed(expressions []string, taskMapping map[string]PipelineTask) (resultRefs []*ResultRef, errs *apis.FieldError) {
var filteredExpressions []string
for _, expression := range expressions {
// ie. "tasks.<pipelineTaskName>.results.<resultName>[*]"
subExpressions := strings.Split(expression, ".")
pipelineTask := subExpressions[1] // pipelineTaskName
taskConsumed := taskMapping[pipelineTask]
if taskConsumed.IsMatrixed() {
if !strings.HasSuffix(expression, "[*]") {
errs = errs.Also(apis.ErrGeneric(fmt.Sprintf("A matrixed pipelineTask can only be consumed in aggregate using [*] notation, but is currently set to %s", expression)))
}
filteredExpressions = append(filteredExpressions, expression)
}
}
return NewResultRefs(filteredExpressions), errs
}
// validateTaskResultsFromMatrixedPipelineTasksConsumed checks that any Matrixed Pipeline Task that the is being consumed
// is consumed in aggregate [*] since consuming a singular result produced by a matrix is currently not supported.
// It also validates that a matrix emitting results can only emit results with the underlying type string
// if those results are being consumed by another PipelineTask.
func validateTaskResultsFromMatrixedPipelineTasksConsumed(tasks []PipelineTask) (errs *apis.FieldError) {
taskMapping := createTaskMapping(tasks)
resultRefs, errs := findAndValidateResultRefsForMatrix(tasks, taskMapping)
if errs != nil {
return errs
}
errs = errs.Also(validateMatrixEmittingStringResults(resultRefs, taskMapping))
return errs
}
// createTaskMapping maps the PipelineTaskName to the PipelineTask to easily access
// the pipelineTask by Name
func createTaskMapping(tasks []PipelineTask) (taskMap map[string]PipelineTask) {
taskMapping := make(map[string]PipelineTask)
for _, task := range tasks {
taskMapping[task.Name] = task
}
return taskMapping
}
// validateMatrixEmittingStringResults checks a matrix emitting results can only emit results with the underlying type string
// if those results are being consumed by another PipelineTask. Note: It is not possible to validate remote tasks
func validateMatrixEmittingStringResults(resultRefs []*ResultRef, taskMapping map[string]PipelineTask) (errs *apis.FieldError) {
for _, resultRef := range resultRefs {
task := taskMapping[resultRef.PipelineTask]
resultName := resultRef.Result
if task.TaskRef != nil {
referencedTask := taskMapping[task.TaskRef.Name]
if referencedTask.TaskSpec != nil {
errs = errs.Also(validateStringResults(referencedTask.TaskSpec.Results, resultName))
}
} else if task.TaskSpec != nil {
errs = errs.Also(validateStringResults(task.TaskSpec.Results, resultName))
}
}
return errs
}
// validateStringResults ensure that the result type is string
func validateStringResults(results []TaskResult, resultName string) (errs *apis.FieldError) {
for _, result := range results {
if result.Name == resultName {
if result.Type != ResultsTypeString {
errs = errs.Also(apis.ErrInvalidValue(
fmt.Sprintf("Matrixed PipelineTasks emitting results must have an underlying type string, but result %s has type %s in pipelineTask", resultName, string(result.Type)),
"",
))
}
}
}
return errs
}
// GetIndexingReferencesToArrayParams returns all strings referencing indices of PipelineRun array parameters
// from parameters, workspaces, and when expressions defined in the Pipeline's Tasks and Finally Tasks.
// For example, if a Task in the Pipeline has a parameter with a value "$(params.array-param-name[1])",
// this would be one of the strings returned.
func (ps *PipelineSpec) GetIndexingReferencesToArrayParams() sets.String {
paramsRefs := []string{}
for i := range ps.Tasks {
paramsRefs = append(paramsRefs, ps.Tasks[i].Params.extractValues()...)
if ps.Tasks[i].IsMatrixed() {
paramsRefs = append(paramsRefs, ps.Tasks[i].Matrix.Params.extractValues()...)
}
for j := range ps.Tasks[i].Workspaces {
paramsRefs = append(paramsRefs, ps.Tasks[i].Workspaces[j].SubPath)
}
for _, wes := range ps.Tasks[i].When {
paramsRefs = append(paramsRefs, wes.Input)
paramsRefs = append(paramsRefs, wes.Values...)
}
}
for i := range ps.Finally {
paramsRefs = append(paramsRefs, ps.Finally[i].Params.extractValues()...)
if ps.Finally[i].IsMatrixed() {
paramsRefs = append(paramsRefs, ps.Finally[i].Matrix.Params.extractValues()...)
}
for _, wes := range ps.Finally[i].When {
paramsRefs = append(paramsRefs, wes.Input)
paramsRefs = append(paramsRefs, wes.Values...)
}
}
// extract all array indexing references, for example []{"$(params.array-params[1])"}
arrayIndexParamRefs := []string{}
for _, p := range paramsRefs {
arrayIndexParamRefs = append(arrayIndexParamRefs, extractArrayIndexingParamRefs(p)...)
}
return sets.NewString(arrayIndexParamRefs...)
}