-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworker.go
82 lines (77 loc) · 1.75 KB
/
worker.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
package taskmanager
import (
"context"
"errors"
"runtime/debug"
"time"
)
type worker struct {
id int32
task chan Task
taskQueue chan chan Task
context context.Context
currTask Task
mgr *TaskManager
logger Logger
}
func newWorker(id int32, m *TaskManager, log Logger) *worker {
return &worker{
id: id,
task: make(chan Task),
taskQueue: m.taskQueue,
context: m.context,
mgr: m,
logger: log,
}
}
func (w *worker) start() {
w.task = make(chan Task)
timedOut := false
go func() {
defer func() {
if r := recover(); r != nil {
w.logger.Errorf("PANIC in TaskManager worker")
debug.PrintStack()
w.logger.Errorf("recovered in worker %d", w.id)
if w.currTask != nil {
w.mgr.handleError(w.id, w.currTask, errors.New("Panic"))
}
}
if !timedOut {
close(w.task)
w.mgr.handleWorkerStop(w)
}
}()
for {
select {
case <-w.context.Done():
w.logger.Infof("worker %d : stopping", w.id)
return
case w.taskQueue <- w.task:
}
select {
case task := <-w.task:
w.logger.Infof("worker %d : Received work request", w.id)
w.mgr.handleStart(w.id, task.Name())
w.currTask = task
err := task.Execute(w.context)
if err != nil {
w.logger.Errorf("worker %d : Failed with error : %s", w.id, err.Error())
w.mgr.handleError(w.id, task, err)
} else {
w.logger.Infof("worker %d : Task finished successfully", w.id)
w.mgr.handleSuccess(w.id, task)
}
case <-w.context.Done():
w.logger.Infof("worker %d : stopping", w.id)
return
case <-time.After(w.mgr.workerTimeout):
w.logger.Infof("worker %d : idle timeout", w.id)
timedOut = true
close(w.task)
w.mgr.handleWorkerTimeout(w)
return
}
}
}()
}