-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgofherd.go
282 lines (248 loc) · 6.73 KB
/
gofherd.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
package gofherd
import (
"fmt"
"net/http"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Gofherd is the core struct, orchestrating all functionality.
// It offers all the public methods of Gofherd.
type Gofherd struct {
input queue
output queue
retry queue
quit chan struct{}
processingLogic func(*Work) Status
successCallback func(*Work)
retryCallback func(*Work)
failureCallback func(*Work)
herdSize int64
maxRetries int64
addr string
logger Logger
}
// New initializes a new Gofherd struct. It takes in the processing logic function
// with the signature `func(*gf.Work) gf.Status`
func New(processingLogic func(*Work) Status) *Gofherd {
return &Gofherd{
processingLogic: processingLogic,
input: newQueue(),
output: newQueue(),
retry: newQueue(),
addr: "127.0.0.1:2112",
logger: noOpLogger{},
quit: make(chan struct{}),
}
}
// SetLogger is used to setup logging. If not specified, gofherd emits no logs.
func (gf *Gofherd) SetLogger(l Logger) {
gf.logger = l
}
// AddSuccessCallback is used to setup logging. If not specified, gofherd emits no logs.
func (gf *Gofherd) AddSuccessCallback(f func(*Work)) {
gf.successCallback = f
}
// AddRetryCallback is used to setup logging. If not specified, gofherd emits no logs.
func (gf *Gofherd) AddRetryCallback(f func(*Work)) {
gf.retryCallback = f
}
// AddFailureCallback is used to setup logging. If not specified, gofherd emits no logs.
func (gf *Gofherd) AddFailureCallback(f func(*Work)) {
gf.failureCallback = f
}
// SendWork enques Work onto the input chan.
func (gf *Gofherd) SendWork(work Work) {
gf.input.increment()
gf.input.hose <- work
gf.logger.Printf("Pushed to input, work: %s\n", work.ID)
}
// OutputChan returns the output chan, it will be closed when the processing is complete,
// enabling it to be read in a `for range` loop.
func (gf *Gofherd) OutputChan() <-chan Work {
return gf.output.hose
}
// CloseInputChan is to closed the input chan. Closing the input chan when the tasks are completed
// will allow gofherd to shutdown gracefully.
func (gf *Gofherd) CloseInputChan() {
gf.input.lock()
defer gf.input.unlock()
if !gf.input.closed() {
close(gf.input.hose)
gf.logger.Printf("Closed input chan\n")
gf.input.setClosedTrue()
gf.maintainRetry()
}
}
func (gf *Gofherd) closeOutputChan() {
gf.output.lock()
defer gf.output.unlock()
if !gf.output.closed() {
close(gf.output.hose)
gf.logger.Printf("Closed output chan\n")
gf.output.setClosedTrue()
}
}
// SetHerdSize sets the herd size. The passed number is the number of
// gofhers spawned up for processing.
func (gf *Gofherd) SetHerdSize(num int64) {
gf.herdSize = num
}
// SetAddr accepts the `addr` string where the started server will be spun up.
func (gf *Gofherd) SetAddr(addr string) {
gf.addr = addr
}
// SetMaxRetries is the maximum number of times a Work unit will be tried before giving up.
func (gf *Gofherd) SetMaxRetries(num int64) {
gf.maxRetries = num
}
func (gf *Gofherd) pushToOutputChan(work Work) {
if work.Status() == Success {
gf.registerSuccess(&work)
}
if work.Status() == Failure {
gf.registerFailure(&work)
}
gf.logger.Printf("Pusing to output, work: %s\n", work.ID)
gf.output.hose <- work
gf.output.increment()
gf.maintainRetry()
return
}
func (gf *Gofherd) maintainRetry() {
gf.retry.lock()
defer gf.retry.unlock()
if !gf.retry.closed() && gf.input.closed() && gf.input.count() == gf.output.count() {
gf.closeRetryChan()
}
}
func (gf *Gofherd) closeRetryChan() {
close(gf.retry.hose)
gf.logger.Printf("Closed retry chan\n")
gf.retry.setClosedTrue()
}
func (gf *Gofherd) pushToRetryChan(work Work) {
gf.registerRetry(&work)
work.incrementRetries()
go func() {
gf.retry.hose <- work
gf.logger.Printf("Pushed to retry, work: %s\n", work.ID)
}()
return
}
func (gf *Gofherd) receivedRetry(work Work, ok bool) bool {
if !ok {
gf.closeOutputChan()
return true
}
gf.logger.Printf("Received work from retry: %s\n", work.ID)
gf.handleInput(work)
return false
}
func (gf *Gofherd) initGopher() {
var work Work
var ok bool
for {
select {
case <-gf.quit:
gf.logger.Printf("Received quit, closing chan\n")
return
case work, ok = <-gf.input.hose:
if !ok {
goto handleRetries
}
gf.logger.Printf("Received work from input: %s\n", work.ID)
gf.handleInput(work)
case work, ok = <-gf.retry.hose:
if quit := gf.receivedRetry(work, ok); quit {
return
}
}
}
handleRetries:
for {
select {
case <-gf.quit:
gf.logger.Printf("Received quit, closing chan\n")
return
case work, ok = <-gf.retry.hose:
if quit := gf.receivedRetry(work, ok); quit {
return
}
}
}
gf.closeOutputChan()
}
func (gf *Gofherd) handleInput(work Work) {
status := gf.processingLogic(&work)
work.setStatus(status)
if work.Status() == Success || work.Status() == Failure {
gf.pushToOutputChan(work)
return
}
if work.Status() == Retry && work.retryCount() < gf.maxRetries {
gf.pushToRetryChan(work)
return
}
work.setStatus(Failure)
gf.pushToOutputChan(work)
}
func (gf *Gofherd) registerRetry(w *Work) {
if gf.retryCallback != nil {
gf.retryCallback(w)
}
incrementRetryMetric()
}
func (gf *Gofherd) registerSuccess(w *Work) {
if gf.successCallback != nil {
gf.successCallback(w)
}
incrementSuccessMetric()
}
func (gf *Gofherd) registerFailure(w *Work) {
if gf.failureCallback != nil {
gf.failureCallback(w)
}
incrementFailureMetric()
}
func (gf *Gofherd) updateHerdSize(num int64) (Status, string) {
if num < 0 {
msg := fmt.Sprintf("Herd size cannot be negative")
gf.logger.Printf(msg + "\n")
return Retry, msg
}
oldSize := gf.herdSize
if oldSize == num {
msg := fmt.Sprintf("Herd size already %d", num)
gf.logger.Printf(msg + "\n")
return Success, msg
}
if num > oldSize {
gf.IncreasedHerdBy(num - oldSize)
}
if num < oldSize {
gf.DecreaseHerdBy(oldSize - num)
}
gf.SetHerdSize(num)
return Success, "success"
}
// IncreasedHerdBy is used to increase the herd size given amount
func (gf *Gofherd) IncreasedHerdBy(num int64) {
for i := int64(0); i < num; i++ {
gf.logger.Printf("Starting gofher #%d\n", i)
go gf.initGopher()
}
}
// DecreaseHerdBy is used to decrease the herd size given amount
func (gf *Gofherd) DecreaseHerdBy(num int64) {
for i := int64(0); i < num; i++ {
gf.quit <- struct{}{}
}
}
// Start will start the processing and start the server. The function will return immediately.
func (gf *Gofherd) Start() {
gf.logger.Printf("Starting server at %s\n", gf.addr)
mux := http.NewServeMux()
mux.Handle("/herd", http.HandlerFunc(gf.herdHandler))
mux.Handle("/metrics", promhttp.Handler())
go http.ListenAndServe(gf.addr, mux)
gf.IncreasedHerdBy(gf.herdSize)
}