-
Notifications
You must be signed in to change notification settings - Fork 85
/
multi_source_job_queue.go
107 lines (90 loc) · 2.47 KB
/
multi_source_job_queue.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
package worker
import (
"fmt"
"strings"
"time"
gocontext "context"
"github.com/sirupsen/logrus"
"github.com/travis-ci/worker/context"
"github.com/travis-ci/worker/metrics"
)
type MultiSourceJobQueue struct {
queues []JobQueue
}
func NewMultiSourceJobQueue(queues ...JobQueue) *MultiSourceJobQueue {
return &MultiSourceJobQueue{queues: queues}
}
// Jobs returns a Job channel that selects over each source queue Job channel
func (msjq *MultiSourceJobQueue) Jobs(ctx gocontext.Context) (outChan <-chan Job, err error) {
logger := context.LoggerFromContext(ctx).WithFields(logrus.Fields{
"self": "multi_source_job_queue",
"inst": fmt.Sprintf("%p", msjq),
})
buildJobChan := make(chan Job)
outChan = buildJobChan
buildJobChans := map[string]<-chan Job{}
for i, queue := range msjq.queues {
jc, err := queue.Jobs(ctx)
if err != nil {
logger.WithFields(logrus.Fields{
"err": err,
"name": queue.Name(),
}).Error("failed to get job chan from queue")
return nil, err
}
qName := fmt.Sprintf("%s.%d", queue.Name(), i)
buildJobChans[qName] = jc
}
go func() {
for {
for queueName, bjc := range buildJobChans {
var job Job = nil
jobSendBegin := time.Now()
logger = logger.WithField("queue_name", queueName)
logger.Debug("about to receive job")
select {
case job = <-bjc:
if job == nil {
logger.Debug("skipping nil job")
continue
}
jobID := uint64(0)
if job.Payload() != nil {
jobID = job.Payload().Job.ID
}
logger.WithField("job_id", jobID).Debug("about to send job to multi source output channel")
buildJobChan <- job
metrics.TimeSince("travis.worker.job_queue.multi.blocking_time", jobSendBegin)
logger.WithFields(logrus.Fields{
"job_id": jobID,
"source": queueName,
"send_duration_ms": time.Since(jobSendBegin).Seconds() * 1e3,
}).Info("sent job to multi source output channel")
case <-ctx.Done():
return
case <-time.After(time.Second):
continue
}
}
}
}()
return outChan, nil
}
// Name builds a name from each source queue name
func (msjq *MultiSourceJobQueue) Name() string {
s := []string{}
for _, queue := range msjq.queues {
s = append(s, queue.Name())
}
return strings.Join(s, ",")
}
// Cleanup runs cleanup for each source queue
func (msjq *MultiSourceJobQueue) Cleanup() error {
for _, queue := range msjq.queues {
err := queue.Cleanup()
if err != nil {
return err
}
}
return nil
}