/
pipeline_types.go
509 lines (440 loc) · 18.4 KB
/
pipeline_types.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
/*
Copyright 2020 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 v1beta1
import (
"context"
"fmt"
"strings"
"github.com/google/go-containerregistry/pkg/name"
"github.com/tektoncd/pipeline/pkg/apis/config"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
"github.com/tektoncd/pipeline/pkg/reconciler/pipeline/dag"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
"knative.dev/pkg/apis"
"knative.dev/pkg/kmeta"
)
const (
// PipelineTasksAggregateStatus is a param representing aggregate status of all dag pipelineTasks
PipelineTasksAggregateStatus = "tasks.status"
// PipelineTasks is a value representing a task is a member of "tasks" section of the pipeline
PipelineTasks = "tasks"
// PipelineFinallyTasks is a value representing a task is a member of "finally" section of the pipeline
PipelineFinallyTasks = "finally"
)
// +genclient
// +genclient:noStatus
// +genreconciler:krshapedlogic=false
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Pipeline describes a list of Tasks to execute. It expresses how outputs
// of tasks feed into inputs of subsequent tasks.
// +k8s:openapi-gen=true
type Pipeline struct {
metav1.TypeMeta `json:",inline"`
// +optional
metav1.ObjectMeta `json:"metadata,omitempty"`
// Spec holds the desired state of the Pipeline from the client
// +optional
Spec PipelineSpec `json:"spec"`
}
var _ kmeta.OwnerRefable = (*Pipeline)(nil)
// PipelineMetadata returns the Pipeline's ObjectMeta, implementing PipelineObject
func (p *Pipeline) PipelineMetadata() metav1.ObjectMeta {
return p.ObjectMeta
}
// PipelineSpec returns the Pipeline's Spec, implementing PipelineObject
func (p *Pipeline) PipelineSpec() PipelineSpec {
return p.Spec
}
// Copy returns a deep copy of the Pipeline, implementing PipelineObject
func (p *Pipeline) Copy() PipelineObject {
return p.DeepCopy()
}
// GetGroupVersionKind implements kmeta.OwnerRefable.
func (*Pipeline) GetGroupVersionKind() schema.GroupVersionKind {
return SchemeGroupVersion.WithKind(pipeline.PipelineControllerName)
}
// PipelineSpec defines the desired state of Pipeline.
type PipelineSpec struct {
// Description is a user-facing description of the pipeline that may be
// used to populate a UI.
// +optional
Description string `json:"description,omitempty"`
// Resources declares the names and types of the resources given to the
// Pipeline's tasks as inputs and outputs.
Resources []PipelineDeclaredResource `json:"resources,omitempty"`
// Tasks declares the graph of Tasks that execute when this Pipeline is run.
Tasks []PipelineTask `json:"tasks,omitempty"`
// Params declares a list of input parameters that must be supplied when
// this Pipeline is run.
Params []ParamSpec `json:"params,omitempty"`
// Workspaces declares a set of named workspaces that are expected to be
// provided by a PipelineRun.
// +optional
Workspaces []PipelineWorkspaceDeclaration `json:"workspaces,omitempty"`
// Results are values that this pipeline can output once run
// +optional
Results []PipelineResult `json:"results,omitempty"`
// Finally declares the list of Tasks that execute just before leaving the Pipeline
// i.e. either after all Tasks are finished executing successfully
// or after a failure which would result in ending the Pipeline
Finally []PipelineTask `json:"finally,omitempty"`
}
// PipelineResult used to describe the results of a pipeline
type PipelineResult struct {
// Name the given name
Name string `json:"name"`
// Description is a human-readable description of the result
// +optional
Description string `json:"description"`
// Value the expression used to retrieve the value
Value string `json:"value"`
}
// PipelineTaskMetadata contains the labels or annotations for an EmbeddedTask
type PipelineTaskMetadata struct {
// +optional
Labels map[string]string `json:"labels,omitempty"`
// +optional
Annotations map[string]string `json:"annotations,omitempty"`
}
// EmbeddedTask is used to define a Task inline within a Pipeline's PipelineTasks.
type EmbeddedTask struct {
// +optional
runtime.TypeMeta `json:",inline,omitempty"`
// Spec is a specification of a custom task
// +optional
Spec runtime.RawExtension `json:"spec,omitempty"`
// +optional
Metadata PipelineTaskMetadata `json:"metadata,omitempty"`
// TaskSpec is a specification of a task
// +optional
TaskSpec `json:",inline,omitempty"`
}
// PipelineTask defines a task in a Pipeline, passing inputs from both
// Params and from the output of previous tasks.
type PipelineTask struct {
// Name is the name of this task within the context of a Pipeline. Name is
// used as a coordinate with the `from` and `runAfter` fields to establish
// the execution order of tasks relative to one another.
Name string `json:"name,omitempty"`
// TaskRef is a reference to a task definition.
// +optional
TaskRef *TaskRef `json:"taskRef,omitempty"`
// TaskSpec is a specification of a task
// +optional
TaskSpec *EmbeddedTask `json:"taskSpec,omitempty"`
// Conditions is a list of conditions that need to be true for the task to run
// Conditions are deprecated, use WhenExpressions instead
// +optional
Conditions []PipelineTaskCondition `json:"conditions,omitempty"`
// WhenExpressions is a list of when expressions that need to be true for the task to run
// +optional
WhenExpressions WhenExpressions `json:"when,omitempty"`
// Retries represents how many times this task should be retried in case of task failure: ConditionSucceeded set to False
// +optional
Retries int `json:"retries,omitempty"`
// RunAfter is the list of PipelineTask names that should be executed before
// this Task executes. (Used to force a specific ordering in graph execution.)
// +optional
RunAfter []string `json:"runAfter,omitempty"`
// Resources declares the resources given to this task as inputs and
// outputs.
// +optional
Resources *PipelineTaskResources `json:"resources,omitempty"`
// Parameters declares parameters passed to this task.
// +optional
Params []Param `json:"params,omitempty"`
// Workspaces maps workspaces from the pipeline spec to the workspaces
// declared in the Task.
// +optional
Workspaces []WorkspacePipelineTaskBinding `json:"workspaces,omitempty"`
// Time after which the TaskRun times out. Defaults to 1 hour.
// Specified TaskRun timeout should be less than 24h.
// Refer Go's ParseDuration documentation for expected format: https://golang.org/pkg/time/#ParseDuration
// +optional
Timeout *metav1.Duration `json:"timeout,omitempty"`
}
// validateRefOrSpec validates at least one of taskRef or taskSpec is specified
func (pt PipelineTask) validateRefOrSpec() (errs *apis.FieldError) {
// can't have both taskRef and taskSpec at the same time
if pt.TaskRef != nil && pt.TaskSpec != nil {
errs = errs.Also(apis.ErrMultipleOneOf("taskRef", "taskSpec"))
}
// Check that one of TaskRef and TaskSpec is present
if pt.TaskRef == nil && pt.TaskSpec == nil {
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"))
}
// Conditions are deprecated so the effort to support them with custom tasks is not justified.
// When expressions should be used instead.
if len(pt.Conditions) > 0 {
errs = errs.Also(apis.ErrInvalidValue("custom tasks do not support conditions - use when expressions instead", "conditions"))
}
// TODO(#3133): Support these features if possible.
if pt.Resources != nil {
errs = errs.Also(apis.ErrInvalidValue("custom tasks do not support PipelineResources", "resources"))
}
return errs
}
// validateBundle validates bundle specifications - checking name and bundle
func (pt PipelineTask) validateBundle() (errs *apis.FieldError) {
// bundle requires a TaskRef to be specified
if (pt.TaskRef != nil && pt.TaskRef.Bundle != "") && pt.TaskRef.Name == "" {
errs = errs.Also(apis.ErrMissingField("taskRef.name"))
}
// If a bundle url is specified, ensure it is parsable
if pt.TaskRef != nil && pt.TaskRef.Bundle != "" {
if _, err := name.ParseReference(pt.TaskRef.Bundle); err != nil {
errs = errs.Also(apis.ErrInvalidValue(fmt.Sprintf("invalid bundle reference (%s)", err.Error()), "taskRef.bundle"))
}
}
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 {
if pt.TaskRef.Name != "" {
// TaskRef name must be a valid k8s name
if errSlice := validation.IsQualifiedName(pt.TaskRef.Name); len(errSlice) != 0 {
errs = errs.Also(apis.ErrInvalidValue(strings.Join(errSlice, ","), "name"))
}
} else {
errs = errs.Also(apis.ErrInvalidValue("taskRef must specify name", "taskRef.name"))
}
// fail if bundle is present when EnableTektonOCIBundles feature flag is off (as it won't be allowed nor used)
if pt.TaskRef.Bundle != "" {
errs = errs.Also(apis.ErrDisallowedFields("taskref.bundle"))
}
}
return errs
}
// TaskSpecMetadata returns the metadata of the PipelineTask's EmbeddedTask spec.
func (pt *PipelineTask) TaskSpecMetadata() PipelineTaskMetadata {
return pt.TaskSpec.Metadata
}
// HashKey is the name of the PipelineTask, and is used as the key for this PipelineTask in the DAG
func (pt PipelineTask) HashKey() string {
return pt.Name
}
// 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, bundle, 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())
cfg := config.FromContextOrDefaults(ctx)
// If EnableCustomTasks feature flag is on, validate custom task specifications
// pipeline task having taskRef with APIVersion is classified as custom task
switch {
case cfg.FeatureFlags.EnableCustomTasks && pt.TaskRef != nil && pt.TaskRef.APIVersion != "":
errs = errs.Also(pt.validateCustomTask())
case cfg.FeatureFlags.EnableCustomTasks && pt.TaskSpec != nil && pt.TaskSpec.APIVersion != "":
errs = errs.Also(pt.validateCustomTask())
// If EnableTektonOCIBundles feature flag is on, validate bundle specifications
case cfg.FeatureFlags.EnableTektonOCIBundles && pt.TaskRef != nil && pt.TaskRef.Bundle != "":
errs = errs.Also(pt.validateBundle())
default:
errs = errs.Also(pt.validateTask(ctx))
}
return
}
// Deps returns all other PipelineTask dependencies of this PipelineTask, based on resource usage or ordering
func (pt PipelineTask) Deps() []string {
deps := []string{}
deps = append(deps, pt.resourceDeps()...)
deps = append(deps, pt.orderingDeps()...)
uniqueDeps := sets.NewString()
for _, w := range deps {
if uniqueDeps.Has(w) {
continue
}
uniqueDeps.Insert(w)
}
return uniqueDeps.List()
}
func (pt PipelineTask) resourceDeps() []string {
resourceDeps := []string{}
if pt.Resources != nil {
for _, rd := range pt.Resources.Inputs {
resourceDeps = append(resourceDeps, rd.From...)
}
}
// Add any dependents from conditional resources.
for _, cond := range pt.Conditions {
for _, rd := range cond.Resources {
resourceDeps = append(resourceDeps, rd.From...)
}
}
// Add any dependents from result references.
for _, ref := range PipelineTaskResultRefs(&pt) {
resourceDeps = append(resourceDeps, ref.PipelineTask)
}
return resourceDeps
}
func (pt PipelineTask) orderingDeps() []string {
orderingDeps := []string{}
for _, runAfter := range pt.RunAfter {
orderingDeps = append(orderingDeps, runAfter)
}
return orderingDeps
}
// PipelineTaskList is a list of PipelineTasks
type PipelineTaskList []PipelineTask
// Deps returns a map with key as name of a pipelineTask and value as a list of its dependencies
func (l PipelineTaskList) Deps() map[string][]string {
deps := map[string][]string{}
for _, pt := range l {
// get the list of deps for this pipelineTask
d := pt.Deps()
// add the pipelineTask into the map if it has any deps
if len(d) > 0 {
deps[pt.HashKey()] = d
}
}
return deps
}
// Items returns a slice of all tasks in the PipelineTaskList, converted to dag.Tasks
func (l PipelineTaskList) Items() []dag.Task {
tasks := []dag.Task{}
for _, t := range l {
tasks = append(tasks, dag.Task(t))
}
return tasks
}
// Names returns a set of pipeline task names from the given list of pipeline tasks
func (l PipelineTaskList) Names() sets.String {
names := sets.String{}
for _, pt := range l {
names.Insert(pt.Name)
}
return names
}
// Validate a list of pipeline tasks including custom task and bundles
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, bundle, dag, or final task
errs = errs.Also(t.Validate(ctx).ViaFieldIndex(path, i))
}
return errs
}
// PipelineTaskParam is used to provide arbitrary string parameters to a Task.
type PipelineTaskParam struct {
Name string `json:"name"`
Value string `json:"value"`
}
// PipelineTaskCondition allows a PipelineTask to declare a Condition to be evaluated before
// the Task is run.
type PipelineTaskCondition struct {
// ConditionRef is the name of the Condition to use for the conditionCheck
ConditionRef string `json:"conditionRef"`
// Params declare parameters passed to this Condition
// +optional
Params []Param `json:"params,omitempty"`
// Resources declare the resources provided to this Condition as input
Resources []PipelineTaskInputResource `json:"resources,omitempty"`
}
// PipelineDeclaredResource is used by a Pipeline to declare the types of the
// PipelineResources that it will required to run and names which can be used to
// refer to these PipelineResources in PipelineTaskResourceBindings.
type PipelineDeclaredResource struct {
// Name is the name that will be used by the Pipeline to refer to this resource.
// It does not directly correspond to the name of any PipelineResources Task
// inputs or outputs, and it does not correspond to the actual names of the
// PipelineResources that will be bound in the PipelineRun.
Name string `json:"name"`
// Type is the type of the PipelineResource.
Type PipelineResourceType `json:"type"`
// Optional declares the resource as optional.
// optional: true - the resource is considered optional
// optional: false - the resource is considered required (default/equivalent of not specifying it)
Optional bool `json:"optional,omitempty"`
}
// PipelineTaskResources allows a Pipeline to declare how its DeclaredPipelineResources
// should be provided to a Task as its inputs and outputs.
type PipelineTaskResources struct {
// Inputs holds the mapping from the PipelineResources declared in
// DeclaredPipelineResources to the input PipelineResources required by the Task.
Inputs []PipelineTaskInputResource `json:"inputs,omitempty"`
// Outputs holds the mapping from the PipelineResources declared in
// DeclaredPipelineResources to the input PipelineResources required by the Task.
Outputs []PipelineTaskOutputResource `json:"outputs,omitempty"`
}
// PipelineTaskInputResource maps the name of a declared PipelineResource input
// dependency in a Task to the resource in the Pipeline's DeclaredPipelineResources
// that should be used. This input may come from a previous task.
type PipelineTaskInputResource struct {
// Name is the name of the PipelineResource as declared by the Task.
Name string `json:"name"`
// Resource is the name of the DeclaredPipelineResource to use.
Resource string `json:"resource"`
// From is the list of PipelineTask names that the resource has to come from.
// (Implies an ordering in the execution graph.)
// +optional
From []string `json:"from,omitempty"`
}
// PipelineTaskOutputResource maps the name of a declared PipelineResource output
// dependency in a Task to the resource in the Pipeline's DeclaredPipelineResources
// that should be used.
type PipelineTaskOutputResource struct {
// Name is the name of the PipelineResource as declared by the Task.
Name string `json:"name"`
// Resource is the name of the DeclaredPipelineResource to use.
Resource string `json:"resource"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// PipelineList contains a list of Pipeline
type PipelineList struct {
metav1.TypeMeta `json:",inline"`
// +optional
metav1.ListMeta `json:"metadata,omitempty"`
Items []Pipeline `json:"items"`
}