-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
client.go
600 lines (491 loc) · 14 KB
/
client.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package kafka
import (
"errors"
"fmt"
"log"
"math/rand"
"sync"
"time"
"github.com/Shopify/sarama"
)
type TopicMissingError struct {
msg string
}
func (e TopicMissingError) Error() string { return e.msg }
type void struct{}
var member void
type Client struct {
client sarama.Client
kafkaConfig *sarama.Config
config *Config
supportedAPIs map[int]int
topics map[string]void
topicsMutex sync.RWMutex
}
func NewClient(config *Config) (*Client, error) {
if config == nil {
return nil, errors.New("Cannot create client without kafka config")
}
log.Printf("[TRACE] configuring bootstrap_servers %v", config.copyWithMaskedSensitiveValues())
if config.BootstrapServers == nil {
return nil, fmt.Errorf("No bootstrap_servers provided")
}
bootstrapServers := *(config.BootstrapServers)
if bootstrapServers == nil {
return nil, fmt.Errorf("No bootstrap_servers provided")
}
log.Printf("[INFO] configuring kafka client with %v", config.copyWithMaskedSensitiveValues())
kc, err := config.newKafkaConfig()
if err != nil {
log.Printf("[ERROR] Error creating kafka client %v", err)
return nil, err
}
c, err := sarama.NewClient(bootstrapServers, kc)
if err != nil {
log.Printf("[ERROR] Error connecting to kafka %s", err)
return nil, err
}
client := &Client{
client: c,
config: config,
kafkaConfig: kc,
}
err = client.populateAPIVersions()
if err != nil {
return client, err
}
err = client.extractTopics()
return client, err
}
func (c *Client) SaramaClient() sarama.Client {
return c.client
}
func (c *Client) populateAPIVersions() error {
ch := make(chan []sarama.ApiVersionsResponseKey)
errCh := make(chan error)
brokers := c.client.Brokers()
kafkaConfig := c.kafkaConfig
for _, broker := range brokers {
go apiVersionsFromBroker(broker, kafkaConfig, ch, errCh)
}
clusterApiVersions := make(map[int][2]int) // valid api version intervals across all brokers
errs := make([]error, 0)
for i := 0; i < len(brokers); i++ {
select {
case brokerApiVersions := <-ch:
updateClusterApiVersions(&clusterApiVersions, brokerApiVersions)
case err := <-errCh:
errs = append(errs, err)
}
}
if len(errs) != 0 {
return errors.New(sarama.MultiErrorFormat(errs))
}
c.supportedAPIs = make(map[int]int, len(clusterApiVersions))
for apiKey, versionMinMax := range clusterApiVersions {
versionMin := versionMinMax[0]
versionMax := versionMinMax[1]
if versionMax >= versionMin {
c.supportedAPIs[apiKey] = versionMax
}
// versionMax will be less than versionMin only when
// two or more brokers have disjoint version
// intervals...which means the api is not supported
// cluster-wide
}
return nil
}
func apiVersionsFromBroker(broker *sarama.Broker, config *sarama.Config, ch chan<- []sarama.ApiVersionsResponseKey, errCh chan<- error) {
resp, err := rawApiVersionsRequest(broker, config)
if err != nil {
errCh <- err
} else if sarama.KError(resp.ErrorCode) != sarama.ErrNoError {
errCh <- errors.New(sarama.KError(resp.ErrorCode).Error())
} else {
ch <- resp.ApiKeys
}
}
func rawApiVersionsRequest(broker *sarama.Broker, config *sarama.Config) (*sarama.ApiVersionsResponse, error) {
if err := broker.Open(config); err != nil && err != sarama.ErrAlreadyConnected {
return nil, err
}
defer func() {
if err := broker.Close(); err != nil && err != sarama.ErrNotConnected {
log.Fatal(err)
}
}()
return broker.ApiVersions(&sarama.ApiVersionsRequest{})
}
func updateClusterApiVersions(clusterApiVersions *map[int][2]int, brokerApiVersions []sarama.ApiVersionsResponseKey) {
cluster := *clusterApiVersions
for _, apiBlock := range brokerApiVersions {
apiKey := int(apiBlock.ApiKey)
brokerMin := int(apiBlock.MinVersion)
brokerMax := int(apiBlock.MaxVersion)
clusterMinMax, exists := cluster[apiKey]
if !exists {
cluster[apiKey] = [2]int{brokerMin, brokerMax}
} else {
// shrink the cluster interval according to
// the broker interval
clusterMin := clusterMinMax[0]
clusterMax := clusterMinMax[1]
if brokerMin > clusterMin {
clusterMinMax[0] = brokerMin
}
if brokerMax < clusterMax {
clusterMinMax[1] = brokerMax
}
cluster[apiKey] = clusterMinMax
}
}
}
func (c *Client) extractTopics() error {
topics, err := c.client.Topics()
if err != nil {
log.Printf("[ERROR] Error getting topics %s from Kafka", err)
return err
}
log.Printf("[DEBUG] Got %d topics from Kafka", len(topics))
c.topicsMutex.Lock()
c.topics = make(map[string]void)
for _, t := range topics {
c.topics[t] = member
}
c.topicsMutex.Unlock()
return nil
}
func (c *Client) DeleteTopic(t string) error {
broker, err := c.client.Controller()
if err != nil {
return err
}
timeout := time.Duration(c.config.Timeout) * time.Second
req := &sarama.DeleteTopicsRequest{
Topics: []string{t},
Timeout: timeout,
}
res, err := broker.DeleteTopics(req)
if err == nil {
for k, e := range res.TopicErrorCodes {
if e != sarama.ErrNoError {
return fmt.Errorf("%s : %s", k, e)
}
}
} else {
log.Printf("[ERROR] Error deleting topic %s from Kafka: %s", t, err)
return err
}
log.Printf("[INFO] Deleted topic %s from Kafka", t)
return nil
}
func (c *Client) UpdateTopic(topic Topic) error {
broker, err := c.client.Controller()
if err != nil {
return err
}
r := &sarama.AlterConfigsRequest{
Resources: configToResources(topic),
ValidateOnly: false,
}
res, err := broker.AlterConfigs(r)
if err != nil {
return err
}
if err == nil {
for _, e := range res.Resources {
if e.ErrorCode != int16(sarama.ErrNoError) {
return errors.New(e.ErrorMsg)
}
}
}
return nil
}
func (c *Client) CreateTopic(t Topic) error {
broker, err := c.client.Controller()
if err != nil {
return err
}
timeout := time.Duration(c.config.Timeout) * time.Second
log.Printf("[TRACE] Timeout is %v ", timeout)
req := &sarama.CreateTopicsRequest{
TopicDetails: map[string]*sarama.TopicDetail{
t.Name: {
NumPartitions: t.Partitions,
ReplicationFactor: t.ReplicationFactor,
ConfigEntries: t.Config,
},
},
Timeout: timeout,
}
res, err := broker.CreateTopics(req)
if err == nil {
for _, e := range res.TopicErrors {
if e.Err != sarama.ErrNoError {
return fmt.Errorf("%s", e.Err)
}
}
log.Printf("[INFO] Created topic %s in Kafka", t.Name)
}
return err
}
func (c *Client) AddPartitions(t Topic) error {
broker, err := c.client.Controller()
if err != nil {
return err
}
timeout := time.Duration(c.config.Timeout) * time.Second
tp := map[string]*sarama.TopicPartition{
t.Name: &sarama.TopicPartition{
Count: t.Partitions,
},
}
req := &sarama.CreatePartitionsRequest{
TopicPartitions: tp,
Timeout: timeout,
ValidateOnly: false,
}
log.Printf("[INFO] Adding partitions to %s in Kafka", t.Name)
res, err := broker.CreatePartitions(req)
if err == nil {
for _, e := range res.TopicPartitionErrors {
if e.Err != sarama.ErrNoError {
return fmt.Errorf("%s", e.Err)
}
}
log.Printf("[INFO] Added partitions to %s in Kafka", t.Name)
}
return err
}
func (c *Client) CanAlterReplicationFactor() bool {
_, ok1 := c.supportedAPIs[45] // https://kafka.apache.org/protocol#The_Messages_AlterPartitionReassignments
_, ok2 := c.supportedAPIs[46] // https://kafka.apache.org/protocol#The_Messages_ListPartitionReassignments
return ok1 && ok2
}
func (c *Client) AlterReplicationFactor(t Topic) error {
log.Printf("[DEBUG] Refreshing metadata for topic '%s'", t.Name)
if err := c.client.RefreshMetadata(t.Name); err != nil {
return err
}
admin, err := sarama.NewClusterAdminFromClient(c.client)
if err != nil {
return err
}
assignment, err := c.buildAssignment(t)
if err != nil {
return err
}
return admin.AlterPartitionReassignments(t.Name, *assignment)
}
func (c *Client) buildAssignment(t Topic) (*[][]int32, error) {
partitions, err := c.client.Partitions(t.Name)
if err != nil {
return nil, err
}
allReplicas := c.allReplicas()
newRF := t.ReplicationFactor
rand.Seed(time.Now().UnixNano())
assignment := make([][]int32, len(partitions))
for _, p := range partitions {
oldReplicas, err := c.client.Replicas(t.Name, p)
if err != nil {
return &assignment, err
}
oldRF := int16(len(oldReplicas))
deltaRF := newRF - oldRF
newReplicas, err := buildNewReplicas(allReplicas, &oldReplicas, deltaRF)
if err != nil {
return &assignment, err
}
assignment[p] = *newReplicas
}
return &assignment, nil
}
func (c *Client) allReplicas() *[]int32 {
brokers := c.client.Brokers()
replicas := make([]int32, 0, len(brokers))
for _, b := range brokers {
id := b.ID()
if id != -1 {
replicas = append(replicas, id)
}
}
return &replicas
}
func buildNewReplicas(allReplicas *[]int32, usedReplicas *[]int32, deltaRF int16) (*[]int32, error) {
usedCount := int16(len(*usedReplicas))
if deltaRF == 0 {
return usedReplicas, nil
} else if deltaRF < 0 {
end := usedCount + deltaRF
if end < 1 {
return nil, errors.New("dropping too many replicas")
}
head := (*usedReplicas)[:end]
return &head, nil
} else {
extraCount := int16(len(*allReplicas)) - usedCount
if extraCount < deltaRF {
return nil, errors.New("not enough brokers")
}
unusedReplicas := *findUnusedReplicas(allReplicas, usedReplicas, extraCount)
newReplicas := *usedReplicas
for i := int16(0); i < deltaRF; i++ {
j := rand.Intn(len(unusedReplicas))
newReplicas = append(newReplicas, unusedReplicas[j])
unusedReplicas[j] = unusedReplicas[len(unusedReplicas)-1]
unusedReplicas = unusedReplicas[:len(unusedReplicas)-1]
}
return &newReplicas, nil
}
}
func findUnusedReplicas(allReplicas *[]int32, usedReplicas *[]int32, extraCount int16) *[]int32 {
usedMap := make(map[int32]bool, len(*usedReplicas))
for _, r := range *usedReplicas {
usedMap[r] = true
}
unusedReplicas := make([]int32, 0, extraCount)
for _, r := range *allReplicas {
_, exists := usedMap[r]
if !exists {
unusedReplicas = append(unusedReplicas, r)
}
}
return &unusedReplicas
}
func (c *Client) IsReplicationFactorUpdating(topic string) (bool, error) {
log.Printf("[DEBUG] Refreshing metadata for topic '%s'", topic)
if err := c.client.RefreshMetadata(topic); err != nil {
return false, err
}
partitions, err := c.client.Partitions(topic)
if err != nil {
return false, err
}
admin, err := sarama.NewClusterAdminFromClient(c.client)
if err != nil {
return false, err
}
statusMap, err := admin.ListPartitionReassignments(topic, partitions)
if err != nil {
return false, err
}
for _, status := range statusMap[topic] {
if isPartitionRFChanging(status) {
return true, nil
}
}
return false, nil
}
func isPartitionRFChanging(status *sarama.PartitionReplicaReassignmentsStatus) bool {
return len(status.AddingReplicas) != 0 || len(status.RemovingReplicas) != 0
}
func (client *Client) ReadTopic(name string, refreshMetadata bool) (Topic, error) {
c := client.client
log.Printf("[INFO] 👋 reading topic '%s' from Kafka: %v", name, refreshMetadata)
topic := Topic{
Name: name,
}
if refreshMetadata {
log.Printf("[DEBUG] Refreshing metadata for topic '%s'", name)
err := c.RefreshMetadata(name)
if err == sarama.ErrUnknownTopicOrPartition {
err := TopicMissingError{msg: fmt.Sprintf("%s could not be found", name)}
return topic, err
}
if err != nil {
log.Printf("[ERROR] Error refreshing topic '%s' metadata %s", name, err)
return topic, err
}
err = client.extractTopics()
if err != nil {
return topic, err
}
} else {
log.Printf("[DEBUG] skipping metadata refresh for topic '%s'", name)
}
client.topicsMutex.RLock()
_, topicExists := client.topics[name]
client.topicsMutex.RUnlock()
if topicExists {
log.Printf("[DEBUG] Found %s from Kafka", name)
p, err := c.Partitions(name)
if err == nil {
partitionCount := int32(len(p))
log.Printf("[DEBUG] [%s] %d Partitions Found: %v from Kafka", name, partitionCount, p)
topic.Partitions = partitionCount
r, err := ReplicaCount(c, name, p)
if err != nil {
return topic, err
}
log.Printf("[DEBUG] [%s] ReplicationFactor %d from Kafka", name, r)
topic.ReplicationFactor = int16(r)
configToSave, err := client.topicConfig(name)
if err != nil {
log.Printf("[ERROR] [%s] Could not get config for topic %s", name, err)
return topic, err
}
log.Printf("[TRACE] [%s] Config %v from Kafka", name, strPtrMapToStrMap(configToSave))
topic.Config = configToSave
return topic, nil
}
}
err := TopicMissingError{msg: fmt.Sprintf("%s could not be found", name)}
return topic, err
}
func (c *Client) versionForKey(apiKey, wantedMaxVersion int) int {
if maxSupportedVersion, ok := c.supportedAPIs[apiKey]; ok {
if maxSupportedVersion < wantedMaxVersion {
return maxSupportedVersion
}
return wantedMaxVersion
}
return 0
}
//topicConfig retrives the non-default config map for a topic
func (c *Client) topicConfig(topic string) (map[string]*string, error) {
conf := map[string]*string{}
request := &sarama.DescribeConfigsRequest{
Version: c.getDescribeConfigAPIVersion(),
Resources: []*sarama.ConfigResource{
{
Type: sarama.TopicResource,
Name: topic,
},
},
}
broker, err := c.client.Controller()
if err != nil {
return conf, err
}
cr, err := broker.DescribeConfigs(request)
if err != nil {
return conf, err
}
if len(cr.Resources) > 0 && len(cr.Resources[0].Configs) > 0 {
for _, tConf := range cr.Resources[0].Configs {
v := tConf.Value
log.Printf("[TRACE] [%s] %s: %v. Default %v, Source %v, Version %d", topic, tConf.Name, v, tConf.Default, tConf.Source, cr.Version)
for _, s := range tConf.Synonyms {
log.Printf("[TRACE] Syonyms: %v", s)
}
if isDefault(tConf, int(cr.Version)) {
continue
}
conf[tConf.Name] = &v
}
}
return conf, nil
}
func (c *Client) getDescribeAclsRequestAPIVersion() int16 {
return int16(c.versionForKey(29, 1))
}
func (c *Client) getCreateAclsRequestAPIVersion() int16 {
return int16(c.versionForKey(30, 1))
}
func (c *Client) getDeleteAclsRequestAPIVersion() int16 {
return int16(c.versionForKey(31, 1))
}
func (c *Client) getDescribeConfigAPIVersion() int16 {
return int16(c.versionForKey(32, 1))
}