This repository has been archived by the owner on Apr 8, 2024. It is now read-only.
forked from elodina/go_kafka_client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workers.go
542 lines (472 loc) · 15.4 KB
/
workers.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
/* Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package go_kafka_client
import (
"fmt"
"math"
"sync"
"sync/atomic"
"time"
)
// WorkerManager is responsible for splitting the incomming batches of messages between a configured amount of workers.
// It also keeps track of highest processed offsets and commits them to offset storage with a configurable frequency.
type WorkerManager struct {
id string
config *ConsumerConfig
workers []*Worker
availableWorkers chan *Worker
currentBatch map[TaskId]*Task //TODO inspect for race conditions
batchOrder []TaskId
inputChannel chan []*Message
topicPartition TopicAndPartition
largestOffset int64
lastCommittedOffset int64
failCounter *FailureCounter
batchProcessed chan bool
stopLock sync.Mutex
managerStop chan bool
processingStop chan bool
commitStop chan bool
metrics *ConsumerMetrics
}
// Creates a new WorkerManager with given id using a given ConsumerConfig and responsible for managing given TopicAndPartition.
func NewWorkerManager(id string, config *ConsumerConfig, topicPartition TopicAndPartition, metrics *ConsumerMetrics) *WorkerManager {
workers := make([]*Worker, config.NumWorkers)
availableWorkers := make(chan *Worker, config.NumWorkers)
for i := 0; i < config.NumWorkers; i++ {
workers[i] = &Worker{
OutputChannel: make(chan WorkerResult),
TaskTimeout: config.WorkerTaskTimeout,
}
availableWorkers <- workers[i]
}
return &WorkerManager{
id: id,
config: config,
availableWorkers: availableWorkers,
workers: workers,
inputChannel: make(chan []*Message),
currentBatch: make(map[TaskId]*Task),
batchOrder: make([]TaskId, 0),
topicPartition: topicPartition,
largestOffset: InvalidOffset,
lastCommittedOffset: InvalidOffset,
failCounter: NewFailureCounter(config.WorkerRetryThreshold, config.WorkerThresholdTimeWindow),
batchProcessed: make(chan bool),
managerStop: make(chan bool),
processingStop: make(chan bool),
commitStop: make(chan bool),
metrics: metrics,
}
}
func (wm *WorkerManager) String() string {
return wm.id
}
// Starts processing incoming batches with this WorkerManager. Processing is possible only in batch-at-once mode.
// It also launches an offset committer routine.
// Call to this method blocks.
func (wm *WorkerManager) Start() {
go wm.processBatch()
go wm.commitBatch()
for {
startIdle := time.Now()
// force manager stop to be checked first
select {
case <-wm.managerStop:
return
default:
select {
case batch := <-wm.inputChannel:
{
wm.metrics.wMsIdle().Update(time.Since(startIdle))
Trace(wm, "WorkerManager got batch")
wm.metrics.wMsBatchDuration().Time(func() {
wm.startBatch(batch)
})
Trace(wm, "WorkerManager got batch processed")
}
case <-wm.managerStop:
return
}
}
}
}
// Tells this WorkerManager to finish processing current batch, stop accepting new work and shut down.
// This method returns immediately and returns a channel which will get the value once the shut down is finished.
func (wm *WorkerManager) Stop() chan bool {
finished := make(chan bool)
go func() {
Debugf(wm, "Trying to stop workerManager")
inLock(&wm.stopLock, func() {
Debug(wm, "Stopping manager")
wm.managerStop <- true
Debug(wm, "Stopping processor")
wm.processingStop <- true
Debug(wm, "Successful manager stop")
Debug(wm, "Stopping committer")
wm.commitStop <- true
Debug(wm, "Successful committer stop")
wm.failCounter.Close()
Debug(wm, "Stopped failure counter")
finished <- true
Debug(wm, "Leaving manager stop")
})
Debugf(wm, "Stopped workerManager")
}()
return finished
}
func (wm *WorkerManager) startBatch(batch []*Message) {
inLock(&wm.stopLock, func() {
wm.batchOrder = make([]TaskId, 0)
for _, message := range batch {
topicPartition := TopicAndPartition{message.Topic, message.Partition}
id := TaskId{topicPartition, message.Offset}
wm.batchOrder = append(wm.batchOrder, id)
wm.currentBatch[id] = &Task{Msg: message}
}
wm.metrics.pendingWMsTasks().Inc(int64(len(wm.currentBatch)))
for _, id := range wm.batchOrder {
task := wm.currentBatch[id]
worker := <-wm.availableWorkers
wm.metrics.activeWorkers().Inc(1)
wm.metrics.pendingWMsTasks().Dec(1)
worker.Start(task, wm.config.Strategy)
}
<-wm.batchProcessed
})
}
func (wm *WorkerManager) commitBatch() {
for {
select {
case <-wm.commitStop:
{
wm.commitOffset()
return
}
case <-time.After(wm.config.OffsetCommitInterval):
{
wm.commitOffset()
}
}
}
}
func (wm *WorkerManager) commitOffset() {
largestOffset := wm.GetLargestOffset()
Tracef(wm, "Inside commit offset with largest %d and last %d", largestOffset, wm.lastCommittedOffset)
if largestOffset <= wm.lastCommittedOffset || isOffsetInvalid(largestOffset) {
return
}
success := false
for i := 0; i <= wm.config.OffsetsCommitMaxRetries; i++ {
err := wm.config.OffsetStorage.CommitOffset(wm.config.Groupid, wm.topicPartition.Topic, wm.topicPartition.Partition, largestOffset)
if err == nil {
success = true
Tracef(wm, "Successfully committed offset %d for %s", largestOffset, wm.topicPartition)
break
} else {
Warnf(wm, "Failed to commit offset %d for %s. Retrying...", largestOffset, &wm.topicPartition)
}
}
if !success {
Errorf(wm, "Failed to commit offset %d for %s after %d retries", largestOffset, &wm.topicPartition, wm.config.OffsetsCommitMaxRetries)
//TODO: what to do next?
} else {
wm.lastCommittedOffset = largestOffset
}
}
// Asks this WorkerManager whether the current batch is fully processed. Returns true if so, false otherwise.
func (wm *WorkerManager) IsBatchProcessed() bool {
return len(wm.currentBatch) == 0
}
func (wm *WorkerManager) processBatch() {
outputChannels := make([]*chan WorkerResult, wm.config.NumWorkers)
for i, worker := range wm.workers {
outputChannels[i] = &worker.OutputChannel
}
resultsChannel := make(chan WorkerResult)
for {
stopRedirecting := redirectChannelsTo(outputChannels, resultsChannel)
select {
case result := <-resultsChannel:
{
go func() {
stopRedirecting <- true
}()
task := wm.currentBatch[result.Id()]
if result.Success() {
wm.taskIsDone(result)
} else {
if _, ok := result.(*TimedOutResult); ok {
task.Callee.OutputChannel = make(chan WorkerResult)
}
Warnf(wm, "Worker task %s has failed", result.Id())
task.Retries++
if task.Retries > wm.config.MaxWorkerRetries {
Errorf(wm, "Worker task %s has failed after %d retries", result.Id(), wm.config.MaxWorkerRetries)
var decision FailedDecision
if wm.failCounter.Failed() {
decision = wm.config.WorkerFailureCallback(wm)
} else {
decision = wm.config.WorkerFailedAttemptCallback(task, result)
}
switch decision {
case CommitOffsetAndContinue:
{
wm.taskIsDone(result)
}
case DoNotCommitOffsetAndContinue:
{
wm.availableWorkers <- wm.currentBatch[result.Id()].Callee
delete(wm.currentBatch, result.Id())
}
case CommitOffsetAndStop:
{
wm.taskIsDone(result)
wm.stopBatch()
}
case DoNotCommitOffsetAndStop:
{
wm.stopBatch()
}
}
} else {
Warnf(wm, "Retrying worker task %s %dth time", result.Id(), task.Retries)
time.Sleep(wm.config.WorkerBackoff)
go task.Callee.Start(task, wm.config.Strategy)
}
}
if wm.IsBatchProcessed() {
Trace(wm, "Sending batch processed")
wm.batchProcessed <- true
Trace(wm, "Received batch processed")
}
}
case <-wm.processingStop:
{
go func() {
stopRedirecting <- true
}()
return
}
}
}
}
func (wm *WorkerManager) stopBatch() {
wm.currentBatch = make(map[TaskId]*Task)
for _, worker := range wm.workers {
worker.OutputChannel = make(chan WorkerResult)
}
}
func (wm *WorkerManager) taskIsDone(result WorkerResult) {
Tracef(wm, "Task is done: %d", result.Id().Offset)
wm.UpdateLargestOffset(result.Id().Offset)
wm.availableWorkers <- wm.currentBatch[result.Id()].Callee
wm.metrics.activeWorkers().Dec(1)
delete(wm.currentBatch, result.Id())
}
// Gets the highest offset that has been processed by this WorkerManager.
func (wm *WorkerManager) GetLargestOffset() int64 {
return atomic.LoadInt64(&wm.largestOffset)
}
// Updates the highest offset that has been processed by this WorkerManager with a new value.
func (wm *WorkerManager) UpdateLargestOffset(offset int64) {
atomic.StoreInt64(&wm.largestOffset, int64(math.Max(float64(wm.GetLargestOffset()), float64(offset))))
}
// Represents a worker that is able to process a single message.
type Worker struct {
// Channel to write processing results to.
OutputChannel chan WorkerResult
// Timeout for a single worker task.
TaskTimeout time.Duration
// Indicates whether this worker is closed and cannot accept new work.
Closed bool
}
func (w *Worker) String() string {
return "worker"
}
// Starts processing a given task using given strategy with this worker.
// Call to this method blocks until the task is done or timed out.
func (w *Worker) Start(task *Task, strategy WorkerStrategy) {
task.Callee = w
go func() {
shouldStop := false
resultChannel := make(chan WorkerResult)
go func() {
result := strategy(w, task.Msg, task.Id())
for !shouldStop {
select {
case resultChannel <- result:
return
case <-time.After(5 * time.Second):
}
}
}()
select {
case result := <-resultChannel:
{
w.OutputChannel <- result
}
case <-time.After(w.TaskTimeout):
{
shouldStop = true
w.OutputChannel <- &TimedOutResult{task.Id()}
}
}
}()
}
// Defines what to do with a single Kafka message. Returns a WorkerResult to distinguish successful and unsuccessful processings.
type WorkerStrategy func(*Worker, *Message, TaskId) WorkerResult
// A callback that is triggered when a worker fails to process ConsumerConfig.WorkerRetryThreshold messages within ConsumerConfig.WorkerThresholdTimeWindow
type FailedCallback func(*WorkerManager) FailedDecision
// A callback that is triggered when a worker fails to process a single message.
type FailedAttemptCallback func(*Task, WorkerResult) FailedDecision
// A counter used to track whether we reached the configurable threshold of failed messages within a given time window.
type FailureCounter struct {
count int32
failed bool
countLock sync.Mutex
failedThreshold int32
stop chan bool
}
// Creates a new FailureCounter with threshold FailedThreshold and time window WorkerThresholdTimeWindow.
func NewFailureCounter(FailedThreshold int32, WorkerThresholdTimeWindow time.Duration) *FailureCounter {
counter := &FailureCounter{
failedThreshold: FailedThreshold,
stop: make(chan bool),
}
go func() {
for {
select {
case <-time.After(WorkerThresholdTimeWindow):
{
if counter.count >= FailedThreshold {
counter.failed = true
return
} else {
inLock(&counter.countLock, func() {
counter.count = 0
})
}
}
case <-counter.stop:
return
}
}
}()
return counter
}
// Tells this FailureCounter to increment a number of failures by one.
// Returns true if threshold is reached, false otherwise.
func (f *FailureCounter) Failed() bool {
inLock(&f.countLock, func() { f.count++ })
return f.count >= f.failedThreshold || f.failed
}
// Stops this failure counter
func (f *FailureCounter) Close() {
f.stop <- true
}
// Represents a single task for a worker.
type Task struct {
// A message that should be processed.
Msg *Message
// Number of retries used for this task.
Retries int
// A worker that is responsible for processing this task.
Callee *Worker
}
// Returns an id for this Task.
func (t *Task) Id() TaskId {
return TaskId{TopicAndPartition{t.Msg.Topic, t.Msg.Partition}, t.Msg.Offset}
}
// Interface that represents a result of processing incoming message.
type WorkerResult interface {
// Returns an id of task that was processed.
Id() TaskId
// Returns true if processing succeeded, false otherwise.
Success() bool
}
// An implementation of WorkerResult interface representing a successfully processed incoming message.
type SuccessfulResult struct {
id TaskId
}
// Creates a new SuccessfulResult for given TaskId.
func NewSuccessfulResult(id TaskId) *SuccessfulResult {
return &SuccessfulResult{id}
}
func (sr *SuccessfulResult) String() string {
return fmt.Sprintf("{Success: %s}", sr.Id())
}
// Returns an id of task that was processed.
func (wr *SuccessfulResult) Id() TaskId {
return wr.id
}
// Always returns true for SuccessfulResult.
func (wr *SuccessfulResult) Success() bool {
return true
}
// An implementation of WorkerResult interface representing a failure to process incoming message.
type ProcessingFailedResult struct {
id TaskId
}
// Creates a new ProcessingFailedResult for given TaskId.
func NewProcessingFailedResult(id TaskId) *ProcessingFailedResult {
return &ProcessingFailedResult{id}
}
func (sr *ProcessingFailedResult) String() string {
return fmt.Sprintf("{Failed: %s}", sr.Id())
}
// Returns an id of task that was processed.
func (wr *ProcessingFailedResult) Id() TaskId {
return wr.id
}
// Always returns false for ProcessingFailedResult.
func (wr *ProcessingFailedResult) Success() bool {
return false
}
// An implementation of WorkerResult interface representing a timeout to process incoming message.
type TimedOutResult struct {
id TaskId
}
func (sr *TimedOutResult) String() string {
return fmt.Sprintf("{Timed out: %s}", sr.Id())
}
// Returns an id of task that was processed.
func (wr *TimedOutResult) Id() TaskId {
return wr.id
}
// Always returns false for TimedOutResult.
func (wr *TimedOutResult) Success() bool {
return false
}
// Type representing a task id. Consists from topic, partition and offset of a message being processed.
type TaskId struct {
// Message's topic and partition
TopicPartition TopicAndPartition
// Message's offset
Offset int64
}
func (tid TaskId) String() string {
return fmt.Sprintf("%s, Offset: %d", &tid.TopicPartition, tid.Offset)
}
// Defines what to do when worker fails to process a message.
type FailedDecision int32
const (
// Tells the worker manager to ignore the failure and continue normally.
CommitOffsetAndContinue FailedDecision = iota
// Tells the worker manager to continue processing new messages but not to commit offset that failed.
DoNotCommitOffsetAndContinue
// Tells the worker manager to commit offset and stop processing the current batch.
CommitOffsetAndStop
// Tells the worker manager not to commit offset and stop processing the current batch.
DoNotCommitOffsetAndStop
)