forked from pingcap/tidb-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
232 lines (197 loc) · 5.29 KB
/
reader.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
// Copyright 2018 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package reader
import (
"time"
"github.com/Shopify/sarama"
"github.com/pingcap/errors"
"github.com/pingcap/log"
pb "github.com/pingcap/tidb-tools/tidb-binlog/slave_binlog_proto/go-binlog"
"go.uber.org/zap"
)
const (
KafkaReadTimeout = 10 * time.Minute
KafkaWaitTimeout = 11 * time.Minute
)
func init() {
// log.SetLevel(log.LOG_LEVEL_NONE)
sarama.MaxResponseSize = 1<<31 - 1
}
// Config for Reader
type Config struct {
KafkaAddr []string
// the CommitTs of binlog return by reader will bigger than the config CommitTs
CommitTS int64
Offset int64 // start at kafka offset
// if Topic is empty, use the default name in drainer <ClusterID>_obinlog
Topic string
ClusterID string
// buffer size of messages of the reader internal.
// default value 1.
// suggest only setting the buffer size of this if you want the reader to buffer
// message internal and leave `SaramaBufferSize` as 1 default.
MessageBufferSize int
// the sarama internal buffer size of messages.
SaramaBufferSize int
}
func (c *Config) getSaramaBuffserSize() int {
if c.SaramaBufferSize > 0 {
return c.SaramaBufferSize
}
return 1
}
func (c *Config) getMessageBufferSize() int {
if c.MessageBufferSize > 0 {
return c.MessageBufferSize
}
return 1
}
func (c *Config) valid() error {
if len(c.Topic) == 0 && len(c.ClusterID) == 0 {
return errors.New("Topic or ClusterID must be set")
}
return nil
}
// Message read from reader
type Message struct {
Binlog *pb.Binlog
Offset int64 // kafka offset
}
// Reader to read binlog from kafka
type Reader struct {
cfg *Config
client sarama.Client
msgs chan *Message
stop chan struct{}
clusterID string
}
func (r *Reader) getTopic() (string, int32) {
if r.cfg.Topic != "" {
return r.cfg.Topic, 0
}
return r.cfg.ClusterID + "_obinlog", 0
}
// NewReader creates an instance of Reader
func NewReader(cfg *Config) (r *Reader, err error) {
err = cfg.valid()
if err != nil {
errors.Trace(err)
}
r = &Reader{
cfg: cfg,
stop: make(chan struct{}),
msgs: make(chan *Message, cfg.getMessageBufferSize()),
clusterID: cfg.ClusterID,
}
conf := sarama.NewConfig()
// set to 10 minutes to prevent i/o timeout when reading huge message
conf.Net.ReadTimeout = KafkaReadTimeout
if cfg.SaramaBufferSize > 0 {
conf.ChannelBufferSize = cfg.SaramaBufferSize
}
r.client, err = sarama.NewClient(r.cfg.KafkaAddr, conf)
if err != nil {
err = errors.Trace(err)
r = nil
return
}
if r.cfg.CommitTS > 0 {
r.cfg.Offset, err = r.getOffsetByTS(r.cfg.CommitTS, conf)
if err != nil {
err = errors.Trace(err)
r = nil
return
}
log.Debug("set offset to", zap.Int64("offset", r.cfg.Offset))
}
go r.run()
return
}
// Close shuts down the reader
func (r *Reader) Close() {
close(r.stop)
r.client.Close()
}
// Messages returns a chan that contains unread buffered message
func (r *Reader) Messages() (msgs <-chan *Message) {
return r.msgs
}
func (r *Reader) getOffsetByTS(ts int64, conf *sarama.Config) (offset int64, err error) {
// set true to retrive error
conf.Consumer.Return.Errors = true
seeker, err := NewKafkaSeeker(r.cfg.KafkaAddr, conf)
if err != nil {
err = errors.Trace(err)
return
}
topic, partition := r.getTopic()
log.Debug("get offset",
zap.String("topic", topic),
zap.Int32("partition", partition),
zap.Int64("ts", ts))
offsets, err := seeker.Seek(topic, ts, []int32{partition})
if err != nil {
err = errors.Trace(err)
return
}
offset = offsets[0]
return
}
func (r *Reader) run() {
offset := r.cfg.Offset
log.Debug("start at", zap.Int64("offset", offset))
consumer, err := sarama.NewConsumerFromClient(r.client)
if err != nil {
log.Fatal("create kafka consumer failed", zap.Error(err))
}
defer consumer.Close()
topic, partition := r.getTopic()
partitionConsumer, err := consumer.ConsumePartition(topic, partition, offset)
if err != nil {
log.Fatal("create kafka partition consumer failed", zap.Error(err))
}
defer partitionConsumer.Close()
// add select to avoid message blocking while reading
for {
select {
case <-r.stop:
// clean environment
partitionConsumer.Close()
close(r.msgs)
log.Info("reader stop to run")
return
case kmsg := <-partitionConsumer.Messages():
log.Debug("get kafka message", zap.Int64("offset", kmsg.Offset))
binlog := new(pb.Binlog)
err := binlog.Unmarshal(kmsg.Value)
if err != nil {
log.Warn("unmarshal binlog failed", zap.Error(err))
continue
}
if r.cfg.CommitTS > 0 && binlog.CommitTs <= r.cfg.CommitTS {
log.Warn("skip binlog CommitTs", zap.Int64("commitTS", binlog.CommitTs))
continue
}
msg := &Message{
Binlog: binlog,
Offset: kmsg.Offset,
}
select {
case r.msgs <- msg:
case <-r.stop:
// In the next iteration, the <-r.stop would match again and prepare to quit
continue
}
}
}
}