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 53
/
outputs.go
330 lines (268 loc) · 9.48 KB
/
outputs.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
package array
import (
"context"
"fmt"
"github.com/lyft/flytestdlib/logger"
arrayCore "github.com/lyft/flyteplugins/go/tasks/plugins/array/core"
"github.com/lyft/flyteplugins/go/tasks/pluginmachinery/workqueue"
"github.com/lyft/flytestdlib/bitarray"
"github.com/lyft/flytestdlib/promutils"
"github.com/lyft/flytestdlib/storage"
"github.com/lyft/flyteplugins/go/tasks/pluginmachinery/io"
"github.com/lyft/flyteplugins/go/tasks/plugins/array/errorcollector"
"github.com/lyft/flyteplugins/go/tasks/pluginmachinery/ioutils"
"github.com/lyft/flyteidl/gen/pb-go/flyteidl/core"
pluginCore "github.com/lyft/flyteplugins/go/tasks/pluginmachinery/core"
)
var (
nilLiteral = &core.Literal{
Value: &core.Literal_Scalar{
Scalar: &core.Scalar{
Value: &core.Scalar_NoneType{
NoneType: &core.Void{},
},
},
},
}
)
// Represents an indexed work queue that aggregates outputs of sub tasks.
type OutputAssembler struct {
workqueue.IndexedWorkQueue
}
func (o OutputAssembler) Queue(ctx context.Context, id workqueue.WorkItemID, item *outputAssembleItem) error {
return o.IndexedWorkQueue.Queue(ctx, id, item)
}
type outputAssembleItem struct {
outputPaths io.OutputFilePaths
varNames []string
finalPhases bitarray.CompactArray
dataStore *storage.DataStore
}
type assembleOutputsWorker struct {
}
func (w assembleOutputsWorker) Process(ctx context.Context, workItem workqueue.WorkItem) (workqueue.WorkStatus, error) {
i := workItem.(*outputAssembleItem)
outputReaders, err := ConstructOutputReaders(ctx, i.dataStore, i.outputPaths.GetOutputPrefixPath(), i.outputPaths.GetRawOutputPrefix(), int(i.finalPhases.ItemsCount))
if err != nil {
logger.Warnf(ctx, "Failed to construct output readers. Error: %v", err)
return workqueue.WorkStatusFailed, err
}
finalOutputs := &core.LiteralMap{
Literals: map[string]*core.Literal{},
}
for idx, subTaskPhaseIdx := range i.finalPhases.GetItems() {
existingPhase := pluginCore.Phases[subTaskPhaseIdx]
if existingPhase.IsSuccess() {
output, executionError, err := outputReaders[idx].Read(ctx)
if err != nil {
logger.Warnf(ctx, "Failed to read output for subtask [%v]. Error: %v", idx, err)
return workqueue.WorkStatusFailed, err
}
if executionError == nil && output != nil {
appendSubTaskOutput(finalOutputs, output, int64(i.finalPhases.ItemsCount))
continue
}
}
// TODO: Do we need the names of the outputs in the literalMap here?
appendEmptyOutputs(finalOutputs, i.varNames)
}
ow := ioutils.NewRemoteFileOutputWriter(ctx, i.dataStore, i.outputPaths)
if err = ow.Put(ctx, ioutils.NewInMemoryOutputReader(finalOutputs, nil)); err != nil {
return workqueue.WorkStatusNotDone, err
}
return workqueue.WorkStatusSucceeded, nil
}
func appendOneItem(outputs *core.LiteralMap, varName string, literal *core.Literal, expectedSize int64) {
existingVal, found := outputs.Literals[varName]
var list *core.LiteralCollection
if found {
list = existingVal.GetCollection()
} else {
list = &core.LiteralCollection{
Literals: make([]*core.Literal, 0, expectedSize),
}
existingVal = &core.Literal{
Value: &core.Literal_Collection{
Collection: list,
},
}
}
list.Literals = append(list.Literals, literal)
outputs.Literals[varName] = existingVal
}
func appendSubTaskOutput(outputs *core.LiteralMap, subTaskOutput *core.LiteralMap,
expectedSize int64) {
for key, val := range subTaskOutput.GetLiterals() {
appendOneItem(outputs, key, val, expectedSize)
}
}
func appendEmptyOutputs(outputs *core.LiteralMap, vars []string) {
for _, varName := range vars {
appendOneItem(outputs, varName, nilLiteral, 1)
}
}
func buildFinalPhases(executedTasks bitarray.CompactArray, indexes *bitarray.BitSet, totalSize uint) bitarray.CompactArray {
res := arrayCore.NewPhasesCompactArray(totalSize)
// Copy phases of executed sub-tasks
for i, phaseIdx := range executedTasks.GetItems() {
res.SetItem(arrayCore.CalculateOriginalIndex(i, indexes), phaseIdx)
}
// Set phases os already discovered tasks to success
for i := uint(0); i < totalSize; i++ {
if !indexes.IsSet(i) {
res.SetItem(int(i), bitarray.Item(pluginCore.PhaseSuccess))
}
}
return res
}
// Assembles a single outputs.pb that contain all the outputs of the subtasks and write them to the final OutputWriter.
// This step can potentially be expensive (hence the metrics) and why it's offloaded to a background process.
func AssembleFinalOutputs(ctx context.Context, assemblyQueue OutputAssembler, tCtx pluginCore.TaskExecutionContext,
terminalPhase arrayCore.Phase, state *arrayCore.State) (*arrayCore.State, error) {
// Otherwise, run the data catalog steps - create and submit work items to the catalog processor,
// build input readers
workItemID := tCtx.TaskExecutionMetadata().GetTaskExecutionID().GetGeneratedName()
w, found, err := assemblyQueue.Get(workItemID)
if err != nil {
return nil, err
}
// If the work item is not found in the queue, it's either never queued, was evicted, or we are recovering from a
// reboot. Add it again.
if !found {
taskTemplate, err := tCtx.TaskReader().Read(ctx)
if err != nil {
return nil, err
}
outputVariables := taskTemplate.GetInterface().GetOutputs()
if outputVariables == nil || outputVariables.GetVariables() == nil {
// If the task has no outputs, bail early.
state = state.SetPhase(terminalPhase, 0).SetReason("Task has no outputs")
return state, nil
}
logger.Debugf(ctx, "Building final phases for original array of size [%v] and execution size [%v]",
state.GetOriginalArraySize(), state.GetArrayStatus().Detailed.ItemsCount)
varNames := make([]string, 0, len(outputVariables.GetVariables()))
for varName := range outputVariables.GetVariables() {
varNames = append(varNames, varName)
}
finalPhases := buildFinalPhases(state.GetArrayStatus().Detailed,
state.GetIndexesToCache(), uint(state.GetOriginalArraySize()))
err = assemblyQueue.Queue(ctx, workItemID, &outputAssembleItem{
varNames: varNames,
finalPhases: finalPhases,
outputPaths: tCtx.OutputWriter(),
dataStore: tCtx.DataStore(),
})
if err != nil {
return nil, err
}
w, found, err = assemblyQueue.Get(workItemID)
if err != nil {
return nil, err
}
if !found {
return nil, fmt.Errorf("couldn't find work item [%v] after immediately adding it", workItemID)
}
}
switch w.Status() {
case workqueue.WorkStatusSucceeded:
or := ioutils.NewRemoteFileOutputReader(ctx, tCtx.DataStore(), tCtx.OutputWriter(), tCtx.MaxDatasetSizeBytes())
if err = tCtx.OutputWriter().Put(ctx, or); err != nil {
return nil, err
}
outputExists, err := or.Exists(ctx)
if err != nil {
return nil, err
}
if outputExists {
state = state.SetPhase(terminalPhase, 0).SetReason("Assembled outputs")
return state, nil
}
isErr, err := or.IsError(ctx)
if err != nil {
return nil, err
}
if isErr {
ee, err := or.ReadError(ctx)
if err != nil {
return nil, err
}
state = state.SetPhase(terminalPhase, 0).
SetReason("Assembled error").
SetExecutionErr(ee.ExecutionError)
} else {
state = state.SetPhase(terminalPhase, 0).SetReason("No output or error assembled.")
}
case workqueue.WorkStatusFailed:
state = state.SetExecutionErr(&core.ExecutionError{
Message: w.Error().Error(),
})
state = state.SetPhase(arrayCore.PhaseRetryableFailure, 0).SetReason("Failed to assemble outputs/errors.")
}
return state, nil
}
type assembleErrorsWorker struct {
maxErrorMessageLength int
}
func (a assembleErrorsWorker) Process(ctx context.Context, workItem workqueue.WorkItem) (workqueue.WorkStatus, error) {
w := workItem.(*outputAssembleItem)
outputReaders, err := ConstructOutputReaders(ctx, w.dataStore, w.outputPaths.GetOutputPrefixPath(), w.outputPaths.GetRawOutputPrefix(), int(w.finalPhases.ItemsCount))
if err != nil {
return workqueue.WorkStatusNotDone, err
}
ec := errorcollector.NewErrorMessageCollector()
for idx, subTaskPhaseIdx := range w.finalPhases.GetItems() {
existingPhase := pluginCore.Phases[subTaskPhaseIdx]
if existingPhase.IsFailure() {
isError, err := outputReaders[idx].IsError(ctx)
if err != nil {
return workqueue.WorkStatusNotDone, err
}
if isError {
executionError, err := outputReaders[idx].ReadError(ctx)
if err != nil {
return workqueue.WorkStatusNotDone, err
}
ec.Collect(idx, executionError.String())
} else {
ec.Collect(idx, "Job Failed.")
}
}
}
msg := ""
if ec.Length() > 0 {
msg = ec.Summary(a.maxErrorMessageLength)
}
ow := ioutils.NewRemoteFileOutputWriter(ctx, w.dataStore, w.outputPaths)
if err = ow.Put(ctx, ioutils.NewInMemoryOutputReader(nil, &io.ExecutionError{
ExecutionError: &core.ExecutionError{
Code: "",
Message: msg,
ErrorUri: "",
},
IsRecoverable: false,
})); err != nil {
return workqueue.WorkStatusNotDone, err
}
return workqueue.WorkStatusSucceeded, nil
}
func NewOutputAssembler(workQueueConfig workqueue.Config, scope promutils.Scope) (OutputAssembler, error) {
q, err := workqueue.NewIndexedWorkQueue("output", assembleOutputsWorker{}, workQueueConfig, scope)
if err != nil {
return OutputAssembler{}, err
}
return OutputAssembler{
IndexedWorkQueue: q,
}, nil
}
func NewErrorAssembler(maxErrorMessageLength int, workQueueConfig workqueue.Config, scope promutils.Scope) (OutputAssembler, error) {
q, err := workqueue.NewIndexedWorkQueue("error", assembleErrorsWorker{
maxErrorMessageLength: maxErrorMessageLength,
}, workQueueConfig, scope)
if err != nil {
return OutputAssembler{}, err
}
return OutputAssembler{
IndexedWorkQueue: q,
}, nil
}