forked from s8sg/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
1463 lines (1216 loc) · 43.5 KB
/
executor.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package executor
import (
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/url"
"strconv"
hmac "github.com/alexellis/hmac"
xid "github.com/rs/xid"
sdk "github.com/changfeng012008/goflow/core/sdk"
)
// RawRequest a raw request for the flow
type RawRequest struct {
Data []byte
AuthSignature string
Query string
RequestId string // RequestId is Optional, if provided faas-flow will reuse it
}
// PartialState a partial request for the flow
type PartialState struct {
uprequest *Request
}
func DecodePartialReq(encodedState []byte) (*PartialState, error) {
request, err := decodeRequest(encodedState)
if err != nil {
return nil, err
}
req := &PartialState{uprequest: request}
return req, err
}
func (req *PartialState) Encode() ([]byte, error) {
return req.uprequest.encode()
}
// ExecutionRuntime implements how operation executed and handle next nodes in async
type ExecutionRuntime interface {
// HandleNextNode handles execution of next nodes based on partial state
HandleNextNode(state *PartialState) (err error)
// Provide an execution option that will be passed to the operation
GetExecutionOption(operation sdk.Operation) map[string]interface{}
// Handle the completion of execution of data
HandleExecutionCompletion(data []byte) error
}
// Executor implements a faas-flow executor
type Executor interface {
// Configure configure an executor with request id
Configure(requestId string)
// GetFlowName get name of the flow
GetFlowName() string
// GetFlowDefinition get definition of the faas-flow
GetFlowDefinition(*sdk.Pipeline, *sdk.Context) error
// ReqValidationEnabled check if request validation enabled
ReqValidationEnabled() bool
// GetValidationKey get request validation key
GetValidationKey() (string, error)
// ReqAuthEnabled check if request auth enabled
ReqAuthEnabled() bool
// GetReqAuthKey get the request auth key
GetReqAuthKey() (string, error)
// MonitoringEnabled check if request monitoring enabled
MonitoringEnabled() bool
// GetEventHandler get the event handler for request monitoring
GetEventHandler() (sdk.EventHandler, error)
// LoggingEnabled check if logging is enabled
LoggingEnabled() bool
// GetLogger get the logger
GetLogger() (sdk.Logger, error)
// GetStateStore get the state store
GetStateStore() (sdk.StateStore, error)
// GetDataStore get the data store
GetDataStore() (sdk.DataStore, error)
ExecutionRuntime
}
// FlowExecutor faas-flow executor
type FlowExecutor struct {
flow *sdk.Pipeline // the faas-flow
// the pipeline properties
hasBranch bool // State if the pipeline dag has at-least one branch
hasEdge bool // State if pipeline dag has at-least one edge
isExecutionFlow bool // State if pipeline has execution only branches
flowName string // the name of the flow
id string // the unique request id
query string // the query to the flow
eventHandler sdk.EventHandler // Handler flow events
logger sdk.Logger // Handle flow logs
stateStore sdk.StateStore // the state store
dataStore sdk.DataStore // the data store
partial bool // denotes the flow is in partial execution state
newRequest *RawRequest // holds the new request
partialState *PartialState // holds the partially completed state
finished bool // denote the flow has finished execution
executor Executor // executor
notifyChan chan string // notify about execution complete, if not nil
}
const (
STATE_RUNNING = "RUNNING"
STATE_FINISHED = "FINISHED"
STATE_PAUSED = "PAUSED"
)
type ExecutionStateOptions struct {
newRequest *RawRequest
partialState *PartialState
}
type ExecutionStateOption func(*ExecutionStateOptions)
func NewRequest(request *RawRequest) ExecutionStateOption {
return func(o *ExecutionStateOptions) {
o.newRequest = request
}
}
func PartialRequest(partialState *PartialState) ExecutionStateOption {
return func(o *ExecutionStateOptions) {
o.partialState = partialState
}
}
const (
// signature of SHA265 equivalent of "github.com/s8sg/faas-flow"
defaultHmacKey = "71F1D3011F8E6160813B4997BA29856744375A7F26D427D491E1CCABD4627E7C"
// max retry count to update counter
counterUpdateRetryCount = 10
)
// log logs using logger if logging enabled
func (fexec *FlowExecutor) log(str string, a ...interface{}) {
if fexec.executor.LoggingEnabled() {
str := fmt.Sprintf(str, a...)
fexec.logger.Log(str)
}
}
// setRequestState set the request state
func (fexec *FlowExecutor) setRequestState(state string) error {
return fexec.stateStore.Set("request-state", state)
}
// getRequestState get state of the request
func (fexec *FlowExecutor) getRequestState() (string, error) {
value, err := fexec.stateStore.Get("request-state")
return value, err
}
// setDynamicBranchOptions set dynamic options for a dynamic node
func (fexec *FlowExecutor) setDynamicBranchOptions(nodeUniqueId string, options []string) error {
encoded, err := json.Marshal(options)
if err != nil {
return err
}
return fexec.stateStore.Set(nodeUniqueId, string(encoded))
}
// getDynamicBranchOptions get dynamic options for a dynamic node
func (fexec *FlowExecutor) getDynamicBranchOptions(nodeUniqueId string) ([]string, error) {
encoded, err := fexec.stateStore.Get(nodeUniqueId)
if err != nil {
return nil, err
}
var option []string
err = json.Unmarshal([]byte(encoded), &option)
return option, err
}
// incrementCounter increment counter by given term, if doesn't exist init with increment by
func (fexec *FlowExecutor) incrementCounter(counter string, incrementBy int) (int, error) {
var serr error
count := 0
for i := 0; i < counterUpdateRetryCount; i++ {
encoded, err := fexec.stateStore.Get(counter)
if err != nil {
// if doesn't exist try to create
err := fexec.stateStore.Set(counter, fmt.Sprintf("%d", incrementBy))
if err != nil {
serr = fmt.Errorf("failed to update counter %s, error %v", counter, err)
continue
}
return incrementBy, nil
}
current, err := strconv.Atoi(encoded)
if err != nil {
return 0, fmt.Errorf("failed to update counter %s, error %v", counter, err)
}
count = current + incrementBy
counterStr := fmt.Sprintf("%d", count)
err = fexec.stateStore.Update(counter, encoded, counterStr)
if err == nil {
return count, nil
}
serr = err
}
return 0, fmt.Errorf("failed to update counter after max retry for %s, error %v", counter, serr)
}
// retrieveCounter retrieves a counter value
func (fexec *FlowExecutor) retrieveCounter(counter string) (int, error) {
encoded, err := fexec.stateStore.Get(counter)
if err != nil {
return 0, fmt.Errorf("failed to get counter %s, error %v", counter, err)
}
current, err := strconv.Atoi(encoded)
if err != nil {
return 0, fmt.Errorf("failed to get counter %s, error %v", counter, err)
}
return current, nil
}
func (fexec *FlowExecutor) storePartialState(partialState *PartialState) error {
data, _ := partialState.Encode()
enState := string(data)
partialStates := []string{enState}
key := "partial-state"
var serr error
for i := 0; i < counterUpdateRetryCount; i++ {
encoded, err := fexec.stateStore.Get(key)
if err != nil {
data, _ := json.Marshal(partialStates)
// if doesn't exist try to create
err := fexec.stateStore.Set(key, string(data))
if err != nil {
serr = fmt.Errorf("failed to update partial-state, error %v", err)
continue
}
return nil
}
err = json.Unmarshal([]byte(encoded), &partialStates)
if err != nil {
return fmt.Errorf("failed to update partial-state, error %v", err)
}
partialStates = append(partialStates, enState)
data, _ := json.Marshal(partialStates)
err = fexec.stateStore.Update(key, encoded, string(data))
if err == nil {
return nil
}
serr = err
}
return fmt.Errorf("failed to update partial-state after max retry, error %v", serr)
}
func (fexec *FlowExecutor) retrievePartialStates() ([]*PartialState, error) {
key := "partial-state"
var encodedStates []string
var partialStates []*PartialState
encoded, err := fexec.stateStore.Get(key)
if err != nil {
return nil, fmt.Errorf("failed to retrive partial-state, error %v", err)
}
err = json.Unmarshal([]byte(encoded), &encodedStates)
if err != nil {
return nil, fmt.Errorf("failed to retrive partial-state, error %v", err)
}
for _, state := range encodedStates {
ps, err := DecodePartialReq([]byte(state))
if err != nil {
return nil, fmt.Errorf("failed to retrive partial-state, error %v", err)
}
partialStates = append(partialStates, ps)
}
return partialStates, nil
}
// isActive check if flow is active
func (fexec *FlowExecutor) isActive() bool {
state, err := fexec.getRequestState()
if err != nil {
fexec.log("[request `%s`] failed to obtain pipeline state, error %v\n", fexec.id, err)
return false
}
return state == STATE_RUNNING || state == STATE_PAUSED
}
// isRunning check if flow is running
func (fexec *FlowExecutor) isRunning() bool {
state, err := fexec.getRequestState()
if err != nil {
fexec.log("[request `%s`] failed to obtain pipeline state\n", fexec.id)
return false
}
return state == STATE_RUNNING
}
// isPaused check if flow is paused
func (fexec *FlowExecutor) isPaused() bool {
state, err := fexec.getRequestState()
if err != nil {
fexec.log("[request `%s`] failed to obtain pipeline state\n", fexec.id)
return false
}
return state == STATE_PAUSED
}
// executeNode executes a node on a faas-flow dag
func (fexec *FlowExecutor) executeNode(request []byte) ([]byte, error) {
var result []byte
var err error
pipeline := fexec.flow
currentNode, _ := pipeline.GetCurrentNodeDag()
// mark as start of node
if fexec.executor.MonitoringEnabled() {
fexec.eventHandler.ReportNodeStart(currentNode.GetUniqueId(), fexec.id)
}
for _, operation := range currentNode.Operations() {
// Check if request is terminate
if !fexec.isActive() {
fexec.log("[request `%s`] pipeline is not active\n", fexec.id)
panic(fmt.Sprintf("[request `%s`] Pipeline is not active", fexec.id))
}
if fexec.executor.MonitoringEnabled() {
fexec.eventHandler.ReportOperationStart(operation.GetId(), currentNode.GetUniqueId(), fexec.id)
}
options := fexec.executor.GetExecutionOption(operation)
if result == nil {
result, err = operation.Execute(request, options)
} else {
result, err = operation.Execute(result, options)
}
if err != nil {
if fexec.executor.MonitoringEnabled() {
fexec.eventHandler.ReportOperationFailure(operation.GetId(), currentNode.GetUniqueId(), fexec.id, err)
}
err = fmt.Errorf("Node(%s), Operation (%s), error: execution failed, %v",
currentNode.GetUniqueId(), operation.GetId(), err)
return nil, err
}
if fexec.executor.MonitoringEnabled() {
fexec.eventHandler.ReportOperationEnd(operation.GetId(), currentNode.GetUniqueId(), fexec.id)
}
}
fexec.log("[request `%s`] completed execution of node %s\n", fexec.id, currentNode.GetUniqueId())
return result, nil
}
// findCurrentNodeToExecute find right node to execute based on state
func (fexec *FlowExecutor) findCurrentNodeToExecute() {
currentNode, currentDag := fexec.flow.GetCurrentNodeDag()
fexec.log("[request `%s`] executing node %s\n", fexec.id, currentNode.GetUniqueId())
// recurse to the subdag - if a node is dynamic stop to evaluate it
for true {
// break if request is dynamic
if currentNode.Dynamic() {
return
}
subdag := currentNode.SubDag()
if subdag == nil {
break
}
// trace node - mark as start of the parent node
if fexec.executor.MonitoringEnabled() {
fexec.eventHandler.ReportNodeStart(currentNode.GetUniqueId(), fexec.id)
}
fexec.log("[request `%s`] executing node %s\n", fexec.id, currentNode.GetUniqueId())
currentDag = subdag
currentNode = currentDag.GetInitialNode()
fexec.flow.UpdatePipelineExecutionPosition(sdk.DEPTH_INCREMENT, currentNode.Id)
}
}
// forwardState forward async request to core
func (fexec *FlowExecutor) forwardState(currentNodeId string, nextNodeId string, result []byte) error {
var sign string
store := make(map[string][]byte)
// get pipeline
pipeline := fexec.flow
// Get pipeline state
pipelineState := pipeline.GetState()
defaultStore, ok := fexec.dataStore.(*requestEmbedDataStore)
if ok {
store = defaultStore.store
}
// Check if request validation used
if fexec.executor.ReqValidationEnabled() {
key, err := fexec.executor.GetValidationKey()
if err != nil {
return fmt.Errorf("failed to get key, error %v", err)
}
hash := hmac.Sign([]byte(pipelineState), []byte(key))
sign = "sha1=" + hex.EncodeToString(hash)
}
// Build request
uprequest := buildRequest(fexec.id, string(pipelineState), fexec.query, result, store, sign)
if fexec.executor.MonitoringEnabled() {
fexec.eventHandler.ReportExecutionForward(currentNodeId, fexec.id)
}
partialState := &PartialState{uprequest: uprequest}
var err error
if fexec.isPaused() {
// if request is paused, store the partial state in the StateStore
fexec.log("[request `%s`] Request is paused, storing partial state for node: %s\n", fexec.id, nextNodeId)
err = fexec.storePartialState(partialState)
if err != nil {
return err
}
}
err = fexec.executor.HandleNextNode(partialState)
if err != nil {
return err
}
return nil
}
// executeDynamic executes a dynamic node
func (fexec *FlowExecutor) executeDynamic(context *sdk.Context, result []byte) ([]byte, error) {
// get pipeline
pipeline := fexec.flow
currentNode, _ := pipeline.GetCurrentNodeDag()
// trace node - mark as start of the dynamic node
if fexec.executor.MonitoringEnabled() {
fexec.eventHandler.ReportNodeStart(currentNode.GetUniqueId(),
fexec.id)
}
currentNodeUniqueId := currentNode.GetUniqueId()
if fexec.executor.MonitoringEnabled() {
defer fexec.eventHandler.ReportNodeEnd(currentNodeUniqueId, fexec.id)
}
fexec.log("[request `%s`] processing dynamic node %s\n", fexec.id, currentNodeUniqueId)
// sub results and sub dags
subresults := make(map[string][]byte)
subdags := make(map[string]*sdk.Dag)
options := []string{}
condition := currentNode.GetCondition()
foreach := currentNode.GetForEach()
switch {
case condition != nil:
fexec.log("[request `%s`] executing condition\n", fexec.id)
conditions := condition(result)
if conditions == nil {
panic(fmt.Sprintf("Condition function at %s returned nil, failed to proceed",
currentNodeUniqueId))
}
for _, conditionKey := range conditions {
if len(conditionKey) == 0 {
panic(fmt.Sprintf("Condition function at %s returned invalid condiiton, failed to proceed",
currentNodeUniqueId))
}
subdags[conditionKey] = currentNode.GetConditionalDag(conditionKey)
if subdags[conditionKey] == nil {
panic(fmt.Sprintf("Condition function at %s returned invalid condiiton, failed to proceed",
currentNodeUniqueId))
}
subresults[conditionKey] = result
options = append(options, conditionKey)
}
case foreach != nil:
fexec.log("[request `%s`] executing foreach\n", fexec.id)
foreachResults := foreach(result)
if foreachResults == nil {
panic(fmt.Sprintf("Foreach function at %s returned nil, failed to proceed",
currentNodeUniqueId))
}
for foreachKey, foreachResult := range foreachResults {
if len(foreachKey) == 0 {
panic(fmt.Sprintf("Foreach function at %s returned invalid key, failed to proceed",
currentNodeUniqueId))
}
subdags[foreachKey] = currentNode.SubDag()
subresults[foreachKey] = foreachResult
options = append(options, foreachKey)
}
}
branchCount := len(options)
if branchCount == 0 {
return nil, fmt.Errorf("[request `%s`] Dynamic Node %s, failed to execute as condition/foreach returned no option",
fexec.id, currentNodeUniqueId)
}
// Set the no of branch completion for the current dynamic node
key := pipeline.GetNodeExecutionUniqueId(currentNode) + "-branch-completion"
_, err := fexec.incrementCounter(key, 0)
if err != nil {
return nil, fmt.Errorf("[request `%s`] Failed to initiate dynamic in-degree count for %s, err %v",
fexec.id, key, err)
}
fexec.log("[request `%s`] dynamic in-degree count initiated as %s\n",
fexec.id, key)
// Set all the dynamic options for the current dynamic node
key = pipeline.GetNodeExecutionUniqueId(currentNode) + "-dynamic-branch-options"
err = fexec.setDynamicBranchOptions(key, options)
if err != nil {
return nil, fmt.Errorf("[request `%s`] Dynamic Node %s, failed to store dynamic options",
fexec.id, currentNodeUniqueId)
}
fexec.log("[request `%s`] dynamic options initiated as %s\n",
fexec.id, key)
for option, subdag := range subdags {
subNode := subdag.GetInitialNode()
intermediateData := subresults[option]
// If forwarder is not nil its not an execution flow
if currentNode.GetForwarder("dynamic") != nil {
key := fmt.Sprintf("%s--%s--%s", option,
pipeline.GetNodeExecutionUniqueId(currentNode), subNode.GetUniqueId())
serr := context.Set(key, intermediateData)
if serr != nil {
return []byte(""), fmt.Errorf("failed to store intermediate result, error %v", serr)
}
fexec.log("[request `%s`] intermediate result for option %s from Node %s to %s stored as %s\n",
fexec.id, option, currentNodeUniqueId, subNode.GetUniqueId(), key)
// intermediateData is set to blank once its stored in storage
intermediateData = []byte("")
}
// Increment the depth to execute the dynamic branch
pipeline.UpdatePipelineExecutionPosition(sdk.DEPTH_INCREMENT, subNode.Id)
// Set the option the dynamic branch is performing
pipeline.CurrentDynamicOption[currentNode.GetUniqueId()] = option
// forward the flow request
forwardErr := fexec.forwardState(currentNode.GetUniqueId(), subNode.GetUniqueId(),
intermediateData)
if forwardErr != nil {
// reset dag execution position
pipeline.UpdatePipelineExecutionPosition(sdk.DEPTH_DECREMENT, currentNode.Id)
return nil, fmt.Errorf("Node(%s): error: %v",
currentNode.GetUniqueId(), forwardErr)
}
fexec.log("[request `%s`] request submitted for node %s option %s\n",
fexec.id, subNode.GetUniqueId(), option)
// reset pipeline
pipeline.UpdatePipelineExecutionPosition(sdk.DEPTH_DECREMENT, currentNode.Id)
delete(pipeline.CurrentDynamicOption, currentNode.GetUniqueId())
}
return []byte(""), nil
}
// findNextNodeToExecute find the next node(s) to execute after the current node
func (fexec *FlowExecutor) findNextNodeToExecute() bool {
// get pipeline
pipeline := fexec.flow
// Check if pipeline is active in state-store
if !fexec.isActive() {
fexec.log("[request `%s`] pipeline is not active\n", fexec.id)
panic(fmt.Sprintf("[request `%s`] Pipeline is not active", fexec.id))
}
currentNode, currentDag := pipeline.GetCurrentNodeDag()
// Check if the pipeline has completed execution return
// else change depth and continue executing
for true {
if fexec.executor.MonitoringEnabled() {
defer fexec.eventHandler.ReportNodeEnd(currentNode.GetUniqueId(), fexec.id)
}
// If nodes left in current dag return
if currentNode.Children() != nil {
return true
}
// If depth 0 then pipeline has finished
if pipeline.ExecutionDepth == 0 {
fexec.finished = true
return false
} else {
// Update position to lower depth
currentNode = currentDag.GetParentNode()
currentDag = currentNode.ParentDag()
pipeline.UpdatePipelineExecutionPosition(sdk.DEPTH_DECREMENT, currentNode.Id)
fexec.log("[request `%s`] executing node %s", fexec.id, currentNode.GetUniqueId())
// mark execution of the node for new depth
if fexec.executor.MonitoringEnabled() {
defer fexec.eventHandler.ReportNodeStart(currentNode.GetUniqueId(), fexec.id)
}
// If current node is a dynamic node, forward the request for its end
if currentNode.Dynamic() {
break
}
}
}
return false
}
// handleDynamicEnd handles the end of a dynamic node
func (fexec *FlowExecutor) handleDynamicEnd(context *sdk.Context, result []byte) ([]byte, error) {
pipeline := fexec.flow
currentNode, _ := pipeline.GetCurrentNodeDag()
// Get dynamic options computed for the current dynamic node
key := pipeline.GetNodeExecutionUniqueId(currentNode) + "-dynamic-branch-options"
options, err := fexec.getDynamicBranchOptions(key)
if err != nil {
return nil, fmt.Errorf("failed to retrive dynamic options for %v, error %v",
currentNode.GetUniqueId(), err)
}
// Get unique execution id of the node
branchkey := pipeline.GetNodeExecutionUniqueId(currentNode) + "-branch-completion"
// if in-degree is > 1 then use state-store to get in-degree completion state
if len(options) > 1 {
// Get unique execution id of the node
key = pipeline.GetNodeExecutionUniqueId(currentNode) + "-branch-completion"
// Update the state of in-degree completion and get the updated state
// Skip if dynamic node data forwarding is not disabled
if currentNode.GetForwarder("dynamic") != nil {
option := pipeline.CurrentDynamicOption[currentNode.GetUniqueId()]
key = fmt.Sprintf("%s--%s--%s", option, pipeline.GetNodeExecutionUniqueId(currentNode), currentNode.GetUniqueId())
err = context.Set(key, result)
if err != nil {
return nil, fmt.Errorf("failed to store branch result of dynamic node %s for option %s, error %v",
currentNode.GetUniqueId(), option, err)
}
fexec.log("[request `%s`] intermediate result from branch to dynamic node %s for option %s stored as %s\n",
fexec.id, currentNode.GetUniqueId(), option, key)
}
realIndegree, err := fexec.incrementCounter(branchkey, 1)
if err != nil {
return []byte(""), fmt.Errorf("failed to update inDegree counter for node %s", currentNode.GetUniqueId())
}
fexec.log("[request `%s`] executing end of dynamic node %s, completed in-degree: %d/%d\n",
fexec.id, currentNode.GetUniqueId(), realIndegree, len(options))
//not last branch return
if realIndegree < len(options) {
return nil, nil
}
} else {
fexec.log("[request `%s`] executing end of dynamic node %s, branch count 1\n",
fexec.id, currentNode.GetUniqueId())
}
// get current execution option
currentOption := pipeline.CurrentDynamicOption[currentNode.GetUniqueId()]
// skip aggregating if Data Forwarder is disabled for dynamic node
if currentNode.GetForwarder("dynamic") == nil {
return []byte(""), nil
}
subDataMap := make(map[string][]byte)
// Store the current data
subDataMap[currentOption] = result
// Receive data from a dynamic graph for each options
for _, option := range options {
key := fmt.Sprintf("%s--%s--%s",
option, pipeline.GetNodeExecutionUniqueId(currentNode), currentNode.GetUniqueId())
// skip retrieving data for current option
if option == currentOption {
context.Del(key)
continue
}
idata := context.GetBytes(key)
fexec.log("[request `%s`] intermediate result from branch to dynamic node %s for option %s retrieved from %s\n",
fexec.id, currentNode.GetUniqueId(), option, key)
// delete Intermediate data after retrieval
context.Del(key)
subDataMap[option] = idata
}
// Get SubAggregator and call
fexec.log("[request `%s`] executing aggregator of dynamic node %s\n",
fexec.id, currentNode.GetUniqueId())
aggregator := currentNode.GetSubAggregator()
data, serr := aggregator(subDataMap)
if serr != nil {
serr := fmt.Errorf("failed to aggregate dynamic node data, error %v", serr)
return nil, serr
}
if data == nil {
data = []byte("")
}
return data, nil
}
// handleNextNodes Handle request Response for a faas-flow perform response/async-forward
func (fexec *FlowExecutor) handleNextNodes(context *sdk.Context, result []byte) ([]byte, error) {
// get pipeline
pipeline := fexec.flow
currentNode, _ := pipeline.GetCurrentNodeDag()
nextNodes := currentNode.Children()
for _, node := range nextNodes {
var intermediateData []byte
// Node's total In-degree
inDegree := node.Indegree()
// Get forwarder for child node
forwarder := currentNode.GetForwarder(node.Id)
if forwarder != nil {
// call default or user defined forwarder
intermediateData = forwarder(result)
key := fmt.Sprintf("%s--%s", pipeline.GetNodeExecutionUniqueId(currentNode),
node.GetUniqueId())
serr := context.Set(key, intermediateData)
if serr != nil {
return []byte(""), fmt.Errorf("failed to store intermediate result, error %v", serr)
}
fexec.log("[request `%s`] intermediate result from node %s to %s stored as %s\n",
fexec.id, currentNode.GetUniqueId(), node.GetUniqueId(), key)
// intermediateData is set to blank once its stored in storage
intermediateData = []byte("")
} else {
// in case NoneForward forwarder in nil
intermediateData = []byte("")
}
// if in-degree is > 1 then use state-store to get in-degree completion state
if inDegree > 1 {
// Update the state of in-degree completion and get the updated state
key := pipeline.GetNodeExecutionUniqueId(node)
inDegreeUpdatedCount, err := fexec.incrementCounter(key, 1)
if err != nil {
return []byte(""), fmt.Errorf("failed to update inDegree counter for node %s", node.GetUniqueId())
}
// If all in-degree has finished call that node
if inDegree > inDegreeUpdatedCount {
fexec.log("[request `%s`] request for Node %s is delayed, completed indegree: %d/%d\n",
fexec.id, node.GetUniqueId(), inDegreeUpdatedCount, inDegree)
continue
} else {
fexec.log("[request `%s`] performing request for Node %s, completed indegree: %d/%d\n",
fexec.id, node.GetUniqueId(), inDegreeUpdatedCount, inDegree)
}
} else {
fexec.log("[request `%s`] performing request for Node %s, indegree count is 1\n",
fexec.id, node.GetUniqueId())
}
// Set the DagExecutionPosition as of next Node
pipeline.UpdatePipelineExecutionPosition(sdk.DEPTH_SAME, node.Id)
// forward the flow request
forwardErr := fexec.forwardState(currentNode.GetUniqueId(), node.GetUniqueId(),
intermediateData)
if forwardErr != nil {
// reset dag execution position
pipeline.UpdatePipelineExecutionPosition(sdk.DEPTH_SAME, currentNode.Id)
return nil, fmt.Errorf("Node(%s): error: %v",
node.GetUniqueId(), forwardErr)
}
fexec.log("[request `%s`] request submitted for Node %s\n",
fexec.id, node.GetUniqueId())
}
// reset dag execution position
pipeline.UpdatePipelineExecutionPosition(sdk.DEPTH_SAME, currentNode.Id)
return []byte(""), nil
}
// handleFailure handles failure with failure handler and call finally
func (fexec *FlowExecutor) handleFailure(context *sdk.Context, err error) {
var data []byte
context.State = sdk.StateFailure
// call failure handler if available
if fexec.flow.FailureHandler != nil {
fexec.log("[request `%s`] calling failure handler for error, %v\n",
fexec.id, err)
data, err = fexec.flow.FailureHandler(err)
}
fexec.finished = true
// call finally handler if available
if fexec.flow.Finally != nil {
fexec.log("[request `%s`] calling Finally handler with state: %s\n",
fexec.id, sdk.StateFailure)
fexec.flow.Finally(sdk.StateFailure)
}
if data != nil {
fexec.log("%s", string(data))
}
// Cleanup data and state for failure
if fexec.stateStore != nil {
fexec.stateStore.Cleanup()
}
fexec.dataStore.Cleanup()
if fexec.executor.MonitoringEnabled() {
fexec.eventHandler.ReportRequestFailure(fexec.id, err)
fexec.eventHandler.Flush()
}
fmt.Sprintf("[request `%s`] Failed, %v\n", fexec.id, err)
}
// getDagIntermediateData gets the intermediate data from earlier vertex
func (fexec *FlowExecutor) getDagIntermediateData(context *sdk.Context) ([]byte, error) {
var data []byte
pipeline := fexec.flow
currentNode, dag := pipeline.GetCurrentNodeDag()
dataMap := make(map[string][]byte)
var scenarioFirstNodeOfDynamicBranch bool
// if current node is the initial node of a dynamic branch dag
dagNode := dag.GetParentNode()
if dagNode != nil && dagNode.Dynamic() &&
dag.GetInitialNode() == currentNode {
scenarioFirstNodeOfDynamicBranch = true
}
switch {
// handle if current node is the initial node of a dynamic branch dag
case scenarioFirstNodeOfDynamicBranch:
// Skip if NoDataForward is specified
if dagNode.GetForwarder("dynamic") != nil {
option := pipeline.CurrentDynamicOption[dagNode.GetUniqueId()]
// Option not get appended in key as its already in state
key := fmt.Sprintf("%s--%s", pipeline.GetNodeExecutionUniqueId(dagNode), currentNode.GetUniqueId())
data = context.GetBytes(key)
fexec.log("[request `%s`] intermediate result from Node %s to Node %s for option %s retrieved from %s\n",
fexec.id, dagNode.GetUniqueId(), currentNode.GetUniqueId(),
option, key)
// delete intermediate data after retrieval
context.Del(key)
}
// handle normal scenario
default:
dependencies := currentNode.Dependency()
// current node has dependencies in same dag
for _, node := range dependencies {
// Skip if NoDataForward is specified
if node.GetForwarder(currentNode.Id) == nil {
continue
}
key := fmt.Sprintf("%s--%s", pipeline.GetNodeExecutionUniqueId(node), currentNode.GetUniqueId())
idata := context.GetBytes(key)
fexec.log("[request `%s`] intermediate result from Node %s to Node %s retrieved from %s\n",
fexec.id, node.GetUniqueId(), currentNode.GetUniqueId(), key)
// delete intermediate data after retrieval
context.Del(key)
dataMap[node.Id] = idata
}
// Avail the non aggregated input at context
context.NodeInput = dataMap
// If it has only one in-degree assign the result as a data
if len(dependencies) == 1 {
data = dataMap[dependencies[0].Id]
}
// If Aggregator is available get aggregator
aggregator := currentNode.GetAggregator()
if aggregator != nil {
sdata, serr := aggregator(dataMap)
if serr != nil {
serr := fmt.Errorf("failed to aggregate data, error %v", serr)
return data, serr
}
data = sdata
}
}
return data, nil
}
// initializeStore initialize the store
func (fexec *FlowExecutor) initializeStore() (stateSDefined bool, dataSOverride bool, err error) {
stateSDefined = false
dataSOverride = false
// Initialize the stateS
stateS, err := fexec.executor.GetStateStore()
if err != nil {
return
}
if stateS != nil {
fexec.stateStore = stateS
stateSDefined = true
fexec.stateStore.Configure(fexec.flowName, fexec.id)
// If request is not partial initialize the stateStore
if !fexec.partial {
err = fexec.stateStore.Init()
if err != nil {
return
}
}
}
// Initialize the dataS
dataS, err := fexec.executor.GetDataStore()
if err != nil {
return
}
if dataS != nil {
fexec.dataStore = dataS
dataSOverride = true
}
fexec.dataStore.Configure(fexec.flowName, fexec.id)
// If request is not partial initialize the dataStore
if !fexec.partial {
err = fexec.dataStore.Init()
}
return
}
// createContext create a context from request handler
func (fexec *FlowExecutor) createContext() *sdk.Context {
context := sdk.CreateContext(fexec.id, "",
fexec.flowName, fexec.dataStore)
context.Query, _ = url.ParseQuery(fexec.query)
return context
}