forked from RichardKnop/machinery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
468 lines (380 loc) · 13 KB
/
server.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package machinery
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/google/uuid"
"github.com/robfig/cron/v3"
"github.com/RichardKnop/machinery/v1/backends/result"
"github.com/RichardKnop/machinery/v1/brokers/eager"
"github.com/RichardKnop/machinery/v1/config"
"github.com/RichardKnop/machinery/v1/log"
"github.com/RichardKnop/machinery/v1/tasks"
"github.com/RichardKnop/machinery/v1/tracing"
"github.com/RichardKnop/machinery/v1/utils"
backendsiface "github.com/RichardKnop/machinery/v1/backends/iface"
brokersiface "github.com/RichardKnop/machinery/v1/brokers/iface"
lockiface "github.com/RichardKnop/machinery/v1/locks/iface"
opentracing "github.com/opentracing/opentracing-go"
)
// Server is the main Machinery object and stores all configuration
// All the tasks workers process are registered against the server
type Server struct {
config *config.Config
registeredTasks *sync.Map
broker brokersiface.Broker
backend backendsiface.Backend
lock lockiface.Lock
scheduler *cron.Cron
prePublishHandler func(*tasks.Signature)
}
// NewServerWithBrokerBackend ...
func NewServerWithBrokerBackendLock(cnf *config.Config, brokerServer brokersiface.Broker, backendServer backendsiface.Backend, lock lockiface.Lock) *Server {
srv := &Server{
config: cnf,
registeredTasks: new(sync.Map),
broker: brokerServer,
backend: backendServer,
lock: lock,
scheduler: cron.New(),
}
// Run scheduler job
go srv.scheduler.Run()
return srv
}
// NewServer creates Server instance
func NewServer(cnf *config.Config) (*Server, error) {
broker, err := BrokerFactory(cnf)
if err != nil {
return nil, err
}
// Backend is optional so we ignore the error
backend, _ := BackendFactory(cnf)
// Init lock
lock, err := LockFactory(cnf)
if err != nil {
return nil, err
}
srv := NewServerWithBrokerBackendLock(cnf, broker, backend, lock)
// init for eager-mode
eager, ok := broker.(eager.Mode)
if ok {
// we don't have to call worker.Launch in eager mode
eager.AssignWorker(srv.NewWorker("eager", 0))
}
return srv, nil
}
// NewWorker creates Worker instance
func (server *Server) NewWorker(consumerTag string, concurrency int) *Worker {
return &Worker{
server: server,
ConsumerTag: consumerTag,
Concurrency: concurrency,
Queue: "",
}
}
// NewCustomQueueWorker creates Worker instance with Custom Queue
func (server *Server) NewCustomQueueWorker(consumerTag string, concurrency int, queue string) *Worker {
return &Worker{
server: server,
ConsumerTag: consumerTag,
Concurrency: concurrency,
Queue: queue,
}
}
// GetBroker returns broker
func (server *Server) GetBroker() brokersiface.Broker {
return server.broker
}
// SetBroker sets broker
func (server *Server) SetBroker(broker brokersiface.Broker) {
server.broker = broker
}
// GetBackend returns backend
func (server *Server) GetBackend() backendsiface.Backend {
return server.backend
}
// SetBackend sets backend
func (server *Server) SetBackend(backend backendsiface.Backend) {
server.backend = backend
}
// GetConfig returns connection object
func (server *Server) GetConfig() *config.Config {
return server.config
}
// SetConfig sets config
func (server *Server) SetConfig(cnf *config.Config) {
server.config = cnf
}
// SetPreTaskHandler Sets pre publish handler
func (server *Server) SetPreTaskHandler(handler func(*tasks.Signature)) {
server.prePublishHandler = handler
}
// RegisterTasks registers all tasks at once
func (server *Server) RegisterTasks(namedTaskFuncs map[string]interface{}) error {
for _, task := range namedTaskFuncs {
if err := tasks.ValidateTask(task); err != nil {
return err
}
}
for k, v := range namedTaskFuncs {
server.registeredTasks.Store(k, v)
}
server.broker.SetRegisteredTaskNames(server.GetRegisteredTaskNames())
return nil
}
// RegisterTask registers a single task
func (server *Server) RegisterTask(name string, taskFunc interface{}) error {
if err := tasks.ValidateTask(taskFunc); err != nil {
return err
}
server.registeredTasks.Store(name, taskFunc)
server.broker.SetRegisteredTaskNames(server.GetRegisteredTaskNames())
return nil
}
// IsTaskRegistered returns true if the task name is registered with this broker
func (server *Server) IsTaskRegistered(name string) bool {
_, ok := server.registeredTasks.Load(name)
return ok
}
// GetRegisteredTask returns registered task by name
func (server *Server) GetRegisteredTask(name string) (interface{}, error) {
taskFunc, ok := server.registeredTasks.Load(name)
if !ok {
return nil, fmt.Errorf("Task not registered error: %s", name)
}
return taskFunc, nil
}
// SendTaskWithContext will inject the trace context in the signature headers before publishing it
func (server *Server) SendTaskWithContext(ctx context.Context, signature *tasks.Signature) (*result.AsyncResult, error) {
span, _ := opentracing.StartSpanFromContext(ctx, "SendTask", tracing.ProducerOption(), tracing.MachineryTag)
defer span.Finish()
// tag the span with some info about the signature
signature.Headers = tracing.HeadersWithSpan(signature.Headers, span)
// Make sure result backend is defined
if server.backend == nil {
return nil, errors.New("Result backend required")
}
// Auto generate a UUID if not set already
if signature.UUID == "" {
taskID := uuid.New().String()
signature.UUID = fmt.Sprintf("task_%v", taskID)
}
// Set initial task state to PENDING
if err := server.backend.SetStatePending(signature); err != nil {
return nil, fmt.Errorf("Set state pending error: %s", err)
}
if server.prePublishHandler != nil {
server.prePublishHandler(signature)
}
if err := server.broker.Publish(ctx, signature); err != nil {
return nil, fmt.Errorf("Publish message error: %s", err)
}
return result.NewAsyncResult(signature, server.backend), nil
}
// SendTask publishes a task to the default queue
func (server *Server) SendTask(signature *tasks.Signature) (*result.AsyncResult, error) {
return server.SendTaskWithContext(context.Background(), signature)
}
// SendChainWithContext will inject the trace context in all the signature headers before publishing it
func (server *Server) SendChainWithContext(ctx context.Context, chain *tasks.Chain) (*result.ChainAsyncResult, error) {
span, _ := opentracing.StartSpanFromContext(ctx, "SendChain", tracing.ProducerOption(), tracing.MachineryTag, tracing.WorkflowChainTag)
defer span.Finish()
tracing.AnnotateSpanWithChainInfo(span, chain)
return server.SendChain(chain)
}
// SendChain triggers a chain of tasks
func (server *Server) SendChain(chain *tasks.Chain) (*result.ChainAsyncResult, error) {
_, err := server.SendTask(chain.Tasks[0])
if err != nil {
return nil, err
}
return result.NewChainAsyncResult(chain.Tasks, server.backend), nil
}
// SendGroupWithContext will inject the trace context in all the signature headers before publishing it
func (server *Server) SendGroupWithContext(ctx context.Context, group *tasks.Group, sendConcurrency int) ([]*result.AsyncResult, error) {
span, _ := opentracing.StartSpanFromContext(ctx, "SendGroup", tracing.ProducerOption(), tracing.MachineryTag, tracing.WorkflowGroupTag)
defer span.Finish()
tracing.AnnotateSpanWithGroupInfo(span, group, sendConcurrency)
// Make sure result backend is defined
if server.backend == nil {
return nil, errors.New("Result backend required")
}
asyncResults := make([]*result.AsyncResult, len(group.Tasks))
var wg sync.WaitGroup
wg.Add(len(group.Tasks))
errorsChan := make(chan error, len(group.Tasks)*2)
// Init group
server.backend.InitGroup(group.GroupUUID, group.GetUUIDs())
// Init the tasks Pending state first
for _, signature := range group.Tasks {
if err := server.backend.SetStatePending(signature); err != nil {
errorsChan <- err
continue
}
}
pool := make(chan struct{}, sendConcurrency)
go func() {
for i := 0; i < sendConcurrency; i++ {
pool <- struct{}{}
}
}()
for i, signature := range group.Tasks {
if sendConcurrency > 0 {
<-pool
}
go func(s *tasks.Signature, index int) {
defer wg.Done()
// Publish task
err := server.broker.Publish(ctx, s)
if sendConcurrency > 0 {
pool <- struct{}{}
}
if err != nil {
errorsChan <- fmt.Errorf("Publish message error: %s", err)
return
}
asyncResults[index] = result.NewAsyncResult(s, server.backend)
}(signature, i)
}
done := make(chan int)
go func() {
wg.Wait()
done <- 1
}()
select {
case err := <-errorsChan:
return asyncResults, err
case <-done:
return asyncResults, nil
}
}
// SendGroup triggers a group of parallel tasks
func (server *Server) SendGroup(group *tasks.Group, sendConcurrency int) ([]*result.AsyncResult, error) {
return server.SendGroupWithContext(context.Background(), group, sendConcurrency)
}
// SendChordWithContext will inject the trace context in all the signature headers before publishing it
func (server *Server) SendChordWithContext(ctx context.Context, chord *tasks.Chord, sendConcurrency int) (*result.ChordAsyncResult, error) {
span, _ := opentracing.StartSpanFromContext(ctx, "SendChord", tracing.ProducerOption(), tracing.MachineryTag, tracing.WorkflowChordTag)
defer span.Finish()
tracing.AnnotateSpanWithChordInfo(span, chord, sendConcurrency)
_, err := server.SendGroupWithContext(ctx, chord.Group, sendConcurrency)
if err != nil {
return nil, err
}
return result.NewChordAsyncResult(
chord.Group.Tasks,
chord.Callback,
server.backend,
), nil
}
// SendChord triggers a group of parallel tasks with a callback
func (server *Server) SendChord(chord *tasks.Chord, sendConcurrency int) (*result.ChordAsyncResult, error) {
return server.SendChordWithContext(context.Background(), chord, sendConcurrency)
}
// GetRegisteredTaskNames returns slice of registered task names
func (server *Server) GetRegisteredTaskNames() []string {
taskNames := make([]string, 0)
server.registeredTasks.Range(func(key, value interface{}) bool {
taskNames = append(taskNames, key.(string))
return true
})
return taskNames
}
// RegisterPeriodicTask register a periodic task which will be triggered periodically
func (server *Server) RegisterPeriodicTask(spec, name string, signature *tasks.Signature) error {
//check spec
schedule, err := cron.ParseStandard(spec)
if err != nil {
return err
}
f := func() {
//get lock
err := server.lock.LockWithRetries(utils.GetLockName(name, spec), schedule.Next(time.Now()).UnixNano()-1)
if err != nil {
return
}
//send task
_, err = server.SendTask(tasks.CopySignature(signature))
if err != nil {
log.ERROR.Printf("periodic task failed. task name is: %s. error is %s", name, err.Error())
}
}
_, err = server.scheduler.AddFunc(spec, f)
return err
}
// RegisterPeriodicChain register a periodic chain which will be triggered periodically
func (server *Server) RegisterPeriodicChain(spec, name string, signatures ...*tasks.Signature) error {
//check spec
schedule, err := cron.ParseStandard(spec)
if err != nil {
return err
}
f := func() {
// new chain
chain, _ := tasks.NewChain(tasks.CopySignatures(signatures...)...)
//get lock
err := server.lock.LockWithRetries(utils.GetLockName(name, spec), schedule.Next(time.Now()).UnixNano()-1)
if err != nil {
return
}
//send task
_, err = server.SendChain(chain)
if err != nil {
log.ERROR.Printf("periodic task failed. task name is: %s. error is %s", name, err.Error())
}
}
_, err = server.scheduler.AddFunc(spec, f)
return err
}
// RegisterPeriodicGroup register a periodic group which will be triggered periodically
func (server *Server) RegisterPeriodicGroup(spec, name string, sendConcurrency int, signatures ...*tasks.Signature) error {
//check spec
schedule, err := cron.ParseStandard(spec)
if err != nil {
return err
}
f := func() {
// new group
group, _ := tasks.NewGroup(tasks.CopySignatures(signatures...)...)
//get lock
err := server.lock.LockWithRetries(utils.GetLockName(name, spec), schedule.Next(time.Now()).UnixNano()-1)
if err != nil {
return
}
//send task
_, err = server.SendGroup(group, sendConcurrency)
if err != nil {
log.ERROR.Printf("periodic task failed. task name is: %s. error is %s", name, err.Error())
}
}
_, err = server.scheduler.AddFunc(spec, f)
return err
}
// RegisterPeriodicChord register a periodic chord which will be triggered periodically
func (server *Server) RegisterPeriodicChord(spec, name string, sendConcurrency int, callback *tasks.Signature, signatures ...*tasks.Signature) error {
//check spec
schedule, err := cron.ParseStandard(spec)
if err != nil {
return err
}
f := func() {
// new chord
group, _ := tasks.NewGroup(tasks.CopySignatures(signatures...)...)
chord, _ := tasks.NewChord(group, tasks.CopySignature(callback))
//get lock
err := server.lock.LockWithRetries(utils.GetLockName(name, spec), schedule.Next(time.Now()).UnixNano()-1)
if err != nil {
return
}
//send task
_, err = server.SendChord(chord, sendConcurrency)
if err != nil {
log.ERROR.Printf("periodic task failed. task name is: %s. error is %s", name, err.Error())
}
}
_, err = server.scheduler.AddFunc(spec, f)
return err
}