This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 59
/
workflow_compiler.go
executable file
·330 lines (276 loc) · 11.4 KB
/
workflow_compiler.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
// This package provides compiler services for flyte workflows. It performs static analysis on the Workflow and produces
// CompilerErrors for any detected issue. A flyte workflow should only be considered valid for execution if it passed through
// the compiler first. The intended usage for the compiler is as follows:
// 1) Call GetRequirements(...) and load/retrieve all tasks/workflows referenced in the response.
// 2) Call CompileWorkflow(...) and make sure it reports no errors.
// 3) Use one of the transformer packages (e.g. transformer/k8s) to build the final executable workflow.
//
// +-------------------+
// | start(StartNode) |
// +-------------------+
// |
// | wf_input
// v
// +--------+ +-------------------+
// | static | --> | node_1(TaskNode) |
// +--------+ +-------------------+
// | |
// | | x
// | v
// | +-------------------+
// +----------> | node_2(TaskNode) |
// +-------------------+
// |
// | n2_output
// v
// +-------------------+
// | end(EndNode) |
// +-------------------+
// +-------------------+
// | Workflow Id: repo |
// +-------------------+
package compiler
import (
"strings"
"github.com/golang/protobuf/proto"
"github.com/lyft/flyteidl/gen/pb-go/flyteidl/core"
c "github.com/lyft/flytepropeller/pkg/compiler/common"
"github.com/lyft/flytepropeller/pkg/compiler/errors"
v "github.com/lyft/flytepropeller/pkg/compiler/validators"
"k8s.io/apimachinery/pkg/util/sets"
)
// Updates workflows and tasks references to reflect the needed ones for this workflow (ignoring subworkflows)
func (w *workflowBuilder) updateRequiredReferences() {
reqs := getRequirements(w.CoreWorkflow.Template, w.allSubWorkflows, false, errors.NewCompileErrors())
workflows := map[c.WorkflowIDKey]c.InterfaceProvider{}
tasks := c.TaskIndex{}
for _, workflowID := range reqs.launchPlanIds {
if wf, ok := w.allLaunchPlans[workflowID.String()]; ok {
workflows[workflowID.String()] = wf
}
}
for _, taskID := range reqs.taskIds {
if task, ok := w.allTasks[taskID.String()]; ok {
tasks[taskID.String()] = task
}
}
w.Tasks = tasks
w.LaunchPlans = workflows
}
// Validates the coreWorkflow contains no cycles and that all nodes are reachable.
func (w workflowBuilder) validateReachable(errs errors.CompileErrors) (ok bool) {
neighbors := func(nodeId string) sets.String {
downNodes := w.downstreamNodes[nodeId]
if downNodes == nil {
return sets.String{}
}
return downNodes
}
// TODO: If a branch node can exist in a cycle and not actually be a cycle since it can branch off...
if cycle, visited, detected := detectCycle(c.StartNodeID, neighbors); detected {
errs.Collect(errors.NewCycleDetectedInWorkflowErr(c.StartNodeID, strings.Join(cycle, ">")))
} else {
// If no cycles are detected, we expect all nodes to have been visited. Otherwise there are unreachable
// node(s)..
if visited.Len() != len(w.Nodes) {
// report unreachable nodes
allNodes := toNodeIdsSet(w.Nodes)
unreachableNodes := allNodes.Difference(visited).Difference(sets.NewString(c.EndNodeID))
if len(unreachableNodes) > 0 {
errs.Collect(errors.NewUnreachableNodesErr(c.StartNodeID, strings.Join(toSlice(unreachableNodes), ",")))
}
}
}
return !errs.HasErrors()
}
// Adds unique nodes to the workflow.
func (w workflowBuilder) AddNode(n c.NodeBuilder, errs errors.CompileErrors) (node c.NodeBuilder, ok bool) {
if _, ok := w.Nodes[n.GetId()]; ok {
errs.Collect(errors.NewDuplicateIDFoundErr(n.GetId()))
}
node = n
w.Nodes[n.GetId()] = node
ok = !errs.HasErrors()
w.CoreWorkflow.Template.Nodes = append(w.CoreWorkflow.Template.Nodes, node.GetCoreNode())
return
}
func (w workflowBuilder) AddExecutionEdge(nodeFrom, nodeTo c.NodeID) {
if nodeFrom == "" {
nodeFrom = c.StartNodeID
}
if _, found := w.downstreamNodes[nodeFrom]; !found {
w.downstreamNodes[nodeFrom] = sets.String{}
w.CoreWorkflow.Connections.Downstream[nodeFrom] = &core.ConnectionSet_IdList{}
}
if _, found := w.upstreamNodes[nodeTo]; !found {
w.upstreamNodes[nodeTo] = sets.String{}
w.CoreWorkflow.Connections.Upstream[nodeTo] = &core.ConnectionSet_IdList{
Ids: make([]string, 1),
}
}
w.downstreamNodes[nodeFrom].Insert(nodeTo)
w.upstreamNodes[nodeTo].Insert(nodeFrom)
w.CoreWorkflow.Connections.Downstream[nodeFrom].Ids = w.downstreamNodes[nodeFrom].List()
w.CoreWorkflow.Connections.Upstream[nodeTo].Ids = w.upstreamNodes[nodeTo].List()
}
func (w workflowBuilder) AddEdges(n c.NodeBuilder, errs errors.CompileErrors) (ok bool) {
if n.GetInterface() == nil {
// If there were errors computing node's interface, don't add any edges and just bail.
return
}
// Add explicitly declared edges
if n.GetUpstreamNodeIds() != nil {
for _, upNode := range n.GetUpstreamNodeIds() {
w.AddExecutionEdge(upNode, n.GetId())
}
}
// Add implicit Edges
return v.ValidateBindings(&w, n, n.GetInputs(), n.GetInterface().GetInputs(), errs.NewScope())
}
// Contains the main validation logic for the coreWorkflow. If successful, it'll build an executable Workflow.
func (w workflowBuilder) ValidateWorkflow(fg *flyteWorkflow, errs errors.CompileErrors) (c.Workflow, bool) {
// Initialize workflow
wf := w.newWorkflowBuilder(fg)
wf.updateRequiredReferences()
// Start building out the workflow
// Create global sentinel nodeBuilder with the workflow as its interface.
startNode := &core.Node{
Id: c.StartNodeID,
}
var ok bool
if wf.CoreWorkflow.Template.Interface, ok = v.ValidateInterface(c.StartNodeID, wf.CoreWorkflow.Template.Interface, errs.NewScope()); !ok {
return nil, !errs.HasErrors()
}
checkpoint := make([]*core.Node, 0, len(fg.Template.Nodes))
checkpoint = append(checkpoint, fg.Template.Nodes...)
fg.Template.Nodes = make([]*core.Node, 0, len(fg.Template.Nodes))
wf.GetCoreWorkflow().Connections = &core.ConnectionSet{
Downstream: make(map[string]*core.ConnectionSet_IdList),
Upstream: make(map[string]*core.ConnectionSet_IdList),
}
globalInputNode, _ := wf.AddNode(wf.NewNodeBuilder(startNode), errs)
globalInputNode.SetInterface(&core.TypedInterface{Outputs: wf.CoreWorkflow.Template.Interface.Inputs})
endNode := &core.Node{Id: c.EndNodeID}
globalOutputNode, _ := wf.AddNode(wf.NewNodeBuilder(endNode), errs)
globalOutputNode.SetInterface(&core.TypedInterface{Inputs: wf.CoreWorkflow.Template.Interface.Outputs})
globalOutputNode.SetInputs(wf.CoreWorkflow.Template.Outputs)
// Add and validate all other nodes
for _, n := range checkpoint {
if node, addOk := wf.AddNode(wf.NewNodeBuilder(n), errs.NewScope()); addOk {
v.ValidateNode(&wf, node, errs.NewScope())
}
}
// Add explicitly and implicitly declared edges
for nodeID, n := range wf.Nodes {
if nodeID == c.StartNodeID {
continue
}
wf.AddEdges(n, errs.NewScope())
}
// Add execution edges for orphan nodes that don't have any inward/outward edges.
for nodeID := range wf.Nodes {
if nodeID == c.StartNodeID || nodeID == c.EndNodeID {
continue
}
if _, foundUpStream := wf.upstreamNodes[nodeID]; !foundUpStream {
wf.AddExecutionEdge(c.StartNodeID, nodeID)
}
if _, foundDownStream := wf.downstreamNodes[nodeID]; !foundDownStream {
wf.AddExecutionEdge(nodeID, c.EndNodeID)
}
}
// Validate workflow outputs are bound
if _, wfIfaceOk := v.ValidateInterface(globalOutputNode.GetId(), globalOutputNode.GetInterface(), errs.NewScope()); wfIfaceOk {
v.ValidateBindings(&wf, globalOutputNode, globalOutputNode.GetInputs(),
globalOutputNode.GetInterface().GetInputs(), errs.NewScope())
}
// Validate no cycles are detected.
wf.validateReachable(errs.NewScope())
return wf, !errs.HasErrors()
}
// Validates that all requirements for the coreWorkflow and its subworkflows are present.
func (w workflowBuilder) validateAllRequirements(errs errors.CompileErrors) bool {
reqs := getRequirements(w.CoreWorkflow.Template, w.allSubWorkflows, true, errs)
for _, lp := range reqs.launchPlanIds {
if _, ok := w.allLaunchPlans[lp.String()]; !ok {
errs.Collect(errors.NewWorkflowReferenceNotFoundErr(c.StartNodeID, lp.String()))
}
}
for _, taskID := range reqs.taskIds {
if _, ok := w.allTasks[taskID.String()]; !ok {
errs.Collect(errors.NewTaskReferenceNotFoundErr(c.StartNodeID, taskID.String()))
}
}
return !errs.HasErrors()
}
// Compiles a flyte workflow a and all of its dependencies into a single executable Workflow. Refer to GetRequirements()
// to obtain a list of launchplan and Task ids to load/compile first.
// Returns an executable Workflow (if no errors are found) or a list of errors that must be addressed before the Workflow
// can be executed. Cast the error to errors.CompileErrors to inspect individual errors.
func CompileWorkflow(primaryWf *core.WorkflowTemplate, subworkflows []*core.WorkflowTemplate, tasks []*core.CompiledTask,
launchPlans []c.InterfaceProvider) (*core.CompiledWorkflowClosure, error) {
errs := errors.NewCompileErrors()
if primaryWf == nil {
errs.Collect(errors.NewValueRequiredErr("root", "wf"))
return nil, errs
}
wf := proto.Clone(primaryWf).(*core.WorkflowTemplate)
if tasks == nil {
errs.Collect(errors.NewValueRequiredErr("root", "tasks"))
return nil, errs
}
// Validate all tasks are valid... invalid tasks won't be passed on to the workflow validator
uniqueTasks := sets.NewString()
taskBuilders := make([]c.Task, 0, len(tasks))
for _, task := range tasks {
if task.Template == nil || task.Template.Id == nil {
errs.Collect(errors.NewValueRequiredErr("task", "Template.Id"))
return nil, errs
}
if uniqueTasks.Has(task.Template.Id.String()) {
continue
}
taskBuilders = append(taskBuilders, &taskBuilder{flyteTask: task.Template})
uniqueTasks.Insert(task.Template.Id.String())
}
// Validate overall requirements of the coreWorkflow.
wfIndex, ok := c.NewWorkflowIndex(toCompiledWorkflows(subworkflows...), errs.NewScope())
if !ok {
return nil, errs
}
compiledWf := &core.CompiledWorkflow{Template: wf}
gb := newWorfklowBuilder(compiledWf, wfIndex, c.NewTaskIndex(taskBuilders...), toInterfaceProviderMap(launchPlans))
// Terminate early if there are some required component not present.
if !gb.validateAllRequirements(errs.NewScope()) {
return nil, errs
}
validatedWf, ok := gb.ValidateWorkflow(compiledWf, errs.NewScope())
if ok {
compiledTasks := make([]*core.CompiledTask, 0, len(taskBuilders))
for _, t := range taskBuilders {
compiledTasks = append(compiledTasks, &core.CompiledTask{Template: t.GetCoreTask()})
}
return &core.CompiledWorkflowClosure{
Primary: validatedWf.GetCoreWorkflow(),
Tasks: compiledTasks,
}, nil
}
return nil, errs
}
func (w workflowBuilder) newWorkflowBuilder(fg *flyteWorkflow) workflowBuilder {
return newWorfklowBuilder(fg, w.allSubWorkflows, w.allTasks, w.allLaunchPlans)
}
func newWorfklowBuilder(fg *flyteWorkflow, wfIndex c.WorkflowIndex, tasks c.TaskIndex,
workflows map[string]c.InterfaceProvider) workflowBuilder {
return workflowBuilder{
CoreWorkflow: fg,
LaunchPlans: map[string]c.InterfaceProvider{},
Nodes: c.NewNodeIndex(),
Tasks: c.NewTaskIndex(),
downstreamNodes: c.StringAdjacencyList{},
upstreamNodes: c.StringAdjacencyList{},
allSubWorkflows: wfIndex,
allLaunchPlans: workflows,
allTasks: tasks,
}
}