forked from gocelery/gocelery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
159 lines (141 loc) · 3.88 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
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
package gocelery
import (
"fmt"
"log"
"reflect"
"sync"
)
// CeleryWorker represents distributed task worker
type CeleryWorker struct {
broker CeleryBroker
backend CeleryBackend
numWorkers int
registeredTasks map[string]interface{}
taskLock sync.RWMutex
stopChannel chan struct{}
workWG sync.WaitGroup
}
// NewCeleryWorker returns new celery worker
func NewCeleryWorker(broker CeleryBroker, backend CeleryBackend, numWorkers int) *CeleryWorker {
return &CeleryWorker{
broker: broker,
backend: backend,
numWorkers: numWorkers,
registeredTasks: make(map[string]interface{}),
}
}
// StartWorker starts celery worker
func (w *CeleryWorker) StartWorker() {
w.stopChannel = make(chan struct{}, 1)
w.workWG.Add(w.numWorkers)
for i := 0; i < w.numWorkers; i++ {
go func(workerID int) {
defer w.workWG.Done()
for {
select {
case <-w.stopChannel:
return
default:
// process messages
taskMessage, err := w.broker.GetTask()
if err != nil || taskMessage == nil {
continue
}
log.Printf("WORKER %d task message received: %v\n", workerID, taskMessage)
// run task
resultMsg, err := w.RunTask(taskMessage)
if err != nil {
log.Printf("run error: %v", err)
continue
}
defer releaseResultMessage(resultMsg)
// push result to backend
err = w.backend.SetResult(taskMessage.Id, resultMsg)
if err != nil {
log.Printf("set result error: %v", err)
continue
}
}
}
}(i)
}
}
// StopWorker stops celery workers
func (w *CeleryWorker) StopWorker() {
for i := 0; i < w.numWorkers; i++ {
w.stopChannel <- struct{}{}
}
w.workWG.Wait()
}
// GetNumWorkers returns number of currently running workers
func (w *CeleryWorker) GetNumWorkers() int {
return w.numWorkers
}
// Register registers tasks (functions)
func (w *CeleryWorker) Register(name string, task interface{}) {
w.taskLock.Lock()
w.registeredTasks[name] = task
w.taskLock.Unlock()
}
// GetTask retrieves registered task
func (w *CeleryWorker) GetTask(name string) interface{} {
w.taskLock.RLock()
task, ok := w.registeredTasks[name]
if !ok {
w.taskLock.RUnlock()
return nil
}
w.taskLock.RUnlock()
return task
}
// RunTask runs celery task
func (w *CeleryWorker) RunTask(message *CeleryTask) (*ResultMessage, error) {
// get task
task := w.GetTask(message.Task)
if task == nil {
return nil, fmt.Errorf("task %s is not registered", message.Task)
}
// convert to task interface
taskInterface, ok := task.(Itf_CeleryTask)
if ok {
if err := taskInterface.ParseKwargs(message.Kwargs); err != nil {
return nil, err
}
val, err := taskInterface.RunTask()
if err != nil {
return nil, err
}
return getResultMessage(val), err
}
// log.Println("using reflection")
// use reflection to execute function ptr
taskFunc := reflect.ValueOf(task)
return runTaskFunc(&taskFunc, message)
}
func runTaskFunc(taskFunc *reflect.Value, message *CeleryTask) (*ResultMessage, error) {
// check number of arguments
numArgs := taskFunc.Type().NumIn()
messageNumArgs := len(message.Args)
if numArgs != messageNumArgs {
return nil, fmt.Errorf("Number of task arguments %d does not match number of message arguments %d", numArgs, messageNumArgs)
}
// construct arguments
in := make([]reflect.Value, messageNumArgs)
for i, arg := range message.Args {
origType := taskFunc.Type().In(i).Kind()
msgType := reflect.TypeOf(arg).Kind()
// special case - convert float64 to int if applicable
// this is due to json limitation where all numbers are converted to float64
if origType == reflect.Int && msgType == reflect.Float64 {
arg = int(arg.(float64))
}
in[i] = reflect.ValueOf(arg)
}
// call method
res := taskFunc.Call(in)
if len(res) == 0 {
return nil, nil
}
// defer releaseResultMessage(resultMessage)
return getReflectionResultMessage(&res[0]), nil
}