-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlooper.go
439 lines (348 loc) · 7.73 KB
/
looper.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
package looper
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"time"
)
// Panic handler
type PanicHandlerFunc func(jobName string, recoverData interface{})
var (
panicHandler PanicHandlerFunc
panicHandlerMutex = sync.RWMutex{}
)
func SetPanicHandler(handler PanicHandlerFunc) {
panicHandlerMutex.Lock()
defer panicHandlerMutex.Unlock()
panicHandler = handler
}
// Looper
type Looper struct {
running bool
jobs []*Job
startupTime time.Duration
hooks hooks
mu sync.RWMutex
locker locker
}
type (
HookBeforeJob func(jobName string)
HookAfterJob func(jobName string, duration time.Duration)
HookAfterJobError func(jobName string, duration time.Duration, err error)
)
type hooks struct {
beforeJob HookBeforeJob
afterJob HookAfterJob
afterJobError HookAfterJobError
}
type Config struct {
// Startup time ensuring a consistent delay between registered jobs on start of looper.
//
// StartupTime = 1 second; 5 registered jobs; Jobs would be initiated
// with 200ms delay
StartupTime time.Duration
Locker locker
}
type JobFn func(ctx context.Context) error
type Job struct {
// Job function which get triggered by looper.
JobFn JobFn
// Name of the job.
Name string
// Timeout for job, maximum time, the job can run, after timeout the job get killed.
Timeout time.Duration
// Wait duration before next job execution after successful execution of previous job.
WaitAfterSuccess time.Duration
// Wait duration before next job execution after unsuccessful execution of previous job.
WaitAfterError time.Duration
// If job is Active, and can be started.
Active bool
// If job is started.
Started bool
// If job is currently running.
Running bool
// Last time the job ran.
LastRun time.Time
// Count of successful job runs.
RunCountSuccess uint64
// Count of unsuccessful job runs.
RunCountError uint64
// Copy of last error, that occured.
LastError error
// Hook function before job runs.
BeforeJob HookBeforeJob
// Hook function after job runs successfully.
AfterJob HookAfterJob
// Hook function after job runs unsuccessfully.
AfterJobError HookAfterJobError
// If the job should use locker
WithLocker bool
// Locker
locker locker
// Context cancel
contextCancel context.CancelFunc
mu sync.RWMutex
}
func New(config Config) *Looper {
l := &Looper{
jobs: []*Job{},
startupTime: setDefaultDuration(config.StartupTime, time.Second),
hooks: hooks{
beforeJob: func(jobName string) {},
afterJob: func(jobName string, duration time.Duration) {},
afterJobError: func(jobName string, duration time.Duration, err error) {},
},
locker: newNopLocker(),
}
if config.Locker != nil {
l.locker = config.Locker
}
return l
}
func (l *Looper) RegisterHooks(
beforeJob HookBeforeJob,
afterJob HookAfterJob,
afterJobError HookAfterJobError,
) {
l.hooks.beforeJob = beforeJob
l.hooks.afterJobError = afterJobError
l.hooks.afterJob = afterJob
}
func (l *Looper) AddJob(ctx context.Context, jobInput *Job) (err error) {
if jobInput == nil {
return nil
}
l.mu.Lock()
defer l.mu.Unlock()
beforeJob := jobInput.BeforeJob
if beforeJob == nil {
beforeJob = l.hooks.beforeJob
}
afterJob := jobInput.AfterJob
if afterJob == nil {
afterJob = l.hooks.afterJob
}
afterJobError := jobInput.AfterJobError
if afterJobError == nil {
afterJobError = l.hooks.afterJobError
}
j := &Job{
JobFn: jobInput.JobFn,
Name: l.uniqueName(jobInput.Name),
Timeout: setDefaultDuration(jobInput.Timeout, time.Minute),
WaitAfterSuccess: setDefaultDuration(jobInput.WaitAfterSuccess, time.Second),
WaitAfterError: setDefaultDuration(jobInput.WaitAfterError, time.Second),
Active: jobInput.Active,
BeforeJob: beforeJob,
AfterJob: afterJob,
AfterJobError: afterJobError,
WithLocker: jobInput.WithLocker,
locker: l.locker,
mu: sync.RWMutex{},
}
l.jobs = append(l.jobs, j)
return nil
}
func setDefaultDuration(duration time.Duration, defaultDuration time.Duration) time.Duration {
if duration == time.Duration(0) {
return defaultDuration
}
return duration
}
func (l *Looper) uniqueName(jobInputName string) string {
var counter int
for _, j := range l.jobs {
parts := strings.Split(j.Name, "-")
jobName := strings.Join(parts[:len(parts)-1], "-")
if jobName == jobInputName {
counter++
}
}
return fmt.Sprintf("%s-%v", jobInputName, counter)
}
func (l *Looper) StartJobByName(jobName string) error {
l.mu.RLock()
defer l.mu.RUnlock()
var found bool
for _, j := range l.jobs {
j.mu.Lock()
parts := strings.Split(j.Name, "-")
name := strings.Join(parts[:len(parts)-1], "-")
if name == jobName {
found = true
if j.Active && !j.Started {
j.Started = true
go j.startLoop()
}
}
j.mu.Unlock()
if found {
break
}
}
if !found {
return fmt.Errorf("job with name(%s) not found", jobName)
}
return nil
}
func (l *Looper) Start() {
l.mu.Lock()
defer l.mu.Unlock()
if !l.running {
go l.startJobs()
l.running = true
}
}
func (l *Looper) startJobs() {
if len(l.jobs) == 0 {
return
}
delay := time.Duration(l.startupTime) / time.Duration(len(l.jobs))
for _, j := range l.jobs {
j.mu.Lock()
if j.Active && !j.Started {
j.Started = true
go j.startLoop()
time.Sleep(delay)
}
j.mu.Unlock()
}
}
func (l *Looper) Stop() {
l.mu.Lock()
for _, j := range l.jobs {
j.mu.Lock()
j.Started = false
if j.contextCancel != nil {
j.contextCancel()
}
j.mu.Unlock()
}
l.mu.Unlock()
for {
rj := l.runningJobs()
if rj == 0 {
break
}
time.Sleep(time.Millisecond * 200)
}
l.mu.Lock()
l.running = false
l.mu.Unlock()
}
func (j *Job) startLoop() {
defer func() {
j.mu.Lock()
j.Started = false
j.contextCancel = nil
j.mu.Unlock()
}()
for {
j.mu.RLock()
if !j.Active || !j.Started {
j.mu.RUnlock()
break
}
j.mu.RUnlock()
start := time.Now()
j.BeforeJob(j.Name)
err := j.start()
if err != nil {
j.AfterJobError(j.Name, time.Since(start), err)
time.Sleep(j.WaitAfterError)
} else {
j.AfterJob(j.Name, time.Since(start))
time.Sleep(j.WaitAfterSuccess)
}
}
}
func (j *Job) start() error {
defer func() {
j.mu.Lock()
j.Running = false
j.mu.Unlock()
}()
j.mu.Lock()
j.Running = true
j.mu.Unlock()
lo, err := j.lock()
if err != nil {
if errors.Is(err, ErrFailedToObtainLock) {
time.Sleep(time.Second)
return nil
}
return err
}
ctx, cancel := context.WithTimeout(context.Background(), j.Timeout)
defer cancel()
j.contextCancel = cancel
err = j.run(ctx)
if err != nil {
errLock := j.unlock(lo)
if errLock != nil {
return errors.Join(err, errLock)
}
return err
}
err = j.unlock(lo)
if err != nil {
return err
}
return nil
}
func (j *Job) lock() (lo lock, err error) {
if j.WithLocker {
lo, err = j.locker.lock(context.Background(), j.Name, j.Timeout)
}
return lo, err
}
func (j *Job) unlock(lo lock) (err error) {
if j.WithLocker {
return lo.unlock(context.Background())
}
return nil
}
func (j *Job) run(ctx context.Context) (err error) {
defer func() {
j.mu.Lock()
defer j.mu.Unlock()
j.LastRun = time.Now()
r := recover()
if r != nil {
recErr, ok := r.(error)
if ok {
err = recErr
} else {
err = fmt.Errorf("%v", r)
}
if panicHandler != nil {
panicHandler(j.Name, r)
}
}
if err != nil {
j.RunCountError++
j.LastError = err
} else {
j.RunCountSuccess++
}
}()
err = j.JobFn(ctx)
return err
}
func (l *Looper) runningJobs() (count int) {
l.mu.Lock()
defer l.mu.Unlock()
for _, j := range l.jobs {
j.mu.RLock()
if j.Running {
count++
}
j.mu.RUnlock()
}
return count
}
func (l *Looper) Jobs() []*Job {
return l.jobs
}