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
/
Copy pathmirror_maker.go
395 lines (341 loc) · 11.9 KB
/
mirror_maker.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
/* 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"
avro "github.com/stealthly/go-avro"
"hash/fnv"
"io/ioutil"
"reflect"
"time"
)
// MirrorMakerConfig defines configuration options for MirrorMaker
type MirrorMakerConfig struct {
// Whitelist of topics to mirror. Exactly one whitelist or blacklist is allowed.
Whitelist string
// Blacklist of topics to mirror. Exactly one whitelist or blacklist is allowed.
Blacklist string
// Consumer configurations to consume from a source cluster.
ConsumerConfigs []string
// Embedded producer config.
ProducerConfig string
// Number of producer instances.
NumProducers int
// Number of consumption streams.
NumStreams int
// Flag to preserve partition number. E.g. if message was read from partition 5 it'll be written to partition 5. Note that this can affect performance.
PreservePartitions bool
// Flag to preserve message order. E.g. message sequence 1, 2, 3, 4, 5 will remain 1, 2, 3, 4, 5 in destination topic. Note that this can affect performance.
PreserveOrder bool
// Destination topic prefix. E.g. if message was read from topic "test" and prefix is "dc1_" it'll be written to topic "dc1_test".
TopicPrefix string
// Number of messages that are buffered between the consumer and producer.
ChannelSize int
// Message keys encoder for producer
KeyEncoder Encoder
// Message values encoder for producer
ValueEncoder Encoder
// Message keys decoder for consumer
KeyDecoder Decoder
// Message values decoder for consumer
ValueDecoder Decoder
// Function that generates producer instances
ProducerConstructor ProducerConstructor
// Path to producer configuration, that is responsible for logging timings
// Defines whether add timings to message or not.
// Note: used only for avro encoded messages
TimingsProducerConfig string
}
// Creates an empty MirrorMakerConfig.
func NewMirrorMakerConfig() *MirrorMakerConfig {
return &MirrorMakerConfig{
KeyEncoder: &ByteEncoder{},
ValueEncoder: &ByteEncoder{},
KeyDecoder: &ByteDecoder{},
ValueDecoder: &ByteDecoder{},
ProducerConstructor: NewSaramaProducer,
TimingsProducerConfig: "",
}
}
// MirrorMaker is a tool to mirror source Kafka cluster into a target (mirror) Kafka cluster.
// It uses a Kafka consumer to consume messages from the source cluster, and re-publishes those messages to the target cluster.
type MirrorMaker struct {
config *MirrorMakerConfig
consumers []*Consumer
producers []Producer
messageChannels []chan *Message
timingsProducer Producer
logLineSchema *avro.RecordSchema
evolutioned *schemaSet
errors chan *FailedMessage
}
// Creates a new MirrorMaker using given MirrorMakerConfig.
func NewMirrorMaker(config *MirrorMakerConfig) *MirrorMaker {
var logLineSchema *avro.RecordSchema
if config.TimingsProducerConfig != "" {
logLineSchema = readLoglineSchema()
}
return &MirrorMaker{
config: config,
logLineSchema: logLineSchema,
evolutioned: newSchemaSet(),
errors: make(chan *FailedMessage),
}
}
// Starts the MirrorMaker. This method is blocking and should probably be run in a separate goroutine.
func (this *MirrorMaker) Start() {
this.initializeMessageChannels()
this.startConsumers()
this.startProducers()
}
// Gracefully stops the MirrorMaker.
func (this *MirrorMaker) Stop() {
consumerCloseChannels := make([]<-chan bool, 0)
for _, consumer := range this.consumers {
consumerCloseChannels = append(consumerCloseChannels, consumer.Close())
}
for _, ch := range consumerCloseChannels {
<-ch
}
for _, ch := range this.messageChannels {
close(ch)
}
//TODO maybe drain message channel first?
for _, producer := range this.producers {
producer.Close()
}
}
func (this *MirrorMaker) startConsumers() {
for _, consumerConfigFile := range this.config.ConsumerConfigs {
config, err := ConsumerConfigFromFile(consumerConfigFile)
if err != nil {
panic(err)
}
config.KeyDecoder = this.config.KeyDecoder
config.ValueDecoder = this.config.ValueDecoder
zkConfig, err := ZookeeperConfigFromFile(consumerConfigFile)
if err != nil {
panic(err)
}
config.NumWorkers = 1
config.AutoOffsetReset = SmallestOffset
config.Coordinator = NewZookeeperCoordinator(zkConfig)
config.WorkerFailureCallback = func(_ *WorkerManager) FailedDecision {
return CommitOffsetAndContinue
}
config.WorkerFailedAttemptCallback = func(_ *Task, _ WorkerResult) FailedDecision {
return CommitOffsetAndContinue
}
if this.config.PreserveOrder {
numProducers := this.config.NumProducers
config.Strategy = func(_ *Worker, msg *Message, id TaskId) WorkerResult {
if this.config.TimingsProducerConfig != "" {
consumed := time.Now().Unix()
if record, ok := msg.DecodedValue.(*avro.GenericRecord); ok {
msg.DecodedValue = this.AddTiming(record, "consumed", consumed)
} else {
return NewProcessingFailedResult(id)
}
}
this.messageChannels[topicPartitionHash(msg)%numProducers] <- msg
return NewSuccessfulResult(id)
}
} else {
config.Strategy = func(_ *Worker, msg *Message, id TaskId) WorkerResult {
this.messageChannels[0] <- msg
return NewSuccessfulResult(id)
}
}
consumer := NewConsumer(config)
this.consumers = append(this.consumers, consumer)
if this.config.Whitelist != "" {
go consumer.StartWildcard(NewWhiteList(this.config.Whitelist), this.config.NumStreams)
} else if this.config.Blacklist != "" {
go consumer.StartWildcard(NewBlackList(this.config.Blacklist), this.config.NumStreams)
} else {
panic("Consume pattern not specified")
}
}
}
func (this *MirrorMaker) initializeMessageChannels() {
if this.config.PreserveOrder {
for i := 0; i < this.config.NumProducers; i++ {
this.messageChannels = append(this.messageChannels, make(chan *Message, this.config.ChannelSize))
}
} else {
this.messageChannels = append(this.messageChannels, make(chan *Message, this.config.ChannelSize))
}
}
func (this *MirrorMaker) startProducers() {
if this.config.TimingsProducerConfig != "" {
conf, err := ProducerConfigFromFile(this.config.TimingsProducerConfig)
if err != nil {
panic(err)
}
if this.config.PreservePartitions {
conf.Partitioner = NewFixedPartitioner
} else {
conf.Partitioner = NewRandomPartitioner
}
conf.KeyEncoder = this.config.KeyEncoder
conf.ValueEncoder = this.config.ValueEncoder
this.timingsProducer = this.config.ProducerConstructor(conf)
go this.failedRoutine(this.timingsProducer)
}
for i := 0; i < this.config.NumProducers; i++ {
conf, err := ProducerConfigFromFile(this.config.ProducerConfig)
if err != nil {
panic(err)
}
if this.config.PreservePartitions {
conf.Partitioner = NewFixedPartitioner
} else {
conf.Partitioner = NewRandomPartitioner
}
conf.KeyEncoder = this.config.KeyEncoder
conf.ValueEncoder = this.config.ValueEncoder
if this.config.TimingsProducerConfig != "" {
conf.AckSuccesses = true
}
producer := this.config.ProducerConstructor(conf)
this.producers = append(this.producers, producer)
if this.config.TimingsProducerConfig != "" {
go this.timingsRoutine(producer)
}
go this.failedRoutine(producer)
if this.config.PreserveOrder {
go this.produceRoutine(producer, i)
} else {
go this.produceRoutine(producer, 0)
}
}
}
func (this *MirrorMaker) produceRoutine(producer Producer, channelIndex int) {
partitionEncoder := &Int32Encoder{}
for msg := range this.messageChannels[channelIndex] {
if this.config.TimingsProducerConfig != "" {
preProduce := time.Now().UnixNano()
if record, ok := msg.DecodedValue.(*avro.GenericRecord); ok {
msg.DecodedValue = this.AddTiming(record, "pre-produce", preProduce)
} else {
panic("Failed to decode message")
}
}
if this.config.PreservePartitions {
producer.Input() <- &ProducerMessage{Topic: this.config.TopicPrefix + msg.Topic, Key: uint32(msg.Partition), Value: msg.DecodedValue, KeyEncoder: partitionEncoder}
} else {
producer.Input() <- &ProducerMessage{Topic: this.config.TopicPrefix + msg.Topic, Key: msg.Key, Value: msg.DecodedValue}
}
}
}
func (this *MirrorMaker) timingsRoutine(producer Producer) {
var keyDecoder Decoder
if this.config.PreservePartitions {
keyDecoder = &Int32Decoder{}
} else {
keyDecoder = this.config.KeyDecoder
}
for msg := range producer.Successes() {
decodedKey, err := keyDecoder.Decode(msg.Key.([]byte))
if err != nil {
Errorf(this, "Failed to decode %v", msg.Key)
}
decodedValue, err := this.config.ValueDecoder.Decode(msg.Value.([]byte))
if err != nil {
Errorf(this, "Failed to decode %v", msg.Value)
}
if record, ok := decodedValue.(*avro.GenericRecord); ok {
record = this.AddTiming(record, "post-produce", time.Now().Unix())
if this.config.PreservePartitions {
this.timingsProducer.Input() <- &ProducerMessage{Topic: "timings_" + msg.Topic, Key: int32(decodedKey.(uint32)), Value: record}
} else {
this.timingsProducer.Input() <- &ProducerMessage{Topic: "timings_" + msg.Topic, Key: decodedKey, Value: record}
}
} else {
Errorf(this, "Invalid avro schema type %s", decodedValue)
}
}
}
func (this *MirrorMaker) AddTiming(record *avro.GenericRecord, tag string, now int64) *avro.GenericRecord {
if !this.evolutioned.exists(record.Schema().String()) {
currentSchema := record.Schema().(*avro.RecordSchema)
newSchema := *record.Schema().(*avro.RecordSchema)
for _, newField := range this.logLineSchema.Fields {
var exists bool
for _, currentField := range currentSchema.Fields {
if currentField.Name == newField.Name {
if reflect.DeepEqual(currentField, newField) {
exists = true
break
}
panic(fmt.Sprintf("Incompatible field %s in schema %s", currentField.Name, currentSchema.String()))
}
}
if !exists {
newSchema.Fields = append(newSchema.Fields, newField)
}
}
newRecord := avro.NewGenericRecord(&newSchema)
for _, field := range currentSchema.Fields {
newRecord.Set(field.Name, record.Get(field.Name))
}
record = newRecord
this.evolutioned.add(record.Schema().String())
}
var timings map[string]interface{}
if record.Get("timings") == nil {
timings = make(map[string]interface{})
} else {
timings = record.Get("timings").(map[string]interface{})
}
timings[tag] = now
record.Set("timings", timings)
return record
}
func (this *MirrorMaker) Errors() <-chan *FailedMessage {
return this.errors
}
func readLoglineSchema() *avro.RecordSchema {
file, err := ioutil.ReadFile("logline.avsc")
if err != nil {
panic(err)
}
return avro.MustParseSchema(string(file)).(*avro.RecordSchema)
}
func (this *MirrorMaker) failedRoutine(producer Producer) {
for msg := range producer.Errors() {
this.errors <- msg
}
}
func topicPartitionHash(msg *Message) int {
h := fnv.New32a()
h.Write([]byte(fmt.Sprintf("%s%d", msg.Topic, msg.Partition)))
return int(h.Sum32())
}
type schemaSet struct {
internal map[string]interface{}
}
func newSchemaSet() *schemaSet {
return &schemaSet{
internal: make(map[string]interface{}),
}
}
func (this *schemaSet) add(schema string) {
if _, exists := this.internal[schema]; !exists {
this.internal[schema] = nil
}
}
func (this *schemaSet) exists(schema string) bool {
_, exists := this.internal[schema]
return exists
}