-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathproducer.go
129 lines (105 loc) · 2.46 KB
/
producer.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
package borges
import (
"io"
"sync"
"github.com/src-d/borges/metrics"
"gopkg.in/src-d/go-log.v1"
"gopkg.in/src-d/go-queue.v1"
)
// Producer is a service to generate jobs and put them to the queue.
type Producer struct {
jobIter JobIter
queue queue.Queue
running bool
maxJobRetries int
priority queue.Priority
startOnce *sync.Once
stopOnce *sync.Once
// used by Stop() to wait until Start() has finished
startIsRunning chan struct{}
}
// NewProducer creates a new producer.
func NewProducer(i JobIter, q queue.Queue, p queue.Priority, jobRetries int) *Producer {
return &Producer{
jobIter: i,
queue: q,
maxJobRetries: jobRetries,
priority: p,
startOnce: &sync.Once{},
stopOnce: &sync.Once{},
}
}
// Start starts the producer services. It blocks until Stop is called.
func (p *Producer) Start() {
p.startOnce.Do(p.start)
}
// Stop stops the producer.
func (p *Producer) Stop() {
p.stopOnce.Do(p.stop)
}
func (p *Producer) start() {
log.Debugf("starting up")
p.running = true
p.startIsRunning = make(chan struct{})
defer func() { close(p.startIsRunning) }()
const nextJobErrMaxPrints = 5
var nextJobSameErr int
var lastNextJobErr error
for {
if !p.running {
break
}
j, err := p.jobIter.Next()
if err == io.EOF {
log.Debugf("no more jobs in the queue")
break
}
if err != nil {
if nextJobSameErr < nextJobErrMaxPrints {
log.Errorf(err, "error obtaining next job")
if lastNextJobErr == nil || err.Error() == lastNextJobErr.Error() {
nextJobSameErr++
} else {
nextJobSameErr = 0
}
}
lastNextJobErr = err
continue
}
nextJobSameErr = 0
if err := p.add(j); err != nil {
metrics.RepoProduceFailed()
log.With(log.Fields{"job": j.RepositoryID}).Errorf(err, "error adding job to the queue")
} else {
metrics.RepoProduced()
log.With(log.Fields{"job": j.RepositoryID}).Infof("job queued")
}
}
log.Infof("stopping")
}
func (p *Producer) add(j *Job) error {
qj, err := queue.NewJob()
if err != nil {
return err
}
qj.Retries = int32(p.maxJobRetries)
if err := qj.Encode(j); err != nil {
return err
}
qj.SetPriority(p.priority)
return p.queue.Publish(qj)
}
func (p *Producer) stop() {
p.running = false
p.closeIter()
<-p.startIsRunning
}
func (p *Producer) closeIter() {
if p.jobIter == nil {
return
}
if err := p.jobIter.Close(); err != nil {
log.Errorf(err, "error closing queue iterator")
}
p.jobIter = nil
}