-
Notifications
You must be signed in to change notification settings - Fork 189
/
kafka.go
201 lines (172 loc) · 4.99 KB
/
kafka.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
// Copyright 2020 The klaytn Authors
// This file is part of the klaytn library.
//
// The klaytn library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The klaytn library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the klaytn library. If not, see <http://www.gnu.org/licenses/>.
package kafka
import (
"encoding/json"
"github.com/Shopify/sarama"
"github.com/klaytn/klaytn/common"
"github.com/klaytn/klaytn/log"
)
var logger = log.NewModuleLogger(log.ChainDataFetcher)
const (
// item indices of message header
MsgHeaderTotalSegments = iota
MsgHeaderSegmentIdx
MsgHeaderVersion
MsgHeaderProducerId
MsgHeaderLength
)
const LegacyMsgHeaderLength = 2
const (
KeyTotalSegments = "totalSegments"
KeySegmentIdx = "segmentIdx"
KeyVersion = "version"
KeyProducerId = "producerId"
)
const (
MsgVersion1_0 = "1.0"
)
type IKey interface {
Key() string
}
// Kafka connects to the brokers in an existing kafka cluster.
type Kafka struct {
config *KafkaConfig
producer sarama.SyncProducer
admin sarama.ClusterAdmin
}
func NewKafka(conf *KafkaConfig) (*Kafka, error) {
producer, err := sarama.NewSyncProducer(conf.Brokers, conf.SaramaConfig)
if err != nil {
logger.Error("Failed to create a new producer", "brokers", conf.Brokers)
return nil, err
}
admin, err := sarama.NewClusterAdmin(conf.Brokers, conf.SaramaConfig)
if err != nil {
logger.Error("Failed to create a new cluster admin", "brokers", conf.Brokers)
return nil, err
}
kafka := &Kafka{
config: conf,
producer: producer,
admin: admin,
}
blockGroupTopic := conf.GetTopicName(EventBlockGroup)
if err := kafka.setupTopic(blockGroupTopic); err != nil {
return nil, err
}
traceGroupTopic := conf.GetTopicName(EventTraceGroup)
if err := kafka.setupTopic(traceGroupTopic); err != nil {
return nil, err
}
return kafka, nil
}
func (k *Kafka) setupTopic(topicName string) error {
topics, err := k.ListTopics()
if err != nil {
logger.Error("getting topic has an error", "topicName", topicName, "err", err)
return err
}
if detail, exist := topics[topicName]; exist {
logger.Info("topic configuration", "topicName", topicName, "partition", detail.NumPartitions, "replicas", detail.ReplicationFactor)
return nil
}
if err := k.CreateTopic(topicName); err != nil {
logger.Error("creating a topic is failed", "topicName", topicName, "err", err)
return err
}
return nil
}
func (k *Kafka) Close() {
k.producer.Close()
k.admin.Close()
}
func (k *Kafka) getTopicName(event string) string {
return k.config.GetTopicName(event)
}
func (k *Kafka) CreateTopic(topic string) error {
return k.admin.CreateTopic(topic, &sarama.TopicDetail{
NumPartitions: k.config.Partitions,
ReplicationFactor: k.config.Replicas,
}, false)
}
func (k *Kafka) DeleteTopic(topic string) error {
return k.admin.DeleteTopic(topic)
}
func (k *Kafka) ListTopics() (map[string]sarama.TopicDetail, error) {
return k.admin.ListTopics()
}
func (k *Kafka) split(data []byte) ([][]byte, int) {
size := k.config.SegmentSizeBytes
var segments [][]byte
for len(data) > size {
segments = append(segments, data[:size])
data = data[size:]
}
segments = append(segments, data)
return segments, len(segments)
}
func (k *Kafka) makeProducerMessage(topic, key string, segment []byte, segmentIdx, totalSegments uint64) *sarama.ProducerMessage {
msg := &sarama.ProducerMessage{
Topic: topic,
Key: sarama.StringEncoder(key),
Headers: []sarama.RecordHeader{
{
Key: []byte(KeyTotalSegments),
Value: common.Int64ToByteBigEndian(totalSegments),
},
{
Key: []byte(KeySegmentIdx),
Value: common.Int64ToByteBigEndian(segmentIdx),
},
},
Value: sarama.ByteEncoder(segment),
}
if k.config.MsgVersion == MsgVersion1_0 {
extraHeaders := []sarama.RecordHeader{
{
Key: []byte(KeyVersion),
Value: []byte(k.config.MsgVersion),
},
{
Key: []byte(KeyProducerId),
Value: []byte(k.config.ProducerId),
},
}
msg.Headers = append(msg.Headers, extraHeaders...)
}
return msg
}
func (k *Kafka) Publish(topic string, data interface{}) error {
dataBytes, err := json.Marshal(data)
if err != nil {
return err
}
key := ""
if v, ok := data.(IKey); ok {
key = v.Key()
}
segments, totalSegments := k.split(dataBytes)
for idx, segment := range segments {
msg := k.makeProducerMessage(topic, key, segment, uint64(idx), uint64(totalSegments))
_, _, err = k.producer.SendMessage(msg)
if err != nil {
logger.Error("sending kafka message is failed", "err", err, "segmentIdx", idx, "key", key)
return err
}
}
return err
}