-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
232 lines (184 loc) · 5.37 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
package main
import (
"context"
"log"
"os"
"os/signal"
"strconv"
"strings"
"time"
"github.com/IBM/sarama"
"github.com/bas-baskara/kafka-consumer-grpc/configs"
pb "github.com/bas-baskara/kafka-consumer-grpc/protobuf"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/protobuf/types/known/timestamppb"
)
var env = configs.EnvGetter()
var initialTopics []string
func initClientGrpc() (*pb.ListenMessagesClient, *grpc.ClientConn, error) {
var opts []grpc.DialOption
if env.GRPC_DIAL_OPTION == "insecure" {
opts = append(opts, grpc.WithInsecure())
} else {
creds, err := credentials.NewClientTLSFromFile(env.CERT_FILE_PATH, "")
if err != nil {
log.Fatalf("Failed to create TLS credentials: %v", err)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
}
conn, err := grpc.Dial(env.GRPC_ADDRESS, opts...)
if err != nil {
log.Fatal("Failed to dial server:", err)
return nil, nil, err
}
client := pb.NewListenMessagesClient(conn)
log.Println("grpc connection was started...")
return &client, conn, nil
}
func main() {
// initialize grpc client
client, conn, err := initClientGrpc()
if err != nil {
log.Fatalf("Failed to initialize gRPC client: %v", err)
}
defer conn.Close()
// kafka broker addresses
brokers := strings.Split(env.KAFKA_BROKER, ",")
// Create configuration
config := sarama.NewConfig()
config.Consumer.Return.Errors = true
// Create consumer
consumer, err := sarama.NewConsumer(brokers, config)
if err != nil {
panic(err)
}
defer func() {
if err := consumer.Close(); err != nil {
log.Println("Error closing kafka consumer:", err)
}
}()
topics, err := consumer.Topics()
if err != nil {
log.Println("Error getting topics", err)
}
initialTopics = topics
// Trap SIGINT to trigger a graceful shutdown
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
// create channel
messageChan := make(chan *sarama.ConsumerMessage)
// consume all initial topics available
go consumeAllTopics(consumer, messageChan)
// start worker
workerNumber, err := strconv.Atoi(env.KAFKA_WORKER_POOL_NUMBER)
if err != nil {
log.Fatal("Worker number not set:", err)
return
}
for i := 0; i < workerNumber; i++ {
go worker(messageChan, *client)
}
// Periodically check for new topics and consume messages
tickerInterval := 10
tickerSecond, err := strconv.Atoi(env.KAFKA_TICKER_SECOND)
if err != nil {
log.Println("Error getting ticker interval in seconds", err)
} else {
tickerInterval = tickerSecond
}
go func(tickerInterval int) {
ticker := time.NewTicker(time.Duration(tickerInterval) * time.Second)
defer ticker.Stop()
for range ticker.C {
newConsumer, err := sarama.NewConsumer(brokers, config)
if err != nil {
log.Println("error when create new consumer connection", err)
}
newTopics, err := newConsumer.Topics()
if err != nil {
log.Println("Error getting topics in interval:", err)
newConsumer.Close()
continue
}
for _, newTopic := range newTopics {
if !containsTopic(initialTopics, newTopic) {
initialTopics = append(initialTopics, newTopic)
go consumeTopic(newTopic, consumer, messageChan)
}
}
if err := newConsumer.Close(); err != nil {
log.Println("Error closing new consumer in interval:", err)
}
}
}(tickerInterval)
// wait for shutdown signal
<-signals
log.Println("Shutdown signal received. Exiting...")
}
func containsTopic(topics []string, topic string) bool {
for _, t := range topics {
if t == topic {
return true
}
}
return false
}
func worker(messages <-chan *sarama.ConsumerMessage, client pb.ListenMessagesClient) {
ctx := context.Background()
for msg := range messages {
timestamp := timestamppb.New(msg.Timestamp)
res, err := client.HandleIncomingMessage(ctx, &pb.IncomingMessage{
Topic: msg.Topic,
Value: msg.Value,
Timestamp: timestamp,
Key: string(msg.Key),
})
if err != nil {
log.Println("error when client handle incoming message", err)
continue
}
log.Printf("client successfully handle incoming message: %v", res)
}
}
func consumeAllTopics(consumer sarama.Consumer, messageChan chan *sarama.ConsumerMessage) {
// subscribe to all topics
topics, err := consumer.Topics()
if err != nil {
log.Println("Error getting topics:", err)
return
}
for _, topic := range topics {
go consumeTopic(topic, consumer, messageChan)
}
}
func consumeTopic(topic string, consumer sarama.Consumer, messageChan chan<- *sarama.ConsumerMessage) {
partitions, err := consumer.Partitions(topic)
if err != nil {
log.Printf("error getting partitions for topic %s: %v", topic, err)
return
}
for _, partition := range partitions {
go func(topic string, partition int32) {
partitionConsumer, err := consumer.ConsumePartition(topic, partition, sarama.OffsetNewest)
if err != nil {
log.Printf("error creating partition consumer for topic %s, partition %d: %v", topic, partition, err)
return
}
defer func() {
if err := partitionConsumer.Close(); err != nil {
log.Printf("Error closing partition consumer for topic %s, partition %d: %v", topic, partition, err)
}
}()
// process message
for {
select {
case msg := <-partitionConsumer.Messages():
messageChan <- msg
case err := <-partitionConsumer.Errors():
log.Printf("Error consuming message: %v", err)
}
}
}(topic, partition)
}
}