-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
328 lines (274 loc) · 6.76 KB
/
runner.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
/*
Copyright 2024 Go-Flow Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package flow
import (
"context"
"errors"
"fmt"
"sync"
"time"
)
func NewRunner(f *Flow) *Runner {
return &Runner{Flow: f}
}
type Runner struct {
*Flow
flowCtx context.Context
cancelFlow context.CancelFunc
shotCtx context.Context
cancelShot context.CancelFunc
fsm *FSM
stopCh chan struct{}
started bool
mux sync.Mutex
}
func (r *Runner) Start(ctx context.Context) (err error) {
if IsFinishedStatus(r.Status) {
return
}
r.flowCtx, r.cancelFlow = context.WithCancel(ctx)
if err = r.executor.Setup(ctx); err != nil {
r.SetStatus(ErrorStatus, err.Error())
return err
}
r.fsm = buildFlowFSM(r)
r.stopCh = make(chan struct{})
if !r.waitingForRunning(ctx) {
return
}
if err = r.pushEvent2FlowFSM(statusEvent{Type: TriggerEvent}); err != nil {
r.SetStatus(ErrorStatus, err.Error())
return err
}
// waiting all task down
<-r.stopCh
return r.executor.Teardown(ctx)
}
func (r *Runner) Pause() error {
if r.Status == RunningStatus {
return r.pushEvent2FlowFSM(statusEvent{Type: ExecutePauseEvent})
}
return fmt.Errorf("current status is %s", r.Status)
}
func (r *Runner) Resume() error {
if r.Status == PausedStatus {
return r.pushEvent2FlowFSM(statusEvent{Type: ExecuteResumeEvent})
}
return fmt.Errorf("current status is %s", r.Status)
}
func (r *Runner) Cancel() error {
if IsFinishedStatus(r.Status) {
return nil
}
return r.pushEvent2FlowFSM(statusEvent{Type: ExecuteCancelEvent})
}
func (r *Runner) handleJobRun(event statusEvent) error {
r.mux.Lock()
defer r.mux.Unlock()
if r.started {
return nil
}
r.started = true
r.SetStatus(RunningStatus, event.Message)
go func() {
defer func() { r.started = false }()
r.triggerFlow()
}()
return nil
}
func (r *Runner) triggerFlow() {
var (
isFinish bool
err error
)
shotCtx, cancelShot := context.WithCancel(r.flowCtx)
defer cancelShot()
r.shotCtx = shotCtx
r.cancelShot = cancelShot
for {
select {
case <-r.flowCtx.Done():
err = r.flowCtx.Err()
default:
}
switch r.Status {
case RunningStatus:
case PausingStatus:
_ = r.pushEvent2FlowFSM(statusEvent{Type: ExecutePausedEvent, Message: ""})
return
default:
return
}
isFinish, err = r.runNextBatchTask(r.shotCtx)
if err != nil {
if errors.Is(err, context.Canceled) {
return
}
_ = r.pushEvent2FlowFSM(statusEvent{Type: ExecuteErrorEvent, Message: err.Error()})
return
}
if isFinish {
if !IsFinishedStatus(r.Status) {
_ = r.pushEvent2FlowFSM(statusEvent{Type: ExecuteFinishEvent, Message: "finish"})
}
return
}
}
}
func (r *Runner) handleJobPause(event statusEvent) error {
r.SetStatus(PausingStatus, event.Message)
if r.cancelShot != nil {
r.cancelShot()
}
return nil
}
func (r *Runner) handleJobPaused(event statusEvent) error {
r.SetStatus(PausedStatus, event.Message)
return nil
}
func (r *Runner) handleJobSucceed(event statusEvent) error {
r.SetStatus(SucceedStatus, event.Message)
r.close()
return nil
}
func (r *Runner) handleJobFailed(event statusEvent) error {
r.SetStatus(FailedStatus, event.Message)
r.close()
return nil
}
func (r *Runner) handleJobCancel(event statusEvent) error {
r.SetStatus(CanceledStatus, event.Message)
r.close()
return nil
}
func (r *Runner) runNextBatchTask(ctx context.Context) (finish bool, err error) {
defer func() {
if panicErr := doRecover(); panicErr != nil {
err = panicErr
}
}()
var batch []Task
batch, err = r.coordinator.NextBatch(ctx)
if err != nil {
return
}
if len(batch) == 0 {
return true, nil
}
wg := sync.WaitGroup{}
for i := range batch {
wg.Add(1)
go func(t Task) {
defer wg.Done()
r.taskRun(ctx, t)
}(batch[i])
}
wg.Wait()
return false, nil
}
func (r *Runner) taskRun(ctx context.Context, task Task) {
if r.Status != RunningStatus {
return
}
r.SetTaskStatue(task, RunningStatus, "")
err := r.executor.Exec(ctx, r.Flow, task)
if err != nil {
r.handleTaskFail(ctx, task, err)
return
}
r.SetTaskStatue(task, SucceedStatus, "")
return
}
func (r *Runner) handleTaskFail(ctx context.Context, task Task, err error) {
msg := fmt.Sprintf("task %s failed: %s", task.GetName(), err)
op := r.coordinator.HandleFail(task, err)
switch op {
case FailAndInterrupt:
r.SetTaskStatue(task, FailedStatus, msg)
_ = r.pushEvent2FlowFSM(statusEvent{Type: ExecuteFailedEvent, Message: msg})
case FailAndPause:
r.SetTaskStatue(task, PausedStatus, msg)
_ = r.pushEvent2FlowFSM(statusEvent{Type: ExecutePauseEvent, Message: msg})
case FailButContinue:
r.SetTaskStatue(task, FailedStatus, msg)
default:
r.SetTaskStatue(task, FailedStatus, msg)
_ = r.pushEvent2FlowFSM(statusEvent{Type: ExecuteFailedEvent, Message: msg})
}
}
func (r *Runner) waitingForRunning(ctx context.Context) bool {
for {
select {
case <-ctx.Done():
return false
default:
switch r.Status {
case SucceedStatus, FailedStatus, CanceledStatus, ErrorStatus:
return false
case InitializingStatus, RunningStatus:
return true
default:
time.Sleep(time.Second * 15)
}
}
}
}
func (r *Runner) close() {
if r.cancelFlow != nil {
r.cancelFlow()
}
close(r.stopCh)
}
func (r *Runner) pushEvent2FlowFSM(event statusEvent) error {
err := r.fsm.Event(event)
if err != nil {
return err
}
return nil
}
func buildFlowFSM(r *Runner) *FSM {
m := NewFSM(r.Status)
m.From([]string{InitializingStatus, RunningStatus}).
To(RunningStatus).
When(TriggerEvent).
Do(r.handleJobRun)
m.From([]string{RunningStatus}).
To(SucceedStatus).
When(ExecuteFinishEvent).
Do(r.handleJobSucceed)
m.From([]string{InitializingStatus, RunningStatus}).
To(ErrorStatus).
When(ExecuteErrorEvent).
Do(r.handleJobFailed)
m.From([]string{InitializingStatus, RunningStatus}).
To(FailedStatus).
When(ExecuteFailedEvent).
Do(r.handleJobFailed)
m.From([]string{InitializingStatus, RunningStatus, PausedStatus}).
To(CanceledStatus).
When(ExecuteCancelEvent).
Do(r.handleJobCancel)
m.From([]string{RunningStatus}).
To(PausingStatus).
When(ExecutePauseEvent).
Do(r.handleJobPause)
m.From([]string{PausingStatus}).
To(PausedStatus).
When(ExecutePausedEvent).
Do(r.handleJobPaused)
m.From([]string{PausedStatus}).
To(RunningStatus).
When(ExecuteResumeEvent).
Do(r.handleJobRun)
return m
}