-
Notifications
You must be signed in to change notification settings - Fork 71
/
consumers.go
248 lines (213 loc) · 6.86 KB
/
consumers.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
package kafka
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/RedHatInsights/chrome-service-backend/config"
"github.com/RedHatInsights/chrome-service-backend/rest/cloudevents"
"github.com/RedHatInsights/chrome-service-backend/rest/connectionhub"
"github.com/google/uuid"
clowder "github.com/redhatinsights/app-common-go/pkg/api/v1"
"github.com/segmentio/kafka-go"
"github.com/segmentio/kafka-go/sasl"
"github.com/segmentio/kafka-go/sasl/plain"
"github.com/segmentio/kafka-go/sasl/scram"
"github.com/sirupsen/logrus"
)
type kafkaConsumer struct {
Topics []string
Readers map[string]*kafka.Reader
}
var Consumer = kafkaConsumer{}
const (
TenMb = 10e7
saslPlain = "plain"
scramSha256 = "scram-sha-256"
scramSha512 = "scram-sha-512"
)
var SaslMechanism sasl.Mechanism
var Dialer *kafka.Dialer
var TlsConfig *tls.Config
func CreateSaslMechanism(saslConfig *clowder.KafkaSASLConfig) (sasl.Mechanism, error) {
if SaslMechanism != nil {
return SaslMechanism, nil
}
if saslConfig == nil {
return nil, errors.New("could not create a Sasl mechanism for Kafka: the Sasl configuration settings are empty")
}
if saslConfig.SaslMechanism == nil || *saslConfig.SaslMechanism == "" {
return nil, errors.New("could not create a Sasl mechanism for Kafka: the Sasl mechanism is empty")
}
if saslConfig.Username == nil {
return nil, errors.New("could not create a Sasl mechanism for Kafka: the Sasl username is nil")
}
if saslConfig.Password == nil {
return nil, errors.New("could not create a Sasl mechanism for Kafka: the Sasl password is nil")
}
var algorithm scram.Algorithm
switch strings.ToLower(*saslConfig.SaslMechanism) {
case saslPlain:
return plain.Mechanism{Username: *saslConfig.Username, Password: *saslConfig.Password}, nil
case scramSha256:
algorithm = scram.SHA256
case scramSha512:
algorithm = scram.SHA512
default:
return nil, fmt.Errorf(`unable to configure Sasl mechanism "%s" for Kafka`, *saslConfig.SaslMechanism)
}
mechanism, err := scram.Mechanism(algorithm, *saslConfig.Username, *saslConfig.Password)
if err != nil {
return nil, fmt.Errorf(`unable to generate "%s" mechanism with the "%v" algorithm: %s`, *saslConfig.SaslMechanism, algorithm, err)
}
SaslMechanism = mechanism
return SaslMechanism, nil
}
func createTLSConfig(caContents *string) *tls.Config {
if TlsConfig != nil {
return TlsConfig
}
tlsConfig := &tls.Config{
MinVersion: tls.VersionTLS12,
}
// The managed Kafka instance may have a self-signed certificate, and in those cases we must be able to support the
// connection too.
if caContents != nil && *caContents != "" {
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM([]byte(*caContents))
tlsConfig.RootCAs = certPool
}
TlsConfig = tlsConfig
return TlsConfig
}
func createDialer(config *clowder.BrokerConfig) (*kafka.Dialer, error) {
if Dialer != nil {
return Dialer, nil
}
if config == nil {
return nil, errors.New(`could not create a dialer for Kafka: the passed configuration is empty`)
}
if config.Sasl == nil {
return nil, errors.New(`could not create a dialer for Kafka: the passed configuration is missing the Sasl settings`)
}
tlsConfig := createTLSConfig(config.Cacert)
mechanism, err := CreateSaslMechanism(config.Sasl)
if err != nil {
return nil, fmt.Errorf(`unable to create the Sasl mechanism for the dialer: %w`, err)
}
Dialer = &kafka.Dialer{
DualStack: true,
SASLMechanism: mechanism,
Timeout: 10 * time.Second,
TLS: tlsConfig,
}
return Dialer, nil
}
func createReader(topic string) *kafka.Reader {
cfg := config.Get()
hostname, err := os.Hostname()
if err != nil {
logrus.Errorln("Couldn't get hostname, using UUID")
hostname = uuid.NewString()
}
dialer := &kafka.Dialer{
Timeout: 10 * time.Second,
DualStack: true,
}
mechanism, err := CreateSaslMechanism(cfg.KafkaConfig.BrokerConfig.Sasl)
if cfg.KafkaConfig.BrokerConfig.Authtype != nil {
dialer, err = createDialer(&cfg.KafkaConfig.BrokerConfig)
if err != nil {
logrus.Errorln("Couldn't create dialer for Kafka: ", err)
}
}
if err == nil {
dialer.SASLMechanism = mechanism
} else {
logrus.Errorln("Couldn't create SASL mechanism for Kafka: ", err)
}
r := kafka.NewReader(kafka.ReaderConfig{
Brokers: cfg.KafkaConfig.KafkaBrokers,
// The consumer group will match the pod name via hostname
// ex platform.chrome.chrome-service-api.<deployHash>.<podHash>
GroupID: fmt.Sprintf("platform.chrome.%s", hostname),
StartOffset: kafka.LastOffset,
Topic: topic,
Logger: kafka.LoggerFunc(logrus.Debugf),
ErrorLogger: kafka.LoggerFunc(logrus.Errorf),
MaxBytes: TenMb,
Dialer: dialer,
})
logrus.Infoln("Creating new kafka reader for topic:", topic)
return r
}
func InitializeConsumers() {
cfg := config.Get()
topics := cfg.KafkaConfig.KafkaTopics
readers := make(map[string]*kafka.Reader)
for _, topic := range topics {
readers[topic] = createReader(topic)
}
Consumer.Readers = readers
for _, r := range readers {
go startKafkaReader(r)
}
}
func startKafkaReader(r *kafka.Reader) {
defer r.Close()
for {
logrus.Infoln("Reading from ", r.Config().Topic)
m, err := r.ReadMessage(context.Background())
if err != nil {
logrus.Errorln("Error reading message: ", err)
break
}
logrus.Infoln(fmt.Sprintf("message at offset %d: %s = %s\n", m.Offset, string(m.Key), string(m.Value)))
var p cloudevents.KafkaEnvelope
err = json.Unmarshal(m.Value, &p)
if err != nil {
logrus.Errorln(fmt.Sprintf("Unable to unmarshal message %s\n", string(m.Value)))
} else if p.Data.Payload == nil {
logrus.Errorln(fmt.Sprintf("No message will be emitted due to missing payload %s! Message might not follow cloud events spec.\n", string(m.Value)))
} else {
event := cloudevents.WrapPayload(p.Data.Payload, p.Source, p.Id, p.Type)
event.Time = p.Time
data, err := json.Marshal(event)
if err != nil {
log.Println("Unable to marshal payload data", p, err)
} else {
validateErr := cloudevents.ValidatePayload(p)
if validateErr == nil {
newMessage := connectionhub.Message{
Destinations: connectionhub.MessageDestinations{
Users: p.Data.Users,
Roles: p.Data.Roles,
Organizations: p.Data.Organizations,
Usernames: p.Data.Usernames,
},
Broadcast: p.Data.Broadcast,
Data: data,
}
if p.Data.Broadcast {
logrus.Infoln("Emitting new broadcast message from kafka reader: ", string(newMessage.Data))
connectionhub.ConnectionHub.Broadcast <- newMessage
} else {
logrus.Infoln("Emitting new message from kafka reader: ", string(newMessage.Data))
connectionhub.ConnectionHub.Emit <- newMessage
}
} else {
logrus.Errorln(validateErr)
}
}
}
}
if err := r.Close(); err != nil {
log.Fatal("failed to close reader:", err)
}
}