forked from project-flogo/flow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
action.go
313 lines (243 loc) · 7.15 KB
/
action.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
package flow
import (
"context"
"errors"
"fmt"
"os"
"strconv"
"strings"
"github.com/project-flogo/core/action"
"github.com/project-flogo/core/app/resource"
"github.com/project-flogo/core/data/expression"
"github.com/project-flogo/core/data/mapper"
"github.com/project-flogo/core/data/metadata"
"github.com/project-flogo/core/support"
"github.com/project-flogo/core/support/log"
"github.com/project-flogo/flow/definition"
"github.com/project-flogo/flow/instance"
"github.com/project-flogo/flow/model"
_ "github.com/project-flogo/flow/model/simple"
flowSupport "github.com/project-flogo/flow/support"
"github.com/project-flogo/flow/tester"
)
const (
ENV_FLOW_RECORD = "FLOGO_FLOW_RECORD"
)
func init() {
action.Register(&FlowAction{}, &ActionFactory{})
resource.RegisterLoader(flowSupport.RESTYPE_FLOW, &flowSupport.FlowLoader{})
}
var ep ExtensionProvider
var idGenerator *support.Generator
var record bool
var maxStepCount = 1000000
var actionMd = action.ToMetadata(&Settings{})
var logger log.Logger
var flowManager *flowSupport.FlowManager
func SetExtensionProvider(provider ExtensionProvider) {
ep = provider
}
type ActionFactory struct {
resManager *resource.Manager
}
func (f *ActionFactory) Initialize(ctx action.InitContext) error {
f.resManager = ctx.ResourceManager()
logger = log.ChildLogger(log.RootLogger(), "flow")
if flowManager != nil {
return nil
}
if ep == nil {
testerEnabled := os.Getenv(tester.ENV_ENABLED)
if strings.ToLower(testerEnabled) == "true" {
ep = tester.NewExtensionProvider()
sm := support.GetDefaultServiceManager()
sm.RegisterService(ep.GetFlowTester())
record = true
} else {
ep = NewDefaultExtensionProvider()
record = recordFlows()
}
}
exprFactory := expression.NewFactory(definition.GetDataResolver())
mapperFactory := mapper.NewFactory(definition.GetDataResolver())
definition.SetMapperFactory(mapperFactory)
definition.SetExprFactory(exprFactory)
if idGenerator == nil {
idGenerator, _ = support.NewGenerator()
}
model.RegisterDefault(ep.GetDefaultFlowModel())
flowManager = flowSupport.NewFlowManager(ep.GetFlowProvider())
resource.RegisterLoader(flowSupport.RESTYPE_FLOW, &flowSupport.FlowLoader{})
flowSupport.InitDefaultDefLookup(flowManager, ctx.ResourceManager())
return nil
}
func recordFlows() bool {
recordFlows := os.Getenv(ENV_FLOW_RECORD)
if len(recordFlows) == 0 {
return false
}
b, _ := strconv.ParseBool(recordFlows)
return b
}
func (f *ActionFactory) New(config *action.Config) (action.Action, error) {
flowAction := &FlowAction{}
settings := &Settings{}
err := metadata.MapToStruct(config.Settings, settings, true)
if err != nil {
return nil, fmt.Errorf("action settings error: %s", err.Error())
}
flowAction.flowURI = settings.FlowURI
def, res, err := flowSupport.GetDefinition(flowAction.flowURI)
if err != nil {
return nil, err
}
if def == nil {
return nil, errors.New("unable to resolve flow: " + flowAction.flowURI)
}
flowAction.ioMetadata = def.Metadata()
if res {
flowAction.resFlow = def
}
return flowAction, nil
}
type FlowAction struct {
flowURI string
resFlow *definition.Definition
ioMetadata *metadata.IOMetadata
info *action.Info
}
func (fa *FlowAction) Info() *action.Info {
return fa.info
}
//Metadata get the Action's metadata
func (fa *FlowAction) Metadata() *action.Metadata {
return actionMd
}
func (fa *FlowAction) IOMetadata() *metadata.IOMetadata {
return fa.ioMetadata
}
// Run implements action.Action.Run
func (fa *FlowAction) Run(context context.Context, inputs map[string]interface{}, handler action.ResultHandler) error {
var err error
op := instance.OpStart
retID := false
var initialState *instance.IndependentInstance
var flowURI string
runOptions, exists := inputs["_run_options"]
var execOptions *instance.ExecOptions
if exists {
ro, ok := runOptions.(*instance.RunOptions)
if ok {
op = ro.Op
retID = ro.ReturnID
initialState = ro.InitialState
flowURI = ro.FlowURI
execOptions = ro.ExecOptions
}
}
delete(inputs, "_run_options")
if flowURI == "" {
flowURI = fa.flowURI
}
logger.Debugf("Running FlowAction for URI: '%s'", flowURI)
//todo: catch panic
//todo: consider switch to URI to dictate flow operation (ex. flow://blah/resume)
var inst *instance.IndependentInstance
switch op {
case instance.OpStart:
flowDef := fa.resFlow
if flowDef == nil {
var err error
flowDef, err = flowManager.GetFlow(flowURI)
if err != nil {
return err
}
if flowDef == nil {
return errors.New("flow not found for URI: " + flowURI)
}
}
instanceID := idGenerator.NextAsString()
logger.Debug("Creating Flow Instance: ", instanceID)
instLogger := logger
if log.CtxLoggingEnabled() {
instLogger = log.ChildLoggerWithFields(logger, log.String("flowName", flowDef.Name()), log.String("flowId", instanceID))
}
inst, err = instance.NewIndependentInstance(instanceID, flowURI, flowDef, instLogger)
if err != nil {
return err
}
case instance.OpResume:
if initialState != nil {
inst = initialState
logger.Debug("Resuming Flow Instance: ", inst.ID())
} else {
return errors.New("unable to resume instance, initial state not provided")
}
case instance.OpRestart:
if initialState != nil {
inst = initialState
instanceID := idGenerator.NextAsString()
//flowDef, err := manager.GetFlow(flowURI)
//if err != nil {
// return err
//}
//if flowDef.Metadata == nil {
// //flowDef.SetMetadata(fa.config.Metadata)
//}
err := inst.Restart(instanceID, flowManager)
if err != nil {
return err
}
logger.Debug("Restarting Flow Instance: ", instanceID)
} else {
return errors.New("unable to restart instance, initial state not provided")
}
}
if execOptions != nil {
logger.Debugf("Applying Exec Options to instance: %s", inst.ID())
instance.ApplyExecOptions(inst, execOptions)
}
//todo how do we check if debug is enabled?
//logInputs(inputs)
logger.Debugf("Executing Flow Instance: %s", inst.ID())
if op == instance.OpStart {
inst.Start(inputs)
} else {
inst.UpdateAttrs(inputs)
}
stepCount := 0
hasWork := true
inst.SetResultHandler(handler)
go func() {
defer handler.Done()
if retID {
//idAttr, _ := data.NewAttribute("id", data.TypeString, inst.ID())
results := map[string]interface{}{
"id": inst.ID(),
}
handler.HandleResult(results, nil)
}
for hasWork && inst.Status() < model.FlowStatusCompleted && stepCount < maxStepCount {
stepCount++
logger.Debugf("Step: %d", stepCount)
hasWork = inst.DoStep()
if record {
ep.GetStateRecorder().RecordSnapshot(inst)
ep.GetStateRecorder().RecordStep(inst)
}
}
if inst.Status() == model.FlowStatusCompleted {
returnData, err := inst.GetReturnData()
handler.HandleResult(returnData, err)
} else if inst.Status() == model.FlowStatusFailed {
handler.HandleResult(nil, inst.GetError())
}
logger.Debugf("Done Executing flow instance [%s] - Status: %d", inst.ID(), inst.Status())
if inst.Status() == model.FlowStatusCompleted {
logger.Infof("Instance [%s] Done", inst.ID())
} else if inst.Status() == model.FlowStatusFailed {
logger.Infof("Instance [%s] Failed", inst.ID())
}
}()
return nil
}