-
Notifications
You must be signed in to change notification settings - Fork 4
/
worker_manager.go
303 lines (266 loc) · 8.27 KB
/
worker_manager.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
package gocelery
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
log "github.com/Sirupsen/logrus"
"github.com/go-errors/errors"
"github.com/taoh/gocelery/broker"
"github.com/taoh/gocelery/serializer"
)
// WorkerManager starts and stop worker jobs
type workerManager struct {
sync.Mutex
brokerURL string
broker broker.Broker
ticker *time.Ticker // ticker for heartbeat
taskExecuted uint64
}
// Connect to broker. Returns an error if connection fails.
func (manager *workerManager) Connect() error {
broker, err := broker.NewBroker(manager.brokerURL)
if err != nil {
log.Fatal("Failed to connect to broker: ", err)
return err
}
log.Debug("Connected to broker: ", manager.brokerURL)
manager.broker = broker
return nil
}
func merge(done <-chan bool, cs ...<-chan *broker.Message) <-chan *broker.Message {
var wg sync.WaitGroup
out := make(chan *broker.Message)
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed, then calls wg.Done.
output := func(c <-chan *broker.Message) {
for n := range c {
select {
case out <- n:
case <-done:
}
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
// Start a goroutine to close out once all the output goroutines are
// done. This must start after the wg.Add call.
go func() {
wg.Wait()
close(out)
}()
return out
}
// Start worker runs the worker command
func (manager *workerManager) Start(queues []string) {
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs // listen to signals
manager.Stop()
manager.Close()
log.Info("gocelery stopped.")
done <- true // send signals to done
}()
log.Debug("Worker is now running")
// now loops to wait for messages
manager.sendWorkerEvent(WorkerOnline)
// start hearbeat
manager.startHeartbeat()
// start getting tasks
taskChannels := make([]<-chan *broker.Message, 3)
for _, queue := range queues {
taskChannel := manager.broker.GetTasks(queue)
taskChannels = append(taskChannels, taskChannel)
}
ch := merge(done, taskChannels...)
for {
select {
case <-done:
log.Debug("Received done signal")
return
case message := <-ch:
log.Debug("Message type: ", message.ContentType, " body:", string(message.Body))
go func(message *broker.Message) {
serializer, err := serializer.NewSerializer(message.ContentType)
// convert message body to task
if err == nil {
var task Task
err = serializer.Deserialize(message.Body, &task)
if err == nil {
task.ContentType = message.ContentType // stores the content type for the task
// publish task received event
taskEventPayload, _ := serializer.Serialize(NewTaskReceivedEvent(&task))
manager.broker.PublishTaskEvent(strings.Replace(TaskReceived.RoutingKey(), "-", ".", -1),
&broker.Message{
Timestamp: time.Now(),
ContentType: message.ContentType,
Body: taskEventPayload,
})
log.Debug("Processing task: ", task.Task, " ID:", task.ID)
// check eta
duration := time.Duration(0)
if !task.Eta.IsZero() {
duration = task.Eta.Sub(time.Now().UTC())
}
if duration > 0 {
timer := time.NewTimer(duration) // wait until ready
go func() {
<-timer.C
manager.runTask(&task)
}()
} else {
// execute the task in a worker immediately
manager.runTask(&task)
}
}
} else {
// send errors to server
log.Error("Cannot deserialize message:", err)
}
}(message)
}
}
}
// PublishTask sends a task to task queue as a client
func (manager *workerManager) PublishTask(queueName string, task *Task, ignoreResult bool) (*Task, error) {
res, err := json.Marshal(task)
if err != nil {
return nil, err
}
message := &broker.Message{
Timestamp: time.Now(),
ContentType: JSON,
Body: res,
}
manager.broker.PublishTask(queueName, task.ID, message, ignoreResult)
// return the task object
return task, nil
}
// GetTaskResult listens to celery and returns the task result for given task
func (manager *workerManager) GetTaskResult(task *Task) chan *TaskResult {
ch := manager.broker.GetTaskResult(task.ID)
tc := make(chan *TaskResult)
go func() {
// listen to queue
message := <-ch
serializer, _ := serializer.NewSerializer(message.ContentType)
// convert message body to task
var taskResult TaskResult
if message.Body != nil {
serializer.Deserialize(message.Body, &taskResult)
} else {
log.Errorf("Task result message is nil")
}
tc <- &taskResult
}()
return tc
}
func (manager *workerManager) startHeartbeat() {
ticker := time.NewTicker(time.Second * 2)
manager.ticker = ticker
go func() {
for _ = range ticker.C {
// log.Debug("Sent heartbeat at: ", t)
// send heartbeat
manager.sendWorkerEvent(WorkerHeartbeat)
}
}()
}
func (manager *workerManager) sendTaskEvent(eventType EventType, payload []byte) {
manager.broker.PublishTaskEvent(strings.Replace(eventType.RoutingKey(), "-", ".", -1),
&broker.Message{Timestamp: time.Now(), ContentType: JSON, Body: payload})
}
// Send Worker Events
func (manager *workerManager) sendWorkerEvent(eventType EventType) {
workerEventPayload, _ := json.Marshal(NewWorkerEvent(eventType))
manager.broker.PublishTaskEvent(strings.Replace(eventType.RoutingKey(), "-", ".", -1),
&broker.Message{Timestamp: time.Now(), ContentType: JSON, Body: workerEventPayload})
}
func (manager *workerManager) stopHeartbeat() {
if manager.ticker != nil {
manager.ticker.Stop()
}
}
// Stop the worker
func (manager *workerManager) Stop() {
manager.stopHeartbeat()
manager.sendWorkerEvent(WorkerOffline)
}
// Close the worker
func (manager *workerManager) Close() {
manager.broker.Close()
}
func (manager *workerManager) runTask(task *Task) (*TaskResult, error) {
// create task result
taskResult := &TaskResult{
ID: task.ID,
Status: Started,
}
taskEventType := None
serializer, _ := serializer.NewSerializer(task.ContentType)
var taskError error
var taskEventPayload []byte
if worker, ok := workerRegistery[task.Task]; ok {
log.Debug("Working on task: ", task.Task)
taskEventPayload, _ = serializer.Serialize(NewTaskStartedEvent(task))
taskEventType = TaskStarted
manager.sendTaskEvent(TaskStarted, taskEventPayload)
// check expiration
if !task.Expires.IsZero() && task.Expires.Before(time.Now().UTC()) {
// time expired, make the task Revoked
log.Warn("Task has expired", task.Expires)
taskResult.Status = Revoked
taskError = errors.New("Task has expired")
taskEventPayload, _ = serializer.Serialize(NewTaskFailedEvent(task, taskResult, taskError))
taskEventType = TaskRevoked
} else {
start := time.Now()
result, err := worker.Execute(task)
elapsed := time.Since(start)
manager.Lock()
manager.taskExecuted = manager.taskExecuted + 1
log.Infof("Executed task [%s] [%s] [%s] in %f seconds", task.Task, task.ID, result, elapsed.Seconds())
manager.Unlock()
if err != nil {
log.Errorf("Failed to execute task [%s]: %s", task.Task, err)
err = errors.Wrap(err, 1)
}
if err != nil {
taskError = err
taskResult.Status = Failure
taskResult.TraceBack = err.(*errors.Error).ErrorStack()
taskEventPayload, _ = serializer.Serialize(NewTaskFailedEvent(task, taskResult, err))
taskEventType = TaskFailed
} else {
taskResult.Status = Success
taskResult.Result = result
taskEventPayload, _ = serializer.Serialize(NewTaskSucceedEvent(task, taskResult, elapsed))
taskEventType = TaskSucceeded
}
}
} else {
taskErrorMessage := fmt.Sprintf("Worker for task [%s] not found", task.Task)
taskError = errors.New(taskErrorMessage)
taskResult.Status = Failure
taskResult.TraceBack = taskError.(*errors.Error).ErrorStack()
taskEventPayload, _ = serializer.Serialize(NewTaskFailedEvent(task, taskResult, taskError))
taskEventType = TaskFailed
}
res, _ := serializer.Serialize(taskResult)
//key := strings.Replace(task.ID, "-", "", -1)
manager.broker.PublishTaskResult(task.ID, &broker.Message{Timestamp: time.Now(), ContentType: task.ContentType, Body: res})
// send task completed event
if taskEventType != None {
manager.sendTaskEvent(taskEventType, taskEventPayload)
}
return taskResult, nil
}