-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
scheduler.go
298 lines (246 loc) · 7.68 KB
/
scheduler.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
package pipeline
import (
"context"
"sort"
"time"
"github.com/jpillora/backoff"
"github.com/pkg/errors"
"gopkg.in/guregu/null.v4"
"github.com/smartcontractkit/chainlink/v2/core/logger"
)
func (s *scheduler) newMemoryTaskRun(task Task, vars Vars) *memoryTaskRun {
run := &memoryTaskRun{task: task, vars: vars}
propagatableInputs := 0
for _, i := range task.Inputs() {
if i.PropagateResult {
propagatableInputs++
}
}
// fill in the inputs, fast path for no inputs
if propagatableInputs != 0 {
// construct a list of inputs, sorted by OutputIndex
type input struct {
index int32
result Result
}
inputs := make([]input, 0, propagatableInputs)
// NOTE: we could just allocate via make, then assign directly to run.inputs[i.OutputIndex()]
// if we're confident that indices are within range
for _, i := range task.Inputs() {
if i.PropagateResult {
inputs = append(inputs, input{index: i.InputTask.OutputIndex(), result: s.results[i.InputTask.ID()].Result})
}
}
sort.Slice(inputs, func(i, j int) bool {
return inputs[i].index < inputs[j].index
})
run.inputs = make([]Result, len(inputs))
for i, input := range inputs {
run.inputs[i] = input.result
}
}
return run
}
type scheduler struct {
pipeline *Pipeline
run *Run
dependencies map[int]uint
waiting uint
results map[int]TaskRunResult
vars Vars
logger logger.Logger
pending bool
exiting bool
taskCh chan *memoryTaskRun
resultCh chan TaskRunResult
}
func newScheduler(p *Pipeline, run *Run, vars Vars, lggr logger.Logger) *scheduler {
lggr = lggr.Named("Scheduler")
dependencies := make(map[int]uint, len(p.Tasks))
for id, task := range p.Tasks {
dependencies[id] = uint(len(task.Inputs()))
}
s := &scheduler{
pipeline: p,
run: run,
dependencies: dependencies,
results: make(map[int]TaskRunResult, len(p.Tasks)),
vars: vars,
logger: lggr,
// taskCh should never block
taskCh: make(chan *memoryTaskRun, len(dependencies)),
resultCh: make(chan TaskRunResult),
}
// if there's results already present on Run, then this is a resumption. Loop over them and fill results table
s.reconstructResults()
// immediately schedule all doable tasks
for id, task := range p.Tasks {
// skip tasks that are not ready
if s.dependencies[id] != 0 {
continue
}
// skip finished tasks
if _, exists := s.results[id]; exists {
continue
}
run := s.newMemoryTaskRun(task, s.vars.Copy())
lggr.Tracew("scheduling task run", "dot_id", task.DotID(), "attempts", run.attempts)
s.taskCh <- run
s.waiting++
}
return s
}
func (s *scheduler) reconstructResults() {
// if there's results already present on Run, then this is a resumption. Loop over them and fill results table
for _, r := range s.run.PipelineTaskRuns {
task := s.pipeline.ByDotID(r.DotID)
if task == nil {
panic("can't find task by dot id")
}
if r.IsPending() {
continue
}
result := Result{}
if r.Error.Valid {
result.Error = errors.New(r.Error.String)
}
if r.Output.Valid {
result.Value = r.Output.Val
}
s.results[task.ID()] = TaskRunResult{
Task: task,
Result: result,
CreatedAt: r.CreatedAt,
FinishedAt: r.FinishedAt,
}
// store the result in vars
var err error
if result.Error != nil {
err = s.vars.Set(task.DotID(), result.Error)
} else {
err = s.vars.Set(task.DotID(), result.Value)
}
if err != nil {
s.logger.Panicf("Vars.Set error: %v", err)
}
// mark all outputs as complete
for _, output := range task.Outputs() {
id := output.ID()
s.dependencies[id]--
}
}
}
func (s *scheduler) Run() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for s.waiting > 0 {
// we don't "for result in resultCh" because it would stall if the
// pipeline is completely empty
result := <-s.resultCh
// TODO: if for some reason the cleanup didn't succeed and we're stuck waiting for reports forever
// we should be able to timeout and finish shutting down
// See: https://app.shortcut.com/chainlinklabs/story/21225/straighten-out-and-clarify-context-usage-in-the-pipeline
s.waiting--
// retrieve previous attempt count
result.Attempts = s.results[result.Task.ID()].Attempts
// only count as an attempt if the job actually ran. If we're exiting then it got cancelled
if !s.exiting {
result.Attempts++
}
// store task run
s.results[result.Task.ID()] = result
// catch the pending state, we will keep the pipeline running until no more progress is made
if result.runInfo.IsPending {
s.pending = true
// skip output wrangling because this task isn't actually complete yet
continue
}
// store the result in vars
var err error
if result.Result.Error != nil {
err = s.vars.Set(result.Task.DotID(), result.Result.Error)
} else {
err = s.vars.Set(result.Task.DotID(), result.Result.Value)
}
if err != nil {
s.logger.Panicf("Vars.Set error: %v", err)
}
// if the task was marked as failEarly, and the result is a fail
if result.Result.Error != nil && result.Task.Base().FailEarly {
// drain remaining jobs (continue the loop until waiting = 0) then exit
s.exiting = true
cancel() // cleanup: terminate pending retries
// mark remaining jobs as cancelled
s.markRemaining(ErrCancelled)
}
if s.exiting {
// skip scheduling dependencies if we're exiting early
continue
}
// if task hasn't reached it's max retry count yet, we schedule it again
if result.Attempts < uint(result.Task.TaskRetries()) && result.Result.Error != nil {
// we immediately increase the in-flight counter so the pipeline doesn't terminate
// while we wait for the next retry
s.waiting++
backoff := backoff.Backoff{
Factor: 2,
Min: result.Task.TaskMinBackoff(),
Max: result.Task.TaskMaxBackoff(),
}
go func(vars Vars) {
select {
case <-ctx.Done():
// report back so the waiting counter gets decreased
now := time.Now()
s.report(context.Background(), TaskRunResult{
Task: result.Task,
Result: Result{Error: ErrCancelled},
CreatedAt: now, // TODO: more accurate start time
FinishedAt: null.TimeFrom(now),
})
case <-time.After(backoff.ForAttempt(float64(result.Attempts - 1))): // we subtract 1 because backoff 0-indexes
// schedule a new attempt
run := s.newMemoryTaskRun(result.Task, vars)
run.attempts = result.Attempts
s.logger.Tracew("scheduling task run", "dot_id", run.task.DotID(), "attempts", run.attempts)
s.taskCh <- run
}
}(s.vars.Copy()) // must Copy() from current goroutine
// skip scheduling dependencies since it's the task is not complete yet
continue
}
for _, output := range result.Task.Outputs() {
id := output.ID()
s.dependencies[id]--
// if all dependencies are done, schedule task run
if s.dependencies[id] == 0 {
task := s.pipeline.Tasks[id]
run := s.newMemoryTaskRun(task, s.vars.Copy())
s.logger.Tracew("scheduling task run", "dot_id", run.task.DotID(), "attempts", run.attempts)
s.taskCh <- run
s.waiting++
}
}
}
close(s.taskCh)
}
func (s *scheduler) markRemaining(err error) {
now := time.Now()
for _, task := range s.pipeline.Tasks {
if _, ok := s.results[task.ID()]; !ok {
s.results[task.ID()] = TaskRunResult{
Task: task,
Result: Result{Error: err},
CreatedAt: now, // TODO: more accurate start time
FinishedAt: null.TimeFrom(now),
}
}
}
}
func (s *scheduler) report(ctx context.Context, result TaskRunResult) {
select {
case s.resultCh <- result:
case <-ctx.Done():
s.logger.Errorw("pipeline.scheduler: discarding result; report context timed out", "result", result, "err", ctx.Err())
}
}