-
Notifications
You must be signed in to change notification settings - Fork 3
/
checkpoint.go
206 lines (180 loc) · 5.07 KB
/
checkpoint.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
package dkafka
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/confluentinc/confluent-kafka-go/kafka"
"go.uber.org/zap"
)
var NoCursorErr = errors.New("no cursor exists")
type checkpointer interface {
Save(cursor string) error
Load() (cursor string, err error)
}
type nilCheckpointer struct{}
func (n *nilCheckpointer) Save(string) error {
return nil
}
func (n *nilCheckpointer) Load() (string, error) {
return "", NoCursorErr
}
func newKafkaCheckpointer(conf kafka.ConfigMap, cursorTopic string, cursorPartition int32, dataTopic string, consumerGroupID string, producer *kafka.Producer) *kafkaCheckpointer {
consumerConfig := cloneConfig(conf)
id := strings.Replace(fmt.Sprintf("dk-%s-%s-%d", dataTopic, cursorTopic, cursorPartition), "_", "", -1)
consumerConfig["group.id"] = consumerGroupID
consumerConfig["enable.auto.commit"] = false
return &kafkaCheckpointer{
consumerConfig: consumerConfig,
topic: cursorTopic,
partition: cursorPartition,
key: []byte(id),
producer: producer,
}
}
type kafkaCheckpointer struct {
key []byte
producer *kafka.Producer
consumerConfig kafka.ConfigMap
topic string
partition int32
}
// in case we need it
//func newFileCheckpointer(filename string) *localFileCheckpointer {
// return &localFileCheckpointer{
// filename: filename,
// }
//}
//
//type localFileCheckpointer struct {
// filename string
//}
//
//func (c *localFileCheckpointer) Save(cursor string) error {
// dat := []byte(cursor)
// return ioutil.WriteFile(c.filename, dat, 0644)
//}
//
//func (c *localFileCheckpointer) Load() (string, error) {
// dat, err := ioutil.ReadFile(c.filename)
// if os.IsNotExist(err) {
// return "", NoCursorErr
// }
// return string(dat), err
//}
type cs struct {
Cursor string `json:"cursor"`
}
func (c *kafkaCheckpointer) Save(cursor string) error {
v, err := json.Marshal(cs{Cursor: cursor})
if err != nil {
return err
}
msg := &kafka.Message{
Key: c.key,
TopicPartition: kafka.TopicPartition{
Topic: &c.topic,
Partition: c.partition,
},
Value: v,
}
return c.producer.Produce(msg, nil)
}
func (c *kafkaCheckpointer) Load() (string, error) {
consumer, err := kafka.NewConsumer(&c.consumerConfig)
if err != nil {
return "", fmt.Errorf("creating consumer: %w", err)
}
defer func() {
if err := consumer.Close(); err != nil {
log.Printf("error closing consumer: %s", err)
}
}()
consumer.Subscribe(c.topic, nil)
md, err := consumer.GetMetadata(&c.topic, false, 500)
if err != nil {
return "", fmt.Errorf("getting metadata: %w", err)
}
parts := md.Topics[c.topic].Partitions
if len(parts) == 0 {
zlog.Info("cursor topic does not exist, creating", zap.String("cursor_topic", c.topic))
err := createKafkaCursorTopic(consumer, c.topic, len(md.Brokers))
if err != nil {
return "", err
}
} else if len(parts)-1 < int(c.partition) {
return "", fmt.Errorf("requested cursor partition does not exist in cursor topic")
}
low, high, err := consumer.QueryWatermarkOffsets(c.topic, c.partition, 500)
if err != nil {
return "", fmt.Errorf("getting low/high: %w", err)
}
for i := kafka.Offset(high) - 1; i >= kafka.Offset(low); i-- {
err = consumer.Assign([]kafka.TopicPartition{
kafka.TopicPartition{
Topic: &c.topic,
Partition: c.partition,
Offset: i,
}})
if err != nil {
return "", err
}
ev := consumer.Poll(1000)
switch event := ev.(type) {
case kafka.Error:
return "", event
case *kafka.Message:
cursor := cs{}
if err := json.Unmarshal(event.Value, &cursor); err != nil {
return "", err
}
if strings.HasPrefix(string(event.Key), "dk-") {
if string(event.Key) != string(c.key) {
return "", fmt.Errorf("invalid key for cursor: expected %s, got %s -- are you reading from the right partition?", string(c.key), string(event.Key))
}
}
if cursor.Cursor == "" {
err = NoCursorErr
}
return cursor.Cursor, err
default:
}
}
return "", NoCursorErr
}
func cloneConfig(in kafka.ConfigMap) kafka.ConfigMap {
out := make(kafka.ConfigMap)
for k, v := range in {
out[k] = v
}
return out
}
func createKafkaCursorTopic(c *kafka.Consumer, cursorTopic string, maxAvailableBrokers int) error {
adminCli, err := kafka.NewAdminClientFromConsumer(c)
if err != nil {
return fmt.Errorf("creating admin client: %w", err)
}
numParts := 10
replicationFactor := 3
if replicationFactor > maxAvailableBrokers {
replicationFactor = maxAvailableBrokers
}
results, err := adminCli.CreateTopics(
context.Background(),
// Multiple topics can be created simultaneously
// by providing more TopicSpecification structs here.
[]kafka.TopicSpecification{{
Topic: cursorTopic,
NumPartitions: numParts,
ReplicationFactor: replicationFactor}},
// Admin options
kafka.SetAdminOperationTimeout(time.Second*10))
if err != nil {
return fmt.Errorf("creating topic: %w", err)
}
zlog.Info("creating topic", zap.Any("results", results), zap.Int("num_partitions", numParts), zap.Int("replication_factor", replicationFactor))
return nil
}