This repository has been archived by the owner on May 18, 2021. It is now read-only.
/
graph.go
488 lines (417 loc) · 13.8 KB
/
graph.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package actor
import (
"fmt"
"reflect"
"time"
"github.com/AsynkronIT/protoactor-go/actor"
protoPersistence "github.com/AsynkronIT/protoactor-go/persistence"
"github.com/fnproject/flow/graph"
"github.com/fnproject/flow/model"
"github.com/fnproject/flow/persistence"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/sirupsen/logrus"
)
const (
// The commitTimeout indicates how long a graph actor has between being started
// and committed before it is passivated
commitTimeout = time.Duration(5 * time.Minute)
// The inactiveTimeout indicates how long a graph actor has between being committed
// and completed before it is passivated
completionTimeout = time.Duration(24 * time.Hour)
// The readTimeout indicates how long a completed graph has after being rematerialized
// from storage before it is passivated
readTimeout = time.Duration(5 * time.Minute)
)
type graphActor struct {
PIDHolder
graph *graph.CompletionGraph
log *logrus.Entry
executor *actor.PID
persistence.Mixin
}
// NewGraphActor returns a pointer to a new graph actor
func NewGraphActor(executor *actor.PID) actor.Actor {
return &graphActor{
executor: executor,
log: logrus.WithField("logger", "graph_actor"),
}
}
func (g *graphActor) Receive(context actor.Context) {
g.log.Debugf("Processing message %s (recovering=%v)", reflect.TypeOf(context.Message()), g.Recovering())
if g.Recovering() {
if e, ok := context.Message().(model.Event); ok {
g.receiveEvent(e)
}
} else {
if c, ok := context.Message().(model.Command); ok {
g.receiveCommand(c, context)
} else {
g.receiveMessage(context)
}
}
}
func (g *graphActor) initGraph(event *model.GraphCreatedEvent) {
g.log = g.log.WithFields(logrus.Fields{"logger": "graph_actor", "flow_id": event.FlowId, "function_id": event.FunctionId})
g.graph = graph.New(event.FlowId, event.FunctionId, g)
}
func (g *graphActor) receiveEvent(event model.Event) {
switch e := event.(type) {
case *model.GraphCreatedEvent:
g.initGraph(e)
case *model.DelayScheduledEvent:
g.scheduleDelay(e)
default:
if g.graph == nil {
panic(fmt.Sprintf("Trying to replay event %v but graph is not initialized", reflect.TypeOf(event)))
}
g.graph.UpdateWithEvent(e, false)
}
}
// if validation fails, this method will respond to the request with an appropriate error message
func (g *graphActor) validateCmd(cmd model.Command, context actor.Context) bool {
switch msg := cmd.(type) {
case *model.CreateGraphRequest:
if g.graph != nil {
g.log.Warn("Graph has already been created")
context.Respond(model.NewGraphAlreadyExistsError(msg.GetFlowId()))
return false
}
default:
if g.graph == nil {
context.Respond(model.NewGraphNotFoundError(msg.GetFlowId()))
return false
}
if validationError := g.graph.ValidateCommand(msg); validationError != nil {
context.Respond(validationError)
return false
}
}
return true
}
func currentTimestamp() *timestamp.Timestamp {
now := time.Now()
return ×tamp.Timestamp{
Seconds: now.Unix(),
Nanos: int32(now.Nanosecond()),
}
}
func (g *graphActor) receiveCommand(cmd model.Command, context actor.Context) {
if !g.validateCmd(cmd, context) {
return
}
switch msg := cmd.(type) {
case *model.CreateGraphRequest:
g.log.Debug("Creating graph")
event := &model.GraphCreatedEvent{
FlowId: msg.FlowId,
FunctionId: msg.FunctionId,
Ts: currentTimestamp()}
g.PersistReceive(event)
g.initGraph(event)
context.Respond(&model.CreateGraphResponse{FlowId: msg.FlowId})
case *model.GetGraphStateRequest:
g.log.Debug("Get graph state")
context.Respond(g.createExternalState())
case *model.AddStageRequest:
g.log.Debug("Adding chained stage")
stageID := g.graph.NextStageID()
g.persistAndUpdateGraph(&model.StageAddedEvent{
FlowId: msg.FlowId,
StageId: stageID,
Op: msg.Operation,
Closure: msg.Closure,
Dependencies: msg.Deps,
Ts: currentTimestamp(),
CodeLocation: msg.CodeLocation,
CallerId: msg.CallerId,
})
context.Respond(&model.AddStageResponse{FlowId: msg.FlowId, StageId: stageID})
case *model.AddCompletedValueStageRequest:
g.log.Debug("Adding completed value stage")
stageID := g.graph.NextStageID()
g.persistAndUpdateGraph(&model.StageAddedEvent{
FlowId: msg.FlowId,
StageId: stageID,
Op: msg.GetOperation(),
Ts: currentTimestamp(),
CodeLocation: msg.CodeLocation,
CallerId: msg.CallerId,
})
g.persistAndUpdateGraph(&model.StageCompletedEvent{
FlowId: msg.FlowId,
StageId: stageID,
Result: msg.Value,
Ts: currentTimestamp(),
})
context.Respond(&model.AddStageResponse{FlowId: msg.FlowId, StageId: stageID})
case *model.AddDelayStageRequest:
g.log.Debug("Adding delay stage")
stageID := g.graph.NextStageID()
g.persistAndUpdateGraph(&model.StageAddedEvent{
FlowId: msg.FlowId,
StageId: stageID,
Op: msg.GetOperation(),
Ts: currentTimestamp(),
CodeLocation: msg.CodeLocation,
CallerId: msg.CallerId,
})
delayEvent := &model.DelayScheduledEvent{
FlowId: msg.FlowId,
StageId: stageID,
TimeMs: timeMillis() + msg.DelayMs,
Ts: currentTimestamp(),
}
g.PersistReceive(delayEvent)
g.scheduleDelay(delayEvent)
context.Respond(&model.AddStageResponse{FlowId: msg.FlowId, StageId: stageID})
case *model.AddInvokeFunctionStageRequest:
g.log.Debug("Adding invoke stage")
stageID := g.graph.NextStageID()
realFunctionID := msg.FunctionId
g.persistAndUpdateGraph(&model.StageAddedEvent{
FlowId: msg.FlowId,
StageId: stageID,
Op: msg.GetOperation(),
Ts: currentTimestamp(),
CodeLocation: msg.CodeLocation,
CallerId: msg.CallerId,
})
g.PersistReceive(&model.FaasInvocationStartedEvent{
FlowId: msg.FlowId,
StageId: stageID,
Ts: currentTimestamp(),
FunctionId: realFunctionID,
})
g.executor.Request(&model.InvokeFunctionRequest{
FlowId: msg.FlowId,
StageId: stageID,
FunctionId: realFunctionID,
Arg: msg.Arg,
}, g.GetSelf())
context.Respond(&model.AddStageResponse{FlowId: msg.FlowId, StageId: stageID})
case *model.CompleteStageExternallyRequest:
g.log.WithFields(logrus.Fields{"stage_id": msg.StageId}).Debug("Completing stage externally")
stage := g.graph.GetStage(msg.StageId)
completable := !stage.IsResolved()
if completable {
g.persistAndUpdateGraph(&model.StageCompletedEvent{
FlowId: msg.FlowId,
StageId: msg.StageId,
Result: msg.Value,
Ts: currentTimestamp(),
})
}
context.Respond(&model.CompleteStageExternallyResponse{FlowId: msg.FlowId, StageId: msg.StageId, Successful: completable})
case *model.CommitGraphRequest:
response := &model.GraphRequestProcessedResponse{FlowId: msg.FlowId}
if g.graph.IsCommitted() {
// idempotent
context.Respond(response)
return
}
g.log.Debug("Committing graph")
g.persistAndUpdateGraph(&model.GraphCommittedEvent{
FlowId: msg.FlowId,
Ts: currentTimestamp(),
})
context.SetReceiveTimeout(completionTimeout)
context.Respond(response)
case *model.AwaitStageResultRequest:
g.log.WithFields(logrus.Fields{"stage_id": msg.StageId}).Debug("Retrieving stage result")
stage := g.graph.GetStage(msg.StageId)
context.AwaitFuture(stage.WhenComplete(), func(result interface{}, err error) {
if err != nil {
context.Respond(model.NewAwaitStageError(msg.FlowId, msg.StageId))
return
}
response := &model.AwaitStageResultResponse{
FlowId: msg.FlowId,
StageId: msg.StageId,
Result: result.(*model.CompletionResult),
}
context.Respond(response)
})
case *model.CompleteDelayStageRequest:
if stage := g.graph.GetStage(msg.StageId); stage != nil && stage.IsResolved() {
// avoids accumulating duplicate StageCompletedEvents
return
}
g.log.WithFields(logrus.Fields{"stage_id": msg.StageId}).Debug("Completing delayed stage")
g.persistAndUpdateGraph(&model.StageCompletedEvent{
FlowId: msg.FlowId,
StageId: msg.StageId,
Result: msg.Result,
Ts: currentTimestamp(),
})
case *model.FaasInvocationResponse:
g.log.WithFields(logrus.Fields{"stage_id": msg.StageId}).Debug("Received fn invocation response")
g.persistAndUpdateGraph(&model.FaasInvocationCompletedEvent{
FlowId: msg.FlowId,
StageId: msg.StageId,
Result: msg.Result,
Ts: currentTimestamp(),
CallId: msg.CallId,
})
case *model.DeactivateGraphRequest:
g.log.Debug("Requesting supervisor to deactivate graph")
// tell supervisor to remove us from active graphs
context.Parent().Tell(msg)
default:
g.log.Debugf("Ignoring command of unknown type %v", reflect.TypeOf(msg))
}
}
func (g *graphActor) receiveMessage(context actor.Context) {
switch msg := context.Message().(type) {
case *protoPersistence.RequestSnapshot:
// snapshots are currently not supported
// NOOP
g.log.Debug("Ignoring snapshot request")
case *actor.Started:
g.log.Debugf("Started actor %s", g.GetSelf().Id)
context.SetReceiveTimeout(commitTimeout)
case *actor.ReceiveTimeout:
if g.graph != nil {
g.log.Debugf("Requesting passivation of inactive actor %s", g.GetSelf().Id)
context.Parent().Tell(&model.DeactivateGraphRequest{FlowId: g.graph.ID})
return
}
g.log.Debugf("Cleaning up uninitialized actor %s", g.GetSelf().Id)
context.Self().GracefulStop()
case *protoPersistence.ReplayComplete:
if g.graph != nil {
g.log.Debug("Replay completed")
g.graph.Recover()
if g.graph.IsCompleted() {
// graph is in read-only mode
context.SetReceiveTimeout(readTimeout)
} else {
// graph is still being processed
context.SetReceiveTimeout(completionTimeout)
}
}
default:
g.log.Debugf("Ignoring message of unknown type %v", reflect.TypeOf(msg))
}
}
func (g *graphActor) scheduleDelay(event *model.DelayScheduledEvent) {
// we always need to complete delay nodes from scratch to avoid completing twice
delayMs := event.TimeMs - timeMillis()
delayReq := &model.CompleteDelayStageRequest{
FlowId: event.FlowId,
StageId: event.StageId,
Result: model.NewEmptyResult(),
}
if delayMs > 0 {
g.log.WithFields(logrus.Fields{"stage_id": event.StageId}).Debug("Scheduling delayed completion of stage")
// Wait for the delay in a goroutine so we can complete the request in the meantime
go func() {
<-time.After(time.Duration(delayMs) * time.Millisecond)
g.pid.Tell(delayReq)
}()
} else {
g.log.WithFields(logrus.Fields{"stage_id": event.StageId}).Debug("Queuing completion of delayed stage")
g.pid.Tell(delayReq)
}
}
func timeMillis() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}
func (g *graphActor) createExternalState() *model.GetGraphStateResponse {
stageOut := make(map[string]*model.GetGraphStateResponse_StageRepresentation)
for _, s := range g.graph.GetStages() {
var status string
if s.IsFailed() {
status = "failed"
} else if s.IsSuccessful() {
status = "successful"
} else if s.IsTriggered() {
status = "running"
} else {
status = "pending"
}
stageDeps := s.GetDeps()
deps := make([]string, len(stageDeps))
for i, dep := range stageDeps {
deps[i] = dep.GetID()
}
rep := &model.GetGraphStateResponse_StageRepresentation{
Type: model.CompletionOperation_name[int32(s.GetOperation())],
Status: status,
Dependencies: deps,
}
stageOut[s.ID] = rep
}
return &model.GetGraphStateResponse{
FlowId: g.graph.ID,
FunctionId: g.graph.FunctionID,
Stages: stageOut,
}
}
func (g *graphActor) OnExecuteStage(stage *graph.CompletionStage, results []*model.CompletionResult) {
g.log.WithField("stage_id", stage.ID).Info("Executing Stage")
g.PersistReceive(&model.FaasInvocationStartedEvent{
FlowId: g.graph.ID,
StageId: stage.ID,
Ts: currentTimestamp(),
FunctionId: g.graph.FunctionID,
})
req := &model.InvokeStageRequest{
FunctionId: g.graph.FunctionID,
FlowId: g.graph.ID,
StageId: stage.ID,
Args: results,
Closure: stage.GetClosure(),
}
g.executor.Request(req, g.GetSelf())
}
//OnCompleteStage indicates that a stage is finished and its result is available
func (g *graphActor) OnCompleteStage(stage *graph.CompletionStage, result *model.CompletionResult) {
g.log.WithField("stage_id", stage.ID).Info("Completing stage in OnCompleteStage")
g.persistAndUpdateGraph(&model.StageCompletedEvent{
FlowId: g.graph.ID,
StageId: stage.ID,
Result: result,
Ts: currentTimestamp(),
})
}
//OnCompose Stage indicates that another stage should be composed into this one
func (g *graphActor) OnComposeStage(stage *graph.CompletionStage, composedStage *graph.CompletionStage) {
g.log.WithField("stage_id", stage.ID).Info("Composing stage in OnComposeStage")
g.persistAndUpdateGraph(&model.StageComposedEvent{
FlowId: g.graph.ID,
StageId: stage.ID,
ComposedStageId: composedStage.ID,
Ts: currentTimestamp(),
})
}
func (g *graphActor) OnGraphExecutionFinished() {
if g.Recovering() {
return
}
g.persistAndUpdateGraph(&model.GraphTerminatingEvent{
FlowId: g.graph.ID,
FunctionId: g.graph.FunctionID,
Status: model.StatusDatumType_succeeded,
Ts: currentTimestamp(),
})
}
func (g *graphActor) OnGraphComplete() {
if g.Recovering() {
return
}
g.persistAndUpdateGraph(&model.GraphCompletedEvent{
FlowId: g.graph.ID,
FunctionId: g.graph.FunctionID,
Ts: currentTimestamp(),
})
g.GetSelf().Tell(&model.DeactivateGraphRequest{FlowId: g.graph.ID})
}
// persistAndUpdateGraph saves an event before applying it to the graph
func (g *graphActor) persistAndUpdateGraph(event model.Event) {
if g.graph == nil {
g.log.Errorf("Ignoring state update for event %v since graph is not initialized", reflect.TypeOf(event))
return
}
g.PersistReceive(event)
g.graph.UpdateWithEvent(event, !g.Recovering())
}