forked from RichardKnop/machinery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
amqp.go
388 lines (329 loc) · 10.9 KB
/
amqp.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
package backends
// NOTE: Using AMQP as a result backend is quite tricky since every time we
// read a message from the queue keeping task states, the message is removed
// from the queue. This leads to problems with keeping a reliable state of a
// group of tasks since concurrent processes updating the group state cause
// race conditions and inconsistent state.
//
// This is avoided by a "clever" hack. A special queue identified by a group
// UUID is created and we store serialised TaskState objects of successfully
// completed tasks. By inspecting the queue we can then say:
// 1) If all group tasks finished (number of unacked messages = group task count)
// 2) If all group tasks finished AND succeeded (by consuming the queue)
//
// It is important to consume the queue exclusively to avoid race conditions.
import (
"encoding/json"
"errors"
"fmt"
"github.com/RichardKnop/machinery/v1/common"
"github.com/RichardKnop/machinery/v1/config"
"github.com/RichardKnop/machinery/v1/log"
"github.com/RichardKnop/machinery/v1/tasks"
"github.com/streadway/amqp"
)
// AMQPBackend represents an AMQP result backend
type AMQPBackend struct {
cnf *config.Config
common.AMQPConnector
}
// NewAMQPBackend creates AMQPBackend instance
func NewAMQPBackend(cnf *config.Config) Interface {
return &AMQPBackend{cnf: cnf, AMQPConnector: common.AMQPConnector{}}
}
// InitGroup creates and saves a group meta data object
func (b *AMQPBackend) InitGroup(groupUUID string, taskUUIDs []string) error {
return nil
}
// GroupCompleted returns true if all tasks in a group finished
// NOTE: Given AMQP limitation this will only return true if all finished
// tasks were successful as we do not keep track of completed failed tasks
func (b *AMQPBackend) GroupCompleted(groupUUID string, groupTaskCount int) (bool, error) {
conn, channel, err := b.Open(b.cnf.Broker, b.cnf.TLSConfig)
if err != nil {
return false, err
}
defer b.Close(channel, conn)
queueState, err := b.InspectQueue(channel, groupUUID)
if err != nil {
return false, nil
}
return queueState.Messages == groupTaskCount, nil
}
// GroupTaskStates returns states of all tasks in the group
func (b *AMQPBackend) GroupTaskStates(groupUUID string, groupTaskCount int) ([]*tasks.TaskState, error) {
conn, channel, err := b.Open(b.cnf.Broker, b.cnf.TLSConfig)
if err != nil {
return nil, err
}
defer b.Close(channel, conn)
queueState, err := b.InspectQueue(channel, groupUUID)
if err != nil {
return nil, err
}
if queueState.Messages != groupTaskCount {
return nil, fmt.Errorf("Already consumed: %v", err)
}
deliveries, err := channel.Consume(
groupUUID, // queue name
"", // consumer tag
false, // auto-ack
true, // exclusive
false, // no-local
false, // no-wait
nil, // arguments
)
if err != nil {
return nil, fmt.Errorf("Queue consume error: %s", err)
}
states := make([]*tasks.TaskState, groupTaskCount)
for i := 0; i < groupTaskCount; i++ {
d := <-deliveries
state := new(tasks.TaskState)
if err := json.Unmarshal([]byte(d.Body), state); err != nil {
d.Nack(false, false) // multiple, requeue
return nil, err
}
d.Ack(false) // multiple
states[i] = state
}
return states, nil
}
// TriggerChord flags chord as triggered in the backend storage to make sure
// chord is never trigerred multiple times. Returns a boolean flag to indicate
// whether the worker should trigger chord (true) or no if it has been triggered
// already (false)
func (b *AMQPBackend) TriggerChord(groupUUID string) (bool, error) {
conn, channel, err := b.Open(b.cnf.Broker, b.cnf.TLSConfig)
if err != nil {
return false, err
}
defer b.Close(channel, conn)
_, err = b.InspectQueue(channel, amqmChordTriggeredQueue(groupUUID))
if err != nil {
return true, nil
}
return false, nil
}
// SetStatePending updates task state to PENDING
func (b *AMQPBackend) SetStatePending(signature *tasks.Signature) error {
taskState := tasks.NewPendingTaskState(signature)
return b.updateState(taskState)
}
// SetStateReceived updates task state to RECEIVED
func (b *AMQPBackend) SetStateReceived(signature *tasks.Signature) error {
taskState := tasks.NewReceivedTaskState(signature)
return b.updateState(taskState)
}
// SetStateStarted updates task state to STARTED
func (b *AMQPBackend) SetStateStarted(signature *tasks.Signature) error {
taskState := tasks.NewStartedTaskState(signature)
return b.updateState(taskState)
}
// SetStateRetry updates task state to RETRY
func (b *AMQPBackend) SetStateRetry(signature *tasks.Signature) error {
state := tasks.NewRetryTaskState(signature)
return b.updateState(state)
}
// SetStateSuccess updates task state to SUCCESS
func (b *AMQPBackend) SetStateSuccess(signature *tasks.Signature, results []*tasks.TaskResult) error {
taskState := tasks.NewSuccessTaskState(signature, results)
if err := b.updateState(taskState); err != nil {
return err
}
if signature.GroupUUID == "" {
return nil
}
return b.markTaskCompleted(signature, taskState)
}
// SetStateFailure updates task state to FAILURE
func (b *AMQPBackend) SetStateFailure(signature *tasks.Signature, err string) error {
taskState := tasks.NewFailureTaskState(signature, err)
if err := b.updateState(taskState); err != nil {
return err
}
if signature.GroupUUID == "" {
return nil
}
return b.markTaskCompleted(signature, taskState)
}
// GetState returns the latest task state. It will only return the status once
// as the message will get consumed and removed from the queue.
func (b *AMQPBackend) GetState(taskUUID string) (*tasks.TaskState, error) {
declareQueueArgs := amqp.Table{
// Time in milliseconds
// after that message will expire
"x-message-ttl": int32(b.getExpiresIn()),
// Time after that the queue will be deleted.
"x-expires": int32(b.getExpiresIn()),
}
conn, channel, _, _, _, err := b.Connect(
b.cnf.Broker,
b.cnf.TLSConfig,
b.cnf.AMQP.Exchange, // exchange name
b.cnf.AMQP.ExchangeType, // exchange type
taskUUID, // queue name
false, // queue durable
true, // queue delete when unused
taskUUID, // queue binding key
nil, // exchange declare args
declareQueueArgs, // queue declare args
nil, // queue binding args
)
if err != nil {
return nil, err
}
defer b.Close(channel, conn)
d, ok, err := channel.Get(
taskUUID, // queue name
false, // multiple
)
if err != nil {
return nil, err
}
if !ok {
return nil, errors.New("No state ready")
}
d.Ack(false)
state := new(tasks.TaskState)
if err := json.Unmarshal([]byte(d.Body), state); err != nil {
log.ERROR.Printf("Failed to unmarshal task state: %s", string(d.Body))
log.ERROR.Print(err)
return nil, err
}
return state, nil
}
// PurgeState deletes stored task state
func (b *AMQPBackend) PurgeState(taskUUID string) error {
conn, channel, err := b.Open(b.cnf.Broker, b.cnf.TLSConfig)
if err != nil {
return err
}
defer b.Close(channel, conn)
return b.DeleteQueue(channel, taskUUID)
}
// PurgeGroupMeta deletes stored group meta data
func (b *AMQPBackend) PurgeGroupMeta(groupUUID string) error {
conn, channel, err := b.Open(b.cnf.Broker, b.cnf.TLSConfig)
if err != nil {
return err
}
defer b.Close(channel, conn)
b.DeleteQueue(channel, amqmChordTriggeredQueue(groupUUID))
return b.DeleteQueue(channel, groupUUID)
}
// updateState saves current task state
func (b *AMQPBackend) updateState(taskState *tasks.TaskState) error {
message, err := json.Marshal(taskState)
if err != nil {
return fmt.Errorf("JSON marshal error: %s", err)
}
declareQueueArgs := amqp.Table{
// Time in milliseconds
// after that message will expire
"x-message-ttl": int32(b.getExpiresIn()),
// Time after that the queue will be deleted.
"x-expires": int32(b.getExpiresIn()),
}
conn, channel, queue, confirmsChan, _, err := b.Connect(
b.cnf.Broker,
b.cnf.TLSConfig,
b.cnf.AMQP.Exchange, // exchange name
b.cnf.AMQP.ExchangeType, // exchange type
taskState.TaskUUID, // queue name
false, // queue durable
true, // queue delete when unused
taskState.TaskUUID, // queue binding key
nil, // exchange declare args
declareQueueArgs, // queue declare args
nil, // queue binding args
)
if err != nil {
return err
}
defer b.Close(channel, conn)
if err := channel.Publish(
b.cnf.AMQP.Exchange, // exchange
queue.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "application/json",
Body: message,
DeliveryMode: amqp.Persistent, // Persistent // Transient
},
); err != nil {
return err
}
confirmed := <-confirmsChan
if confirmed.Ack {
return nil
}
return fmt.Errorf("Failed delivery of delivery tag: %d", confirmed.DeliveryTag)
}
// getExpiresIn returns expiration time
func (b *AMQPBackend) getExpiresIn() int {
resultsExpireIn := b.cnf.ResultsExpireIn * 1000
if resultsExpireIn == 0 {
// // expire results after 1 hour by default
resultsExpireIn = 3600 * 1000
}
return resultsExpireIn
}
// markTaskCompleted marks task as completed in either groupdUUID_success
// or groupUUID_failure queue. This is important for GroupCompleted and
// GroupSuccessful methods
func (b *AMQPBackend) markTaskCompleted(signature *tasks.Signature, taskState *tasks.TaskState) error {
if signature.GroupUUID == "" || signature.GroupTaskCount == 0 {
return nil
}
message, err := json.Marshal(taskState)
if err != nil {
return fmt.Errorf("JSON marshal error: %s", err)
}
declareQueueArgs := amqp.Table{
// Time in milliseconds
// after that message will expire
"x-message-ttl": int32(b.getExpiresIn()),
// Time after that the queue will be deleted.
"x-expires": int32(b.getExpiresIn()),
}
conn, channel, queue, confirmsChan, _, err := b.Connect(
b.cnf.Broker,
b.cnf.TLSConfig,
b.cnf.AMQP.Exchange, // exchange name
b.cnf.AMQP.ExchangeType, // exchange type
signature.GroupUUID, // queue name
false, // queue durable
true, // queue delete when unused
signature.GroupUUID, // queue binding key
nil, // exchange declare args
declareQueueArgs, // queue declare args
nil, // queue binding args
)
if err != nil {
return err
}
defer b.Close(channel, conn)
if err := channel.Publish(
b.cnf.AMQP.Exchange, // exchange
queue.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "application/json",
Body: message,
DeliveryMode: amqp.Persistent, // Persistent // Transient
},
); err != nil {
return err
}
confirmed := <-confirmsChan
if !confirmed.Ack {
return fmt.Errorf("Failed delivery of delivery tag: %v", confirmed.DeliveryTag)
}
return nil
}
func amqmChordTriggeredQueue(groupUUID string) string {
return fmt.Sprintf("%s_chord_triggered", groupUUID)
}