forked from adbys/kafka-connector
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
226 lines (186 loc) · 5.4 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
// Copyright (c) Alex Ellis 2017. All rights reserved.
// Copyright (c) OpenFaaS Project 2018. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package main
import (
"fmt"
"log"
"math"
"os"
"strings"
"time"
"github.com/Shopify/sarama"
cluster "github.com/bsm/sarama-cluster"
"github.com/openfaas-incubator/connector-sdk/types"
)
var saramaKafkaProtocolVersion = sarama.V0_10_2_0
type authConfig struct {
Username string
Password string
}
type connectorConfig struct {
*types.ControllerConfig
Topics []string
Broker string
AuthConfig *authConfig
}
const (
DEFAULT_KAFKA_PORT = "9092"
)
func main() {
credentials := types.GetCredentials()
config := buildConnectorConfig()
controller := types.NewController(credentials, config.ControllerConfig)
controller.BeginMapBuilder()
brokers := strings.Split(config.Broker, ",")
waitForBrokers(brokers, config, controller)
makeConsumer(brokers, config, controller)
}
func waitForBrokers(brokers []string, config connectorConfig, controller *types.Controller) {
var client sarama.Client
var err error
cfg := sarama.NewConfig()
cfg.Version = saramaKafkaProtocolVersion
if config.AuthConfig != nil {
cfg.Net.SASL.Enable = true
cfg.Net.SASL.User = config.AuthConfig.Username
cfg.Net.SASL.Password = config.AuthConfig.Password
}
for {
if len(controller.Topics()) > 0 {
client, err = sarama.NewClient(brokers, cfg)
if client != nil && err == nil {
break
}
if client != nil {
client.Close()
}
fmt.Println(err)
fmt.Println("Wait for brokers ("+config.Broker+") to come up.. ", brokers)
}
time.Sleep(1 * time.Second)
}
}
func makeConsumer(brokers []string, config connectorConfig, controller *types.Controller) {
//setup consumer
cConfig := cluster.NewConfig()
cConfig.Version = saramaKafkaProtocolVersion
cConfig.Consumer.Return.Errors = true
cConfig.Consumer.Offsets.Initial = sarama.OffsetNewest //OffsetOldest
cConfig.Group.Return.Notifications = true
cConfig.Group.Session.Timeout = 6 * time.Second
cConfig.Group.Heartbeat.Interval = 2 * time.Second
if config.AuthConfig != nil {
cConfig.Net.SASL.Enable = true
cConfig.Net.SASL.User = config.AuthConfig.Username
cConfig.Net.SASL.Password = config.AuthConfig.Password
}
group := "faas-kafka-queue-workers"
topics := config.Topics
log.Printf("Binding to topics: %v", config.Topics)
consumer, err := cluster.NewConsumer(brokers, group, topics, cConfig)
if err != nil {
log.Fatalln("Fail to create Kafka consumer: ", err)
}
defer consumer.Close()
num := 0
for {
select {
case msg, ok := <-consumer.Messages():
if ok {
num = (num + 1) % math.MaxInt32
fmt.Printf("[#%d] Received on [%v,%v]: '%s'\n",
num,
msg.Topic,
msg.Partition,
string(msg.Value))
controller.Invoke(msg.Topic, &msg.Value)
consumer.MarkOffset(msg, "") // mark message as processed
}
case err = <-consumer.Errors():
fmt.Println("consumer error: ", err)
case ntf := <-consumer.Notifications():
fmt.Printf("Rebalanced: %+v\n", ntf)
}
}
}
func buildConnectorConfig() connectorConfig {
broker := "kafka:9092"
if val, exists := os.LookupEnv("broker_host"); exists {
broker = val
}
consumerUsername := ""
if val, exists := os.LookupEnv("consumer_username"); exists {
consumerUsername = val
}
consumerPassword := ""
if val, exists := os.LookupEnv("consumer_password"); exists {
consumerPassword = val
}
ac := &authConfig{}
if consumerUsername != "" && consumerPassword != "" {
ac.Username = consumerUsername
ac.Password = consumerPassword
}
topics := []string{}
if val, exists := os.LookupEnv("topics"); exists {
for _, topic := range strings.Split(val, ",") {
if len(topic) > 0 {
topics = append(topics, topic)
}
}
}
if len(topics) == 0 {
log.Fatal(`Provide a list of topics i.e. topics="payment_published,slack_joined"`)
}
gatewayURL := "http://gateway:8080"
if val, exists := os.LookupEnv("gateway_url"); exists {
gatewayURL = val
}
upstreamTimeout := time.Second * 30
rebuildInterval := time.Second * 3
if val, exists := os.LookupEnv("upstream_timeout"); exists {
parsedVal, err := time.ParseDuration(val)
if err == nil {
upstreamTimeout = parsedVal
}
}
if val, exists := os.LookupEnv("rebuild_interval"); exists {
parsedVal, err := time.ParseDuration(val)
if err == nil {
rebuildInterval = parsedVal
}
}
printResponse := false
if val, exists := os.LookupEnv("print_response"); exists {
printResponse = (val == "1" || val == "true")
}
printResponseBody := false
if val, exists := os.LookupEnv("print_response_body"); exists {
printResponseBody = (val == "1" || val == "true")
}
delimiter := ","
if val, exists := os.LookupEnv("topic_delimiter"); exists {
if len(val) > 0 {
delimiter = val
}
}
asynchronousInvocation := false
if val, exists := os.LookupEnv("asynchronous_invocation"); exists {
asynchronousInvocation = (val == "1" || val == "true")
}
return connectorConfig{
ControllerConfig: &types.ControllerConfig{
UpstreamTimeout: upstreamTimeout,
GatewayURL: gatewayURL,
PrintResponse: printResponse,
PrintResponseBody: printResponseBody,
RebuildInterval: rebuildInterval,
TopicAnnotationDelimiter: delimiter,
AsyncFunctionInvocation: asynchronousInvocation,
},
Topics: topics,
Broker: broker,
AuthConfig: ac,
}
}