/
rapiddecider.go
338 lines (302 loc) · 10 KB
/
rapiddecider.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
// godebug run -instrument github.com/CaboodleData/gotools/workflow rapiddecider.go -stdout
// env GOOS=linux GOARCH=386 go build -v rapiddecider.go
// scp -i '/Users/shaun/Google Drive/Keys for Encryption etc/Amazon/RapidtradeDB3.pem' rapiddecider ubuntu@52.204.248.107:/opt/rapiddecider
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"strings"
"time"
"github.com/CaboodleData/gotools/amazon"
"github.com/CaboodleData/gotools/file"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/swf"
)
type decision struct {
svc *swf.SWF
tt string // task token associated with this decision
runid string //Workflows runid
workflowid string //
}
type result struct {
SupplierID string
File string
}
//Globals variables
var (
Info *log.Logger
Error *log.Logger
swfDomain = "Orders"
stdout bool
helpdesk = "shaun@rapidtrade.biz"
swfTasklist = "OrderDecider"
swfIdentity = "RapidDecider"
)
func main() {
flag.BoolVar(&stdout, "stdout", false, "Log to stdout")
flag.Parse()
// initialise logs
Info, Error = file.InitLogs(stdout, "/var/rapiddecider", "rapiddecider")
Info.Println("Starting rapiddecider =================>")
// start workflow
swfsvc := swf.New(session.New(), &aws.Config{Region: aws.String("us-east-1")})
params := &swf.PollForDecisionTaskInput{
Domain: aws.String(swfDomain), //
TaskList: &swf.TaskList{ //
Name: aws.String(swfTasklist), //
},
Identity: aws.String(swfIdentity),
MaximumPageSize: aws.Int64(100),
ReverseOrder: aws.Bool(true),
}
// loop forever while polling for work
for {
resp, err := swfsvc.PollForDecisionTask(params)
if err != nil {
amazon.SESSendEmail("support@rapidtrade.biz", helpdesk, swfIdentity+" unable to pole", err.Error())
Error.Printf("error: unable to poll for decision: %v\n", err)
//panic("Broken, check logs")
}
// if we do not receive a task token then 60 second time out occured so try again
if resp.TaskToken != nil {
if *resp.TaskToken != "" {
// Re-initialise logs so we get latest date
Info, Error = file.InitLogs(stdout, "/var/rapiddecider", "rapiddecider")
d := &decision{
svc: swfsvc,
tt: *resp.TaskToken,
runid: *resp.WorkflowExecution.RunId,
workflowid: *resp.WorkflowExecution.WorkflowId,
}
// make each decision in a goroutine which means that multiple decisions can be made
go d.makeDecision(resp.Events, resp.WorkflowExecution.RunId)
}
} else {
Info.Printf("debug - no decisions required\n")
}
}
}
func (d *decision) makeDecision(events []*swf.HistoryEvent, ID *string) {
Info.Print("###############\n")
Info.Print(ID)
Info.Print("\n##############\n")
var handled bool
var err error
// loop backwards through time and make decisions
for k, event := range events {
switch *event.EventType {
case "WorkflowExecutionStarted":
err = d.handleWorkflowStart(event)
if err != nil {
d.failWorkflow(*event.ActivityTaskFailedEventAttributes.Reason, err)
}
handled = true
case "ActivityTaskCompleted":
_ = "breakpoint"
lastActivity := d.getLastScheduledActivity(events)
switch string(lastActivity) {
case "postorder":
d.completeWorkflow("")
handled = true
}
case "ActivityTaskTimedOut":
d.handleTimeout()
handled = true
case "ActivityTaskFailed":
Info.Println("Cancelling workflow")
d.emailError("ActivityTaskFailed")
d.failWorkflow(*event.ActivityTaskFailedEventAttributes.Reason, nil)
handled = true
case "ActivityTaskCanceled":
d.failWorkflow("Workflow cancelled after activity cancelled", nil)
handled = true
case "WorkflowExecutionCancelRequested":
d.failWorkflow("Workflow cancelled by request", nil)
handled = true
case "TimerFired":
err = d.handleTimerFired(k, events)
handled = true
default:
Info.Printf("Unhandled: %s\n", *event.EventType)
}
if handled == true {
break // decision has been made so stop scanning the events
}
}
if err != nil {
Info.Printf("Error making decision. workflow failed: %v\n", err)
// we are not able to process the workflow so fail it
err2 := d.failWorkflow("", err)
if err2 != nil {
Info.Printf("error while failing workflow: %v\n", err2)
}
}
if handled == false {
Info.Printf("debug dump of received event for taskToken: %s\n", d.tt)
Info.Println(events)
Info.Printf("xxxx debug unhandled decision\n")
}
Info.Print("#################### completed handling Decision ####################\n")
// exit goroutine
}
// ============================== generic functions =========================================
// getLastScheduledActivity loops through the workflow events in reverse order to pick up the details of the name of the last scheduled activity
func (d *decision) getLastScheduledActivity(events []*swf.HistoryEvent) string {
for _, event := range events {
if *event.EventType == "ActivityTaskScheduled" {
return *event.ActivityTaskScheduledEventAttributes.ActivityType.Name
}
}
return ""
}
func (d *decision) handleTimerFired(k int, es []*swf.HistoryEvent) error {
return nil
}
func (d *decision) setTimer(sec, data, id string) error {
Info.Printf("debug start set timer to wait: %s seconds\n", sec)
params := &swf.RespondDecisionTaskCompletedInput{
TaskToken: aws.String(d.tt),
Decisions: []*swf.Decision{
{
DecisionType: aws.String("StartTimer"),
StartTimerDecisionAttributes: &swf.StartTimerDecisionAttributes{
StartToFireTimeout: aws.String(sec),
TimerId: aws.String(id),
Control: aws.String(data),
},
},
},
ExecutionContext: aws.String("ssec2-amicreate"),
}
_, err := d.svc.RespondDecisionTaskCompleted(params)
return err
}
// handleTimeout will send an email if the first timeout, then set marker so next time we dont email
func (d *decision) handleTimeout() error {
to, _ := d.emailError("Activity Timeout")
params := &swf.RespondDecisionTaskCompletedInput{
TaskToken: aws.String(d.tt),
Decisions: []*swf.Decision{
{
DecisionType: aws.String("RecordMarker"),
RecordMarkerDecisionAttributes: &swf.RecordMarkerDecisionAttributes{
MarkerName: aws.String("HelpdeskNotified"),
Details: aws.String(to),
},
},
},
ExecutionContext: aws.String("Data"),
}
_, err := d.svc.RespondDecisionTaskCompleted(params)
return err // which may be nil
}
func (d *decision) emailError(reason string) (string, error) {
runid := strings.Replace(d.runid, "=", "!=", 1)
msg := "https://console.aws.amazon.com/swf/home?region=us-east-1#execution_events:domain=" + swfDomain + ";workflowId=" + d.workflowid + ";runId=" + runid
err := amazon.SESSendEmail("support@rapidtrade.biz", helpdesk, "Workflow "+reason+" Occured", msg)
if err != nil {
return "", err
}
Info.Printf("Error emailed to %v", helpdesk)
return helpdesk, nil
}
// completeWorkflow will complete workflow
func (d *decision) completeWorkflow(result string) error {
params := &swf.RespondDecisionTaskCompletedInput{
TaskToken: aws.String(d.tt),
Decisions: []*swf.Decision{
{
DecisionType: aws.String("CompleteWorkflowExecution"),
CompleteWorkflowExecutionDecisionAttributes: &swf.CompleteWorkflowExecutionDecisionAttributes{
Result: aws.String(result),
},
},
},
ExecutionContext: aws.String("Data"),
}
_, err := d.svc.RespondDecisionTaskCompleted(params)
return err // which may be nil
}
// completeWorkflow will complete workflow
func (d *decision) failWorkflow(details string, err error) error {
errorD := ""
if err != nil {
errorD = fmt.Sprintf("%v", err)
}
params := &swf.RespondDecisionTaskCompletedInput{
TaskToken: aws.String(d.tt),
Decisions: []*swf.Decision{
{
DecisionType: aws.String("FailWorkflowExecution"),
FailWorkflowExecutionDecisionAttributes: &swf.FailWorkflowExecutionDecisionAttributes{
Details: aws.String(details),
Reason: aws.String(errorD),
},
},
},
ExecutionContext: aws.String("Data"),
}
_, err = d.svc.RespondDecisionTaskCompleted(params)
return err // which may be nil
}
// scheduleNextaActivity will start the next activity
func (d *decision) scheduleNextaActivity(tt string, name string, version string, input string, stcTimeout string, tasklist string, context string) error {
id := name + time.Now().Format("200601021504")
Info.Printf("Scheduling eventType: %s\n", name)
params := &swf.RespondDecisionTaskCompletedInput{
TaskToken: aws.String(tt),
Decisions: []*swf.Decision{
{
DecisionType: aws.String("ScheduleActivityTask"), //
ScheduleActivityTaskDecisionAttributes: &swf.ScheduleActivityTaskDecisionAttributes{
ActivityId: aws.String(id),
ActivityType: &swf.ActivityType{
Name: aws.String(name),
Version: aws.String(version),
},
Input: aws.String(input),
StartToCloseTimeout: aws.String(stcTimeout),
TaskList: &swf.TaskList{
Name: aws.String(tasklist),
},
},
},
},
ExecutionContext: aws.String(context),
}
_, err := d.svc.RespondDecisionTaskCompleted(params)
return err
}
func (d *decision) getJSON(input string) (map[string]interface{}, error) {
var data interface{}
err := json.Unmarshal([]byte(input), &data)
if err != nil {
return nil, err
}
m := data.(map[string]interface{})
return m, err
}
//======================================= handle routines ==================================================
// handleLoadBigQueryComplete gets result JSON and starts loadcompleted using the supplierid as the tasklist
func (d *decision) handlePostorderComplete(jsonstr string) error {
var rslt result
err := json.Unmarshal([]byte(jsonstr), &rslt)
if err != nil {
return err
}
err = d.scheduleNextaActivity(d.tt, "loadcompleted", "2", rslt.File, "10000", rslt.SupplierID, "")
return err
}
func (d *decision) handleWorkflowStart(event *swf.HistoryEvent) error {
wfInput := *event.WorkflowExecutionStartedEventAttributes.Input
json, err := d.getJSON(wfInput)
if err != nil {
return err
}
supplierid, _ := json["SupplierID"].(string)
err = d.scheduleNextaActivity(d.tt, "postorder", "1", wfInput, "10000", supplierid, "")
return err
}