-
Notifications
You must be signed in to change notification settings - Fork 29
/
main.go
391 lines (334 loc) · 11.5 KB
/
main.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
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/Shopify/sarama"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/fission/keda-connectors/common"
)
// Following code snippet is from KEDA project and adapted for Fission.
// Copyright 2020 The KEDA Authors.
// and others that have contributed code to the public domain.
// Licensed under the Apache License, Version 2.0 (the "License");
// https://github.com/kedacore/keda/blob/v1.5.0/LICENSE
// https://github.com/kedacore/keda/blob/v1.5.0/pkg/scalers/kafka_scaler.go#L28
type kafkaMetadata struct {
bootstrapServers []string
consumerGroup string
// auth
authMode kafkaAuthMode
username string
password string
// ssl
cert string
key string
ca string
}
type kafkaAuthMode string
const (
kafkaAuthModeNone kafkaAuthMode = "none"
kafkaAuthModeSaslPlaintext kafkaAuthMode = "sasl_plaintext"
kafkaAuthModeSaslScramSha256 kafkaAuthMode = "sasl_scram_sha256"
kafkaAuthModeSaslScramSha512 kafkaAuthMode = "sasl_scram_sha512"
kafkaAuthModeSaslSSL kafkaAuthMode = "sasl_ssl"
kafkaAuthModeSaslSSLPlain kafkaAuthMode = "sasl_ssl_plain"
)
// https://github.com/kedacore/keda/blob/v1.5.0/pkg/scalers/kafka_scaler.go#L83
func parseKafkaMetadata(logger *zap.Logger) (kafkaMetadata, error) {
meta := kafkaMetadata{}
// brokerList marked as deprecated, bootstrapServers is the new one to use
if os.Getenv("BROKER_LIST") != "" && os.Getenv("BOOTSTRAP_SERVERS") != "" {
return meta, errors.New("cannot specify both bootstrapServers and brokerList (deprecated)")
}
if os.Getenv("BROKER_LIST") == "" && os.Getenv("BOOTSTRAP_SERVERS") == "" {
return meta, errors.New("no bootstrapServers or brokerList (deprecated) given")
}
if os.Getenv("BOOTSTRAP_SERVERS") != "" {
meta.bootstrapServers = strings.Split(os.Getenv("BOOTSTRAP_SERVERS"), ",")
}
if os.Getenv("BROKER_LIST") != "" {
logger.Info("WARNING: usage of brokerList is deprecated. use bootstrapServers instead.")
meta.bootstrapServers = strings.Split(os.Getenv("BROKER_LIST"), ",")
}
if os.Getenv("CONSUMER_GROUP") == "" {
return meta, errors.New("No consumerGroup given")
}
meta.consumerGroup = os.Getenv("CONSUMER_GROUP")
meta.authMode = kafkaAuthModeNone
mode := kafkaAuthMode(strings.TrimSpace((os.Getenv("AUTH_MODE"))))
if mode == "" {
mode = kafkaAuthModeNone
}
if mode != kafkaAuthModeNone && mode != kafkaAuthModeSaslPlaintext && mode != kafkaAuthModeSaslSSL && mode != kafkaAuthModeSaslSSLPlain && mode != kafkaAuthModeSaslScramSha256 && mode != kafkaAuthModeSaslScramSha512 {
return meta, fmt.Errorf("err auth mode %s given", mode)
}
meta.authMode = mode
if meta.authMode != kafkaAuthModeNone && meta.authMode != kafkaAuthModeSaslSSL {
if os.Getenv("USERNAME") == "" {
return meta, errors.New("no username given")
}
meta.username = strings.TrimSpace(os.Getenv("USERNAME"))
if os.Getenv("PASSWORD") == "" {
return meta, errors.New("no password given")
}
meta.password = strings.TrimSpace(os.Getenv("PASSWORD"))
}
if meta.authMode == kafkaAuthModeSaslSSL {
if os.Getenv("CA") == "" {
return meta, errors.New("no ca given")
}
meta.ca = os.Getenv("CA")
if os.Getenv("CERT") == "" {
return meta, errors.New("no cert given")
}
meta.cert = os.Getenv("CERT")
if os.Getenv("KEY") == "" {
return meta, errors.New("no key given")
}
meta.key = os.Getenv("KEY")
}
return meta, nil
}
// End of code snippet from KEDA project.
func getConfig(metadata kafkaMetadata) (*sarama.Config, error) {
config := sarama.NewConfig()
config.Version = sarama.V1_0_0_0
if ok := metadata.authMode == kafkaAuthModeSaslPlaintext || metadata.authMode == kafkaAuthModeSaslSSLPlain || metadata.authMode == kafkaAuthModeSaslScramSha256 || metadata.authMode == kafkaAuthModeSaslScramSha512; ok {
config.Net.SASL.Enable = true
config.Net.SASL.User = metadata.username
config.Net.SASL.Password = metadata.password
}
if metadata.authMode == kafkaAuthModeSaslSSLPlain {
config.Net.SASL.Mechanism = sarama.SASLMechanism(sarama.SASLTypePlaintext)
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
ClientAuth: 0,
}
config.Net.TLS.Enable = true
config.Net.TLS.Config = tlsConfig
config.Net.DialTimeout = 10 * time.Second
}
if metadata.authMode == kafkaAuthModeSaslSSL {
cert, err := tls.X509KeyPair([]byte(metadata.cert), []byte(metadata.key))
if err != nil {
return nil, fmt.Errorf("error parse X509KeyPair: %s", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM([]byte(metadata.ca))
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
config.Net.TLS.Enable = true
config.Net.TLS.Config = tlsConfig
}
if metadata.authMode == kafkaAuthModeSaslScramSha256 {
config.Net.SASL.SCRAMClientGeneratorFunc = func() sarama.SCRAMClient { return &XDGSCRAMClient{HashGeneratorFcn: SHA256} }
config.Net.SASL.Mechanism = sarama.SASLMechanism(sarama.SASLTypeSCRAMSHA256)
}
if metadata.authMode == kafkaAuthModeSaslScramSha512 {
config.Net.SASL.SCRAMClientGeneratorFunc = func() sarama.SCRAMClient { return &XDGSCRAMClient{HashGeneratorFcn: SHA512} }
config.Net.SASL.Mechanism = sarama.SASLMechanism(sarama.SASLTypeSCRAMSHA512)
}
if metadata.authMode == kafkaAuthModeSaslPlaintext {
config.Net.SASL.Mechanism = sarama.SASLTypePlaintext
config.Net.TLS.Enable = true
}
return config, nil
}
// kafkaConnector represents a Sarama consumer group consumer
type kafkaConnector struct {
ready chan bool
logger *zap.Logger
producer sarama.SyncProducer
connectorData common.ConnectorMetadata
}
// Setup is run at the beginning of a new session, before ConsumeClaim
func (conn *kafkaConnector) Setup(sarama.ConsumerGroupSession) error {
close(conn.ready)
return nil
}
// Cleanup is run at the end of a session, once all ConsumeClaim goroutines have exited
func (conn *kafkaConnector) Cleanup(sarama.ConsumerGroupSession) error {
return nil
}
// ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages()
func (conn *kafkaConnector) ConsumeClaim(session sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
// NOTE:
// Do not move the code below to a goroutine.
// The `ConsumeClaim` itself is called within a goroutine, see:
// https://github.com/Shopify/sarama/blob/master/consumer_group.go#L27-L29
for message := range claim.Messages() {
conn.logger.Info(fmt.Sprintf("Message claimed: value = %s, timestamp = %v, topic = %s", string(message.Value), message.Timestamp, message.Topic))
msg := string(message.Value)
headers := http.Header{
"KEDA-Topic": {conn.connectorData.Topic},
"KEDA-Response-Topic": {conn.connectorData.ResponseTopic},
"KEDA-Error-Topic": {conn.connectorData.ErrorTopic},
"Content-Type": {conn.connectorData.ContentType},
"KEDA-Source-Name": {conn.connectorData.SourceName},
}
// Set the headers came from Kafka record
for _, h := range message.Headers {
headers.Add(string(h.Key), string(h.Value))
}
resp, err := common.HandleHTTPRequest(msg, headers, conn.connectorData, conn.logger)
if err != nil {
conn.errorHandler(err)
} else {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
conn.errorHandler(err)
} else {
// Generate Kafka record headers
var kafkaRecordHeaders []sarama.RecordHeader
for k, v := range resp.Header {
// One key may have multiple values
for _, v := range v {
kafkaRecordHeaders = append(kafkaRecordHeaders, sarama.RecordHeader{Key: []byte(k), Value: []byte(v)})
}
}
if success := conn.responseHandler(string(body), kafkaRecordHeaders); success {
session.MarkMessage(message, "")
}
}
}
}
return nil
}
func (conn *kafkaConnector) errorHandler(err error) {
if len(conn.connectorData.ErrorTopic) > 0 {
_, _, e := conn.producer.SendMessage(&sarama.ProducerMessage{
Topic: conn.connectorData.ErrorTopic,
Value: sarama.StringEncoder(err.Error()),
})
if e != nil {
conn.logger.Error("failed to publish message to error topic",
zap.Error(e),
zap.String("source", conn.connectorData.SourceName),
zap.String("message", err.Error()),
zap.String("topic", conn.connectorData.Topic))
}
} else {
conn.logger.Error("message received to publish to error topic, but no error topic was set",
zap.String("message", err.Error()),
zap.String("source", conn.connectorData.SourceName),
zap.String("http endpoint", conn.connectorData.HTTPEndpoint),
)
}
}
func (conn *kafkaConnector) responseHandler(msg string, headers []sarama.RecordHeader) bool {
if len(conn.connectorData.ResponseTopic) > 0 {
_, _, err := conn.producer.SendMessage(&sarama.ProducerMessage{
Topic: conn.connectorData.ResponseTopic,
Value: sarama.StringEncoder(msg),
Headers: headers,
})
if err != nil {
conn.logger.Warn("failed to publish response body from http request to topic",
zap.Error(err),
zap.String("topic", conn.connectorData.Topic),
zap.String("source", conn.connectorData.SourceName),
zap.String("http endpoint", conn.connectorData.HTTPEndpoint))
return false
}
}
return true
}
func getProducer(metadata kafkaMetadata) (sarama.SyncProducer, error) {
config, err := getConfig(metadata)
if err != nil {
return nil, err
}
config.Producer.RequiredAcks = sarama.WaitForAll
config.Producer.Retry.Max = 10
config.Producer.Return.Successes = true
producer, err := sarama.NewSyncProducer(metadata.bootstrapServers, config)
if err != nil {
return nil, err
}
return producer, nil
}
func main() {
logger, err := zap.NewProduction()
if err != nil {
log.Fatalf("can't initialize zap logger: %v", err)
}
defer logger.Sync()
metadata, err := parseKafkaMetadata(logger)
if err != nil {
logger.Error("Failed to fetch kafka metadata", zap.Error(err))
return
}
connData, err := common.ParseConnectorMetadata()
if err != nil {
logger.Error("Failed to parse connector meta data", zap.Error(err))
return
}
config, err := getConfig(metadata)
if err != nil {
logger.Error("Failed to create kafka config", zap.Error(err))
return
}
producer, err := getProducer(metadata)
if err != nil {
logger.Error("Failed to create kafka producer", zap.Error(err))
return
}
defer producer.Close()
conn := kafkaConnector{
ready: make(chan bool),
logger: logger,
producer: producer,
connectorData: connData,
}
ctx, cancel := context.WithCancel(context.Background())
client, err := sarama.NewConsumerGroup(metadata.bootstrapServers, metadata.consumerGroup, config)
if err != nil {
logger.Error("Error creating consumer group client", zap.Error(err))
return
}
wg := &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for {
if err := client.Consume(ctx, []string{connData.Topic}, &conn); err != nil {
logger.Error("Error from consumer", zap.Error(err))
}
// check if context was cancelled, signaling that the consumer should stop
if ctx.Err() != nil {
return
}
conn.ready = make(chan bool)
}
}()
<-conn.ready // Await till the consumer has been set up
logger.Info("Sarama consumer up and running!...")
sigterm := make(chan os.Signal, 1)
signal.Notify(sigterm, syscall.SIGINT, syscall.SIGTERM)
select {
case <-ctx.Done():
logger.Info("terminating: context cancelled")
case <-sigterm:
logger.Info("terminating: via signal")
}
cancel()
wg.Wait()
if err = client.Close(); err != nil {
logger.Error("Error closing client", zap.Error(err))
}
}