-
Notifications
You must be signed in to change notification settings - Fork 0
/
consumer.go
316 lines (264 loc) · 7.38 KB
/
consumer.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
package main
import (
"bufio"
"fmt"
"io"
"os"
"regexp"
"strings"
"sync"
log "github.com/Sirupsen/logrus"
"github.com/Shopify/sarama"
"github.com/bsm/sarama-cluster"
)
// Consumer TODO: docs
type Consumer interface {
StartConsuming() error
Wait()
GetMsgChan() <-chan *Message
}
// ConsumerFactory TODO: docs
type ConsumerFactory func(conf map[string]string) (Consumer, error)
var consumerFactories = make(map[string]ConsumerFactory)
// Register TODO: docs
func Register(name string, factory ConsumerFactory) {
if factory == nil {
log.Panicf("Consumer factory %s does not exist.", name)
}
_, registered := consumerFactories[name]
if registered {
fmt.Printf("Consumer factory %s already registered. Ignoring.", name)
}
consumerFactories[name] = factory
}
func init() {
Register("kafka", NewKafkaConsumer)
Register("stdin", NewRsyslogConsumer)
}
// CreateConsumer TODO: docs
func CreateConsumer(conf map[string]string) (Consumer, error) {
consumerType, ok := conf["consumer-type"]
if !ok {
consumerType = "kafka"
}
consumerFactory, ok := consumerFactories[consumerType]
if !ok {
// Factory has not been registered.
// Make a list of all available consumer factories for logging.
availableConsumers := make([]string, len(consumerFactories))
for k := range consumerFactories {
availableConsumers = append(availableConsumers, k)
}
return nil, fmt.Errorf("Invalid Consumer type. Must be one of: %s", strings.Join(availableConsumers, ", "))
}
return consumerFactory(conf)
}
// KafkaConsumer TODO: docs
type KafkaConsumer struct {
groupID string
seedBrokers []string
topics []string
exitChannel chan bool
client *cluster.Client
KafkaStatus KafkaStatus
config *cluster.Config
msgChannel chan *Message
consumers map[string]*cluster.Consumer
consumersMutex *sync.Mutex
}
// RsyslogConsumer TODO: docs
type RsyslogConsumer struct {
exitChannel chan bool
consumer *io.Reader
msgChannel chan *Message
}
// KafkaStatus TODO: docs
type KafkaStatus struct {
Brokers []string
Topics []string
// Map: Topic name -> []int32 slice of partitions
TopicPartitions map[string][]int32
}
// NewKafkaStatus TODO: docs
func NewKafkaStatus() KafkaStatus {
c := KafkaStatus{}
c.TopicPartitions = make(map[string][]int32)
return c
}
// NewRsyslogConsumer TODO: docs
func NewRsyslogConsumer(conf map[string]string) (Consumer, error) {
var input io.Reader = os.Stdin
return &RsyslogConsumer{
consumer: &input,
msgChannel: make(chan *Message, 256),
}, nil
}
func read(r *io.Reader) <-chan *string {
lines := make(chan *string)
go func() {
defer close(lines)
scan := bufio.NewScanner(*r)
for scan.Scan() {
s := scan.Text()
lines <- &s
}
}()
return lines
}
// StartConsuming TODO: docs
func (s *RsyslogConsumer) StartConsuming() error {
go func(in <-chan *string, out chan<- *Message) {
for message := range in {
m := &Message{}
m.Data = []byte(*message)
out <- m
}
}(read(s.consumer), s.msgChannel)
log.Printf("Started consuming rsyslog\n")
return nil
}
// GetMsgChan TODO: docs
func (s *RsyslogConsumer) GetMsgChan() <-chan *Message {
return s.msgChannel
}
// GetMsgChan TODO: docs
func (s *KafkaConsumer) GetMsgChan() <-chan *Message {
return s.msgChannel
}
// Wait TODO: docs
func (s *RsyslogConsumer) Wait() {
<-s.exitChannel
return
}
// NewKafkaConsumer TODO: docs
func NewKafkaConsumer(conf map[string]string) (Consumer, error) {
brokerstring, ok := conf["brokers"]
if !ok {
return nil, fmt.Errorf("%s is required for the Kafka consumer", "brokers")
}
topicString, ok := conf["topics"]
if !ok {
return nil, fmt.Errorf("%s is required for the Kafka consumer", "topics")
}
brokers := strings.Split(brokerstring, ",")
topics := strings.Split(topicString, ",")
groupid, _ := conf["groupid"]
consumers := make(map[string]*cluster.Consumer)
kafkaStatus, topicsMetadata, err := FetchKafkaMetadata(brokers, topics)
if err != nil {
return nil, fmt.Errorf("Failed to initialize Kafka metadata")
}
kafkaConfig := cluster.NewConfig()
kafkaConfig.Group.Return.Notifications = true
kafkaConfig.Consumer.Return.Errors = true
kafkaConfig.Consumer.Offsets.Initial = sarama.OffsetOldest
client, err := cluster.NewClient(kafkaStatus.Brokers, kafkaConfig)
if err != nil {
return nil, fmt.Errorf("error creating new kafka client: %v", err)
}
if kafkaConfig.Validate() != nil {
return nil, fmt.Errorf("error validating kafka config")
}
return &KafkaConsumer{
groupID: groupid,
seedBrokers: brokers,
topics: topicsMetadata,
msgChannel: make(chan *Message, 256),
config: kafkaConfig,
KafkaStatus: kafkaStatus,
client: client,
consumers: consumers,
}, nil
}
// StartConsuming TODO: docs
func (s *KafkaConsumer) StartConsuming() error {
consumer, err := cluster.NewConsumerFromClient(s.client, s.groupID, s.topics)
if err != nil {
fmt.Printf("Error on StartConsumingTopic for topic %s: %+v\n", s.topics, err)
return err
}
go func(notifications <-chan *cluster.Notification) {
for notification := range notifications {
fmt.Printf("Notifications: %+v\n", notification)
}
}(consumer.Notifications())
go func(in <-chan *sarama.ConsumerMessage, out chan<- *Message) {
for message := range in {
m := &Message{}
m.Key = string(message.Key)
m.Topic = message.Topic
m.Partition = message.Partition
m.Data = message.Value
out <- m
consumer.MarkOffset(message, "")
}
}(consumer.Messages(), s.msgChannel)
// Add return channel here to consume successful message submit
/*
go func(return <-chan *Message) {
for message := range return {
m.Offset =
consumer.MarkOffset(, "")
}
}
*/
go func(in <-chan error) {
for error := range in {
fmt.Printf("Errors: %s\n", error.Error())
}
}(consumer.Errors())
fmt.Printf("Started consuming topic %s\n", s.topics)
return nil
}
// Wait TODO: docs
func (s *KafkaConsumer) Wait() {
<-s.exitChannel
}
// connects to on of a list of brokers
func connectToBroker(config *sarama.Config, seed_brokers []string) (*sarama.Broker, error) {
var err error
for _, host := range seed_brokers {
broker := sarama.NewBroker(host)
err = broker.Open(config)
if err != nil {
log.Errorf("error connecting to broker: %s %v", host, err)
} else {
return broker, nil
}
}
return nil, err
}
// FetchKafkaMetadata connects to the broker and fetches current brokers' address and partition ids
func FetchKafkaMetadata(seedBrokers, topics []string) (KafkaStatus, []string, error) {
kf := NewKafkaStatus()
found := []string{}
config := sarama.NewConfig()
broker, err := connectToBroker(config, seedBrokers)
if err != nil {
return kf, nil, err
}
request := sarama.MetadataRequest{}
response, err := broker.GetMetadata(&request)
if err != nil {
_ = broker.Close()
return kf, nil, err
}
if len(response.Brokers) == 0 {
return kf, nil, fmt.Errorf("Unable to find any brokers")
}
for _, broker := range response.Brokers {
kf.Brokers = append(kf.Brokers, broker.Addr())
}
fmt.Printf("Brokers: %+v\n", kf.Brokers)
regexpFilter := regexp.MustCompile(strings.Join(topics, "|"))
for _, topic := range response.Topics {
if regexpFilter.MatchString(topic.Name) {
found = append(found, topic.Name)
kf.Topics = append(kf.Topics, topic.Name)
for _, partition := range topic.Partitions {
kf.TopicPartitions[topic.Name] = append(kf.TopicPartitions[topic.Name], partition.ID)
}
}
}
return kf, found, broker.Close()
}