forked from tektoncd/pipeline
/
pipelinerunresolution.go
477 lines (422 loc) · 16.5 KB
/
pipelinerunresolution.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
/*
Copyright 2019 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 resources
import (
"fmt"
"reflect"
"go.uber.org/zap"
"golang.org/x/xerrors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"knative.dev/pkg/apis"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
"github.com/tektoncd/pipeline/pkg/list"
"github.com/tektoncd/pipeline/pkg/names"
"github.com/tektoncd/pipeline/pkg/reconciler/pipeline/dag"
"github.com/tektoncd/pipeline/pkg/reconciler/taskrun/resources"
)
const (
// ReasonRunning indicates that the reason for the inprogress status is that the TaskRun
// is just starting to be reconciled
ReasonRunning = "Running"
// ReasonFailed indicates that the reason for the failure status is that one of the TaskRuns failed
ReasonFailed = "Failed"
// ReasonSucceeded indicates that the reason for the finished status is that all of the TaskRuns
// completed successfully
ReasonSucceeded = "Succeeded"
// ReasonTimedOut indicates that the PipelineRun has taken longer than its configured
// timeout
ReasonTimedOut = "PipelineRunTimeout"
// ReasonConditionCheckFailed indicates that the reason for the failure status is that the
// condition check associated to the pipeline task evaluated to false
ReasonConditionCheckFailed = "ConditionCheckFailed"
)
// ResolvedPipelineRunTask contains a Task and its associated TaskRun, if it
// exists. TaskRun can be nil to represent there being no TaskRun.
type ResolvedPipelineRunTask struct {
TaskRunName string
TaskRun *v1alpha1.TaskRun
PipelineTask *v1alpha1.PipelineTask
ResolvedTaskResources *resources.ResolvedTaskResources
// ConditionChecks ~~TaskRuns but for evaling conditions
ResolvedConditionChecks TaskConditionCheckState // Could also be a TaskRun or maybe just a Pod?
}
// PipelineRunState is a slice of ResolvedPipelineRunTasks the represents the current execution
// state of the PipelineRun.
type PipelineRunState []*ResolvedPipelineRunTask
func (t ResolvedPipelineRunTask) IsDone() (isDone bool) {
if t.TaskRun == nil || t.PipelineTask == nil {
return
}
status := t.TaskRun.Status.GetCondition(apis.ConditionSucceeded)
retriesDone := len(t.TaskRun.Status.RetriesStatus)
retries := t.PipelineTask.Retries
isDone = status.IsTrue() || status.IsFalse() && retriesDone >= retries
return
}
// IsSuccessful returns true only if the taskrun itself has completed successfully
func (t ResolvedPipelineRunTask) IsSuccessful() bool {
if t.TaskRun == nil {
return false
}
c := t.TaskRun.Status.GetCondition(apis.ConditionSucceeded)
if c == nil {
return false
}
if c.Status == corev1.ConditionTrue {
return true
}
return false
}
// IsFailure returns true only if the taskrun itself has failed
func (t ResolvedPipelineRunTask) IsFailure() bool {
if t.TaskRun == nil {
return false
}
c := t.TaskRun.Status.GetCondition(apis.ConditionSucceeded)
retriesDone := len(t.TaskRun.Status.RetriesStatus)
retries := t.PipelineTask.Retries
return c.IsFalse() && retriesDone >= retries
}
func (state PipelineRunState) toMap() map[string]*ResolvedPipelineRunTask {
m := make(map[string]*ResolvedPipelineRunTask)
for _, rprt := range state {
m[rprt.PipelineTask.Name] = rprt
}
return m
}
func (state PipelineRunState) IsDone() (isDone bool) {
isDone = true
for _, t := range state {
if t.TaskRun == nil || t.PipelineTask == nil {
return false
}
isDone = isDone && t.IsDone()
if !isDone {
return
}
}
return
}
// GetNextTasks will return the next ResolvedPipelineRunTasks to execute, which are the ones in the
// list of candidateTasks which aren't yet indicated in state to be running.
func (state PipelineRunState) GetNextTasks(candidateTasks map[string]struct{}) []*ResolvedPipelineRunTask {
tasks := []*ResolvedPipelineRunTask{}
for _, t := range state {
if _, ok := candidateTasks[t.PipelineTask.Name]; ok && t.TaskRun == nil {
tasks = append(tasks, t)
}
if _, ok := candidateTasks[t.PipelineTask.Name]; ok && t.TaskRun != nil {
status := t.TaskRun.Status.GetCondition(apis.ConditionSucceeded)
if status != nil && status.IsFalse() {
if !(t.TaskRun.IsCancelled() || status.Reason == v1alpha1.TaskRunSpecStatusCancelled || status.Reason == ReasonConditionCheckFailed) {
if len(t.TaskRun.Status.RetriesStatus) < t.PipelineTask.Retries {
tasks = append(tasks, t)
}
}
}
}
}
return tasks
}
// SuccessfulPipelineTaskNames returns a list of the names of all of the PipelineTasks in state
// which have successfully completed.
func (state PipelineRunState) SuccessfulPipelineTaskNames() []string {
done := []string{}
for _, t := range state {
if t.TaskRun != nil {
c := t.TaskRun.Status.GetCondition(apis.ConditionSucceeded)
if c.IsTrue() {
done = append(done, t.PipelineTask.Name)
}
}
}
return done
}
// GetTaskRun is a function that will retrieve the TaskRun name.
type GetTaskRun func(name string) (*v1alpha1.TaskRun, error)
// GetResourcesFromBindings will retrieve all Resources bound in PipelineRun pr and return a map
// from the declared name of the PipelineResource (which is how the PipelineResource will
// be referred to in the PipelineRun) to the PipelineResource, obtained via getResource.
func GetResourcesFromBindings(pr *v1alpha1.PipelineRun, getResource resources.GetResource) (map[string]*v1alpha1.PipelineResource, error) {
rs := map[string]*v1alpha1.PipelineResource{}
for _, resource := range pr.Spec.Resources {
r, err := resources.GetResourceFromBinding(&resource, getResource)
if err != nil {
return rs, xerrors.Errorf("Error following resource reference for %s: %w", resource.Name, err)
}
rs[resource.Name] = r
}
return rs, nil
}
// ValidateResourceBindings validate that the PipelineResources declared in Pipeline p are bound in PipelineRun.
func ValidateResourceBindings(p *v1alpha1.PipelineSpec, pr *v1alpha1.PipelineRun) error {
required := make([]string, 0, len(p.Resources))
for _, resource := range p.Resources {
required = append(required, resource.Name)
}
provided := make([]string, 0, len(pr.Spec.Resources))
for _, resource := range pr.Spec.Resources {
provided = append(provided, resource.Name)
}
if err := list.IsSame(required, provided); err != nil {
return xerrors.Errorf("PipelineRun bound resources didn't match Pipeline: %w", err)
}
return nil
}
// TaskNotFoundError indicates that the resolution failed because a referenced Task couldn't be retrieved
type TaskNotFoundError struct {
Name string
Msg string
}
func (e *TaskNotFoundError) Error() string {
return fmt.Sprintf("Couldn't retrieve Task %q: %s", e.Name, e.Msg)
}
type ConditionNotFoundError struct {
Name string
Msg string
}
func (e *ConditionNotFoundError) Error() string {
return fmt.Sprintf("Couldn't retrieve Condition %q: %s", e.Name, e.Msg)
}
// ResolvePipelineRun retrieves all Tasks instances which are reference by tasks, getting
// instances from getTask. If it is unable to retrieve an instance of a referenced Task, it
// will return an error, otherwise it returns a list of all of the Tasks retrieved.
// It will retrieve the Resources needed for the TaskRun using the mapping of providedResources.
func ResolvePipelineRun(
pipelineRun v1alpha1.PipelineRun,
getTask resources.GetTask,
getTaskRun resources.GetTaskRun,
getClusterTask resources.GetClusterTask,
getCondition GetCondition,
tasks []v1alpha1.PipelineTask,
providedResources map[string]*v1alpha1.PipelineResource,
) (PipelineRunState, error) {
state := []*ResolvedPipelineRunTask{}
for i := range tasks {
pt := tasks[i]
rprt := ResolvedPipelineRunTask{
PipelineTask: &pt,
TaskRunName: getTaskRunName(pipelineRun.Status.TaskRuns, pt.Name, pipelineRun.Name),
}
// Find the Task that this PipelineTask is using
var t v1alpha1.TaskInterface
var err error
if pt.TaskRef.Kind == v1alpha1.ClusterTaskKind {
t, err = getClusterTask(pt.TaskRef.Name)
} else {
t, err = getTask(pt.TaskRef.Name)
}
if err != nil {
return nil, &TaskNotFoundError{
Name: pt.TaskRef.Name,
Msg: err.Error(),
}
}
spec := t.TaskSpec()
rtr, err := ResolvePipelineTaskResources(pt, &spec, t.TaskMetadata().Name, pt.TaskRef.Kind, providedResources)
if err != nil {
return nil, xerrors.Errorf("couldn't match referenced resources with declared resources: %w", err)
}
rprt.ResolvedTaskResources = rtr
taskRun, err := getTaskRun(rprt.TaskRunName)
if err != nil {
if !errors.IsNotFound(err) {
return nil, xerrors.Errorf("error retrieving TaskRun %s: %w", rprt.TaskRunName, err)
}
}
if taskRun != nil {
rprt.TaskRun = taskRun
}
// Get all conditions that this pipelineTask will be using, if any
if len(pt.Conditions) > 0 {
rcc, err := resolveConditionChecks(&pt, pipelineRun.Status.TaskRuns, rprt.TaskRunName, getTaskRun, getCondition, providedResources)
if err != nil {
return nil, err
}
rprt.ResolvedConditionChecks = rcc
}
// Add this task to the state of the PipelineRun
state = append(state, &rprt)
}
return state, nil
}
// getConditionCheckName should return a unique name for a `ConditionCheck` if one has not already been defined, and the existing one otherwise.
func getConditionCheckName(taskRunStatus map[string]*v1alpha1.PipelineRunTaskRunStatus, trName, conditionName string) string {
trStatus, ok := taskRunStatus[trName]
if ok && trStatus.ConditionChecks != nil {
for k, v := range trStatus.ConditionChecks {
// TODO(1022): Should we allow multiple conditions of the same type?
if conditionName == v.ConditionName {
return k
}
}
}
return names.SimpleNameGenerator.RestrictLengthWithRandomSuffix(fmt.Sprintf("%s-%s", trName, conditionName))
}
// getTaskRunName should return a unique name for a `TaskRun` if one has not already been defined, and the existing one otherwise.
func getTaskRunName(taskRunsStatus map[string]*v1alpha1.PipelineRunTaskRunStatus, ptName, prName string) string {
for k, v := range taskRunsStatus {
if v.PipelineTaskName == ptName {
return k
}
}
return names.SimpleNameGenerator.RestrictLengthWithRandomSuffix(fmt.Sprintf("%s-%s", prName, ptName))
}
// GetPipelineConditionStatus will return the Condition that the PipelineRun prName should be
// updated with, based on the status of the TaskRuns in state.
func GetPipelineConditionStatus(pr *v1alpha1.PipelineRun, state PipelineRunState, logger *zap.SugaredLogger, dag *dag.Graph) *apis.Condition {
// We have 4 different states here:
// 1. Timed out -> Failed
// 2. Any one TaskRun has failed - >Failed. This should change with #1020 and #1023
// 3. All tasks are done or are skipped (i.e. condition check failed).-> Success
// 4. A Task or Condition is running right now or there are things left to run -> Running
if pr.IsTimedOut() {
return &apis.Condition{
Type: apis.ConditionSucceeded,
Status: corev1.ConditionFalse,
Reason: ReasonTimedOut,
Message: fmt.Sprintf("PipelineRun %q failed to finish within %q", pr.Name, pr.Spec.Timeout.String()),
}
}
// A single failed task mean we fail the pipeline
for _, rprt := range state {
if rprt.IsFailure() { //IsDone ensures we have crossed the retry limit
logger.Infof("TaskRun %s has failed, so PipelineRun %s has failed, retries done: %b", rprt.TaskRunName, pr.Name, len(rprt.TaskRun.Status.RetriesStatus))
return &apis.Condition{
Type: apis.ConditionSucceeded,
Status: corev1.ConditionFalse,
Reason: ReasonFailed,
Message: fmt.Sprintf("TaskRun %s has failed", rprt.TaskRun.Name),
}
}
}
allTasks := []string{}
successOrSkipTasks := []string{}
// Check to see if all tasks are success or skipped
for _, rprt := range state {
allTasks = append(allTasks, rprt.PipelineTask.Name)
if rprt.IsSuccessful() || isSkipped(rprt, state.toMap(), dag) {
successOrSkipTasks = append(successOrSkipTasks, rprt.PipelineTask.Name)
}
}
if reflect.DeepEqual(allTasks, successOrSkipTasks) {
logger.Infof("All TaskRuns have finished for PipelineRun %s so it has finished", pr.Name)
return &apis.Condition{
Type: apis.ConditionSucceeded,
Status: corev1.ConditionTrue,
Reason: ReasonSucceeded,
Message: "All Tasks have completed executing",
}
}
// Hasn't timed out; no taskrun failed yet; and not all tasks have finished....
// Must keep running then....
return &apis.Condition{
Type: apis.ConditionSucceeded,
Status: corev1.ConditionUnknown,
Reason: ReasonRunning,
Message: "Not all Tasks in the Pipeline have finished executing",
}
}
// isSkipped returns true if a Task in a TaskRun will not be run either because
// its Condition Checks failed or because one of the parent tasks's conditions failed
// Note that this means isSkipped returns false if a conditionCheck is in progress
func isSkipped(rprt *ResolvedPipelineRunTask, stateMap map[string]*ResolvedPipelineRunTask, d *dag.Graph) bool {
// Taskrun not skipped if it already exists
if rprt.TaskRun != nil {
return false
}
// Check if conditionChecks have failed, if so task is skipped
if len(rprt.ResolvedConditionChecks) > 0 {
// isSkipped is only true iof
if rprt.ResolvedConditionChecks.IsDone() && !rprt.ResolvedConditionChecks.IsSuccess() {
return true
}
}
// Recursively look at parent tasks to see if they have been skipped,
// if any of the parents have been skipped, skip as well
node := d.Nodes[rprt.PipelineTask.Name]
for _, p := range node.Prev {
skip := isSkipped(stateMap[p.Task.HashKey()], stateMap, d)
if skip {
return true
}
}
return false
}
func resolveConditionChecks(pt *v1alpha1.PipelineTask, taskRunStatus map[string]*v1alpha1.PipelineRunTaskRunStatus, taskRunName string, getTaskRun resources.GetTaskRun, getCondition GetCondition, providedResources map[string]*v1alpha1.PipelineResource) ([]*ResolvedConditionCheck, error) {
rccs := []*ResolvedConditionCheck{}
for i := range pt.Conditions {
ptc := pt.Conditions[i]
cName := ptc.ConditionRef
c, err := getCondition(cName)
if err != nil {
return nil, &ConditionNotFoundError{
Name: cName,
Msg: err.Error(),
}
}
conditionCheckName := getConditionCheckName(taskRunStatus, taskRunName, cName)
cctr, err := getTaskRun(conditionCheckName)
if err != nil {
if !errors.IsNotFound(err) {
return nil, xerrors.Errorf("error retrieving ConditionCheck %s for taskRun name %s : %w", conditionCheckName, taskRunName, err)
}
}
conditionResources := map[string]*v1alpha1.PipelineResource{}
for _, declared := range ptc.Resources {
r, ok := providedResources[declared.Resource]
if !ok {
return nil, xerrors.Errorf("resources %s missing for condition %s in pipeline task %s", declared.Resource, cName, pt.Name)
}
conditionResources[declared.Name] = r
}
rcc := ResolvedConditionCheck{
Condition: c,
ConditionCheckName: conditionCheckName,
ConditionCheck: v1alpha1.NewConditionCheck(cctr),
PipelineTaskCondition: &ptc,
ResolvedResources: conditionResources,
}
rccs = append(rccs, &rcc)
}
return rccs, nil
}
// ResolvePipelineTaskResources matches PipelineResources referenced by pt inputs and outputs with the
// providedResources and returns an instance of ResolvedTaskResources.
func ResolvePipelineTaskResources(pt v1alpha1.PipelineTask, ts *v1alpha1.TaskSpec, taskName string, kind v1alpha1.TaskKind, providedResources map[string]*v1alpha1.PipelineResource) (*resources.ResolvedTaskResources, error) {
rtr := resources.ResolvedTaskResources{
TaskName: taskName,
TaskSpec: ts,
Kind: kind,
Inputs: map[string]*v1alpha1.PipelineResource{},
Outputs: map[string]*v1alpha1.PipelineResource{},
}
if pt.Resources != nil {
for _, taskInput := range pt.Resources.Inputs {
resource, ok := providedResources[taskInput.Resource]
if !ok {
return nil, xerrors.Errorf("pipelineTask tried to use input resource %s not present in declared resources", taskInput.Resource)
}
rtr.Inputs[taskInput.Name] = resource
}
for _, taskOutput := range pt.Resources.Outputs {
resource, ok := providedResources[taskOutput.Resource]
if !ok {
return nil, xerrors.Errorf("pipelineTask tried to use output resource %s not present in declared resources", taskOutput.Resource)
}
rtr.Outputs[taskOutput.Name] = resource
}
}
return &rtr, nil
}