-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
dag.go
252 lines (222 loc) · 6.43 KB
/
dag.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
/*
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 dag
import (
"errors"
"fmt"
"sort"
"strings"
"github.com/tektoncd/pipeline/pkg/list"
"k8s.io/apimachinery/pkg/util/sets"
)
// Task is an interface for all types that could be in a DAG
type Task interface {
HashKey() string
Deps() []string
}
// Tasks is an interface for lists of types that could be in a DAG
type Tasks interface {
Items() []Task
}
// Node represents a Task in a pipeline.
type Node struct {
// Key represent a unique name of the node in a graph
Key string
// Prev represent all the Previous task Nodes for the current Task
Prev []*Node
// Next represent all the Next task Nodes for the current Task
Next []*Node
}
// Graph represents the Pipeline Graph
type Graph struct {
// Nodes represent map of PipelineTask name to Node in Pipeline Graph
Nodes map[string]*Node
}
// Returns an empty Pipeline Graph
func newGraph() *Graph {
return &Graph{Nodes: map[string]*Node{}}
}
func (g *Graph) addPipelineTask(t Task) (*Node, error) {
if _, ok := g.Nodes[t.HashKey()]; ok {
return nil, errors.New("duplicate pipeline task")
}
newNode := &Node{
Key: t.HashKey(),
}
g.Nodes[t.HashKey()] = newNode
return newNode, nil
}
// Build returns a valid pipeline Graph. Returns error if the pipeline is invalid
func Build(tasks Tasks, deps map[string][]string) (*Graph, error) {
d := newGraph()
// Add all Tasks mentioned in the `PipelineSpec`
for _, pt := range tasks.Items() {
if _, err := d.addPipelineTask(pt); err != nil {
return nil, fmt.Errorf("task %s is already present in Graph, can't add it again: %w", pt.HashKey(), err)
}
}
// Ensure no cycles in the graph
if err := findCyclesInDependencies(deps); err != nil {
return nil, fmt.Errorf("cycle detected; %w", err)
}
// Process all from and runAfter constraints to add task dependency
for pt, taskDeps := range deps {
for _, previousTask := range taskDeps {
if err := addLink(pt, previousTask, d.Nodes); err != nil {
return nil, fmt.Errorf("couldn't add link between %s and %s: %w", pt, previousTask, err)
}
}
}
return d, nil
}
// GetCandidateTasks returns a set of names of PipelineTasks whose ancestors are all completed,
// given a list of finished doneTasks. If the specified
// doneTasks are invalid (i.e. if it is indicated that a Task is done, but the
// previous Tasks are not done), an error is returned.
func GetCandidateTasks(g *Graph, doneTasks ...string) (sets.String, error) {
roots := getRoots(g)
tm := sets.NewString(doneTasks...)
d := sets.NewString()
visited := sets.NewString()
for _, root := range roots {
schedulable := findSchedulable(root, visited, tm)
for _, taskName := range schedulable {
d.Insert(taskName)
}
}
var visitedNames []string
for v := range visited {
visitedNames = append(visitedNames, v)
}
notVisited := list.DiffLeft(doneTasks, visitedNames)
if len(notVisited) > 0 {
return nil, fmt.Errorf("invalid list of done tasks; some tasks were indicated completed without ancestors being done: %v", notVisited)
}
return d, nil
}
func linkPipelineTasks(prev *Node, next *Node) {
next.Prev = append(next.Prev, prev)
prev.Next = append(prev.Next, next)
}
// use Kahn's algorithm to find cycles in dependencies
func findCyclesInDependencies(deps map[string][]string) error {
independentTasks := sets.NewString()
dag := make(map[string]sets.String, len(deps))
childMap := make(map[string]sets.String, len(deps))
for task, taskDeps := range deps {
if len(taskDeps) == 0 {
continue
}
dag[task] = sets.NewString(taskDeps...)
for _, dep := range taskDeps {
if len(deps[dep]) == 0 {
independentTasks.Insert(dep)
}
if children, ok := childMap[dep]; ok {
children.Insert(task)
} else {
childMap[dep] = sets.NewString(task)
}
}
}
for {
parent, ok := independentTasks.PopAny()
if !ok {
break
}
children := childMap[parent]
for {
child, ok := children.PopAny()
if !ok {
break
}
dag[child].Delete(parent)
if dag[child].Len() == 0 {
independentTasks.Insert(child)
delete(dag, child)
}
}
}
return getInterdependencyError(dag)
}
func getInterdependencyError(dag map[string]sets.String) error {
if len(dag) == 0 {
return nil
}
firstChild := ""
for task := range dag {
if firstChild == "" || firstChild > task {
firstChild = task
}
}
deps := dag[firstChild].List()
depNames := make([]string, 0, len(deps))
sort.Strings(deps)
for _, dep := range deps {
depNames = append(depNames, fmt.Sprintf("%q", dep))
}
return fmt.Errorf("task %q depends on %s", firstChild, strings.Join(depNames, ", "))
}
func addLink(pt string, previousTask string, nodes map[string]*Node) error {
prev, ok := nodes[previousTask]
if !ok {
return fmt.Errorf("task %s depends on %s but %s wasn't present in Pipeline", pt, previousTask, previousTask)
}
next := nodes[pt]
linkPipelineTasks(prev, next)
return nil
}
func getRoots(g *Graph) []*Node {
n := []*Node{}
for _, node := range g.Nodes {
if len(node.Prev) == 0 {
n = append(n, node)
}
}
return n
}
func findSchedulable(n *Node, visited sets.String, doneTasks sets.String) []string {
if visited.Has(n.Key) {
return []string{}
}
visited.Insert(n.Key)
if doneTasks.Has(n.Key) {
schedulable := []string{}
// This one is done! Take note of it and look at the next candidate
for _, next := range n.Next {
if _, ok := visited[next.Key]; !ok {
schedulable = append(schedulable, findSchedulable(next, visited, doneTasks)...)
}
}
return schedulable
}
// This one isn't done! Return it if it's schedulable
if isSchedulable(doneTasks, n.Prev) {
// FIXME(vdemeester)
return []string{n.Key}
}
// This one isn't done, but it also isn't ready to schedule
return []string{}
}
func isSchedulable(doneTasks sets.String, prevs []*Node) bool {
if len(prevs) == 0 {
return true
}
collected := []string{}
for _, n := range prevs {
if doneTasks.Has(n.Key) {
collected = append(collected, n.Key)
}
}
return len(collected) == len(prevs)
}