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
|
// Copyright 2020 CUE 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 flow
// This file contains logic for running tasks.
//
// This implementation anticipates that workflows can also be used for defining
// servers, not just batch scripts. In the future, tasks may be long running and
// provide streams of results.
//
// The implementation starts a goroutine for each user-defined task, instead of
// having a fixed pool of workers. The main reason for this is that tasks are
// inherently heterogeneous and may be blocking on top of that. Also, in the
// future tasks may be long running, as discussed above.
import (
"fmt"
"os"
"cuelang.org/go/cue/errors"
"cuelang.org/go/internal/core/adt"
"cuelang.org/go/internal/core/eval"
"cuelang.org/go/internal/value"
)
func (c *Controller) runLoop() {
_, root := value.ToInternal(c.inst)
// Copy the initial conjuncts.
var rootConjuncts []adt.Conjunct
root.VisitLeafConjuncts(func(c adt.Conjunct) bool {
rootConjuncts = append(rootConjuncts, c)
return true
})
n := len(rootConjuncts)
c.conjuncts = make([]adt.Conjunct, n, n+len(c.tasks))
copy(c.conjuncts, rootConjuncts)
c.markReady(nil)
for c.errs == nil {
// Dispatch all unblocked tasks to workers. Only update
// the configuration when all have been dispatched.
waiting := false
running := false
// Mark tasks as Ready.
for _, t := range c.tasks {
switch t.state {
case Waiting:
waiting = true
case Ready:
running = true
t.state = Running
c.updateTaskValue(t)
t.ctxt = eval.NewContext(value.ToInternal(t.v))
go func(t *Task) {
if err := t.r.Run(t, nil); err != nil {
t.err = errors.Promote(err, "task failed")
}
t.c.taskCh <- t
}(t)
case Running:
running = true
case Terminated:
}
}
if !running {
if waiting {
// Should not happen ever, as cycle detection should have caught
// this. But keep this around as a defensive measure.
c.addErr(errors.New("deadlock"), "run loop")
}
break
}
select {
case <-c.context.Done():
return
case t := <-c.taskCh:
t.state = Terminated
taskStats := *t.ctxt.Stats()
t.stats.Add(taskStats)
c.taskStats.Add(taskStats)
start := *c.opCtx.Stats()
switch t.err {
case nil:
c.updateTaskResults(t)
case ErrAbort:
// TODO: do something cleverer.
fallthrough
default:
c.addErr(t.err, "task failure")
return
}
// Recompute the configuration, if necessary.
if c.updateValue() {
// initTasks was already called in New to catch initialization
// errors earlier and add stats.
c.initTasks(false)
}
c.updateTaskValue(t)
t.stats.Add(c.opCtx.Stats().Since(start))
c.markReady(t)
}
}
}
func (c *Controller) markReady(t *Task) {
for _, x := range c.tasks {
if x.state == Waiting && x.isReady() {
x.state = Ready
}
}
if debug {
fmt.Fprintln(os.Stderr, "tools/flow task dependency graph:")
fmt.Fprintln(os.Stderr, "```mermaid")
fmt.Fprint(os.Stderr, mermaidGraph(c))
fmt.Fprintln(os.Stderr, "```")
}
if c.cfg.UpdateFunc != nil {
if err := c.cfg.UpdateFunc(c, t); err != nil {
c.addErr(err, "task completed")
c.cancel()
return
}
}
}
// updateValue recomputes the workflow configuration if it is out of date. It
// reports whether the values were updated.
func (c *Controller) updateValue() bool {
if c.valueSeqNum == c.conjunctSeq {
return false
}
// TODO: incrementally update results. Currently, the entire tree is
// recomputed on every update. This should not be necessary with the right
// notification structure in place.
v := &adt.Vertex{Conjuncts: c.conjuncts}
v.Finalize(c.opCtx)
c.inst = value.Make(c.opCtx, v)
c.valueSeqNum = c.conjunctSeq
return true
}
// updateTaskValue updates the value of the task in the configuration if it is
// out of date.
func (c *Controller) updateTaskValue(t *Task) {
required := t.conjunctSeq
for _, dep := range t.depTasks {
if dep.conjunctSeq > required {
required = dep.conjunctSeq
}
}
if t.valueSeq == required {
return
}
if c.valueSeqNum < required {
c.updateValue()
}
t.v = c.inst.LookupPath(t.path)
t.valueSeq = required
}
// updateTaskResults updates the result status of the task and adds any result
// values to the overall configuration.
func (c *Controller) updateTaskResults(t *Task) bool {
if t.update == nil {
return false
}
expr := t.update
for i := len(t.labels) - 1; i >= 0; i-- {
label := t.labels[i]
switch label.Typ() {
case adt.StringLabel, adt.HiddenLabel:
expr = &adt.StructLit{
Decls: []adt.Decl{
&adt.Field{
Label: t.labels[i],
Value: expr,
},
},
}
case adt.IntLabel:
i := label.Index()
list := &adt.ListLit{}
any := &adt.Top{}
// TODO(perf): make this a constant thing. This will be possible with the query extension.
for range i {
list.Elems = append(list.Elems, any)
}
list.Elems = append(list.Elems, expr, &adt.Ellipsis{})
expr = list
default:
panic(fmt.Errorf("unexpected label type %v", label.Typ()))
}
}
t.update = nil
// TODO: replace rather than add conjunct if this task already added a
// conjunct before. This will allow for serving applications.
c.conjuncts = append(c.conjuncts, adt.MakeRootConjunct(c.env, expr))
c.conjunctSeq++
t.conjunctSeq = c.conjunctSeq
return true
}
|