/
zkclient.go
1156 lines (994 loc) · 26.3 KB
/
zkclient.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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package admin
import (
"context"
"errors"
"fmt"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/segmentio/kafka-go"
"github.com/segmentio/topicctl/pkg/util"
"github.com/segmentio/topicctl/pkg/zk"
log "github.com/sirupsen/logrus"
)
const (
// Various paths in zookeeper
assignmentPath = "/admin/reassign_partitions"
electionPath = "/admin/preferred_replica_election"
brokersPath = "/brokers/ids"
controllerPath = "/controller"
topicsPath = "/brokers/topics"
clusterIDPath = "/cluster/id"
brokerConfigsPath = "/config/brokers"
configChangesPath = "/config/changes/config_change_"
topicConfigsPath = "/config/topics"
// The maximum number of topics to fetch in parallel
maxPoolSize = 20
)
var (
// ErrTopicDoesNotExist is returned by admin functions when a topic that should exist
// does not.
ErrTopicDoesNotExist = errors.New("Topic does not exist")
)
// ZKAdminClient is a general client for interacting with a kafka cluster that assumes
// zookeeper access. Most interactions are done via the latter, but a few (e.g., creating topics or
// getting the controller address) are done via the broker API instead.
type ZKAdminClient struct {
zkClient zk.Client
zkPrefix string
bootstrapAddrs []string
Connector *Connector
sess *session.Session
readOnly bool
}
var _ Client = (*ZKAdminClient)(nil)
// ZKAdminClientConfig contains all of the parameters necessary to create a kafka admin client.
type ZKAdminClientConfig struct {
ZKAddrs []string
ZKPrefix string
BootstrapAddrs []string
ExpectedClusterID string
Sess *session.Session
ReadOnly bool
}
// NewZKAdminClient creates and returns a new Client instance.
func NewZKAdminClient(
ctx context.Context,
config ZKAdminClientConfig,
) (*ZKAdminClient, error) {
zkClient, err := zk.NewPooledClient(
config.ZKAddrs,
time.Minute,
&zk.DebugLogger{},
10,
config.ReadOnly,
)
if err != nil {
return nil, err
}
zkPrefix := config.ZKPrefix
// Normalize prefix
if zkPrefix != "" {
if !strings.HasPrefix(zkPrefix, "/") {
zkPrefix = fmt.Sprintf("/%s", zkPrefix)
}
if strings.HasSuffix(zkPrefix, "/") {
zkPrefix = zkPrefix[:len(zkPrefix)-1]
}
}
client := &ZKAdminClient{
zkClient: zkClient,
zkPrefix: zkPrefix,
sess: config.Sess,
readOnly: config.ReadOnly,
}
if config.ExpectedClusterID != "" {
log.Info("Checking cluster ID against version in cluster")
clusterID, err := client.GetClusterID(ctx)
if err != nil {
return nil, err
}
if clusterID != config.ExpectedClusterID {
return nil, fmt.Errorf(
"ID in cluster (%s) does not match expected one (%s)",
clusterID,
config.ExpectedClusterID,
)
}
}
var bootstrapAddrs []string
if len(config.BootstrapAddrs) == 0 {
log.Debug("No bootstrap addresses provided, getting one from zookeeper")
ids, err := client.GetBrokerIDs(ctx)
if err != nil {
return nil, err
}
// Just use the first ID
brokers, err := client.GetBrokers(ctx, []int{ids[0]})
if err != nil {
return nil, err
}
bootstrapAddrs = []string{brokers[0].Addr()}
} else {
bootstrapAddrs = append(bootstrapAddrs, config.BootstrapAddrs...)
}
client.bootstrapAddrs = bootstrapAddrs
client.Connector, err = NewConnector(
ConnectorConfig{
BrokerAddr: bootstrapAddrs[0],
},
)
return client, nil
}
// GetClusterID gets the cluster ID from zookeeper. This ID is generated when the cluster is
// created and should be stable over the life of the cluster.
func (c *ZKAdminClient) GetClusterID(
ctx context.Context,
) (string, error) {
zkClusterIDPath := c.zNode(clusterIDPath)
zkClusterIDObj := zkClusterID{}
_, err := c.zkClient.GetJSON(ctx, zkClusterIDPath, &zkClusterIDObj)
if err != nil {
return "", err
}
return zkClusterIDObj.ID, nil
}
// GetBrokers gets information on one or more cluster brokers from zookeeper.
// If the argument ids is unset, then it fetches all brokers.
func (c *ZKAdminClient) GetBrokers(
ctx context.Context,
ids []int,
) ([]BrokerInfo, error) {
// TODO (maybe): Use Kafka API instead of ZK to get broker info
var brokerIDs []int
var err error
if len(ids) > 0 {
brokerIDs = ids
} else {
brokerIDs, err = c.GetBrokerIDs(ctx)
if err != nil {
return nil, err
}
}
brokers := []BrokerInfo{}
brokerHosts := []string{}
for _, id := range brokerIDs {
zkBrokerInfo := zkBrokerInfo{}
_, err = c.zkClient.GetJSON(
ctx,
c.zNode(brokersPath, fmt.Sprintf("%d", id)),
&zkBrokerInfo,
)
if err != nil {
return nil, err
}
zBrokerConfigPath := c.zNode(brokerConfigsPath, fmt.Sprintf("%d", id))
zkBrokerConfig := zkBrokerConfig{}
exists, _, err := c.zkClient.Exists(
ctx,
zBrokerConfigPath,
)
if err != nil {
return nil, err
}
if exists {
_, err = c.zkClient.GetJSON(
ctx,
zBrokerConfigPath,
&zkBrokerConfig,
)
if err != nil {
return nil, err
}
}
epochMillis, err := strconv.ParseInt(
zkBrokerInfo.TimestampStr,
10,
64,
)
if err != nil {
return nil, err
}
brokerInfo := BrokerInfo{
ID: int(id),
Endpoints: zkBrokerInfo.Endpoints,
Host: zkBrokerInfo.Host,
Port: zkBrokerInfo.Port,
Rack: zkBrokerInfo.Rack,
Version: zkBrokerInfo.Version,
Timestamp: time.Unix(epochMillis/1000, 0),
Config: zkBrokerConfig.Config,
}
brokerHosts = append(
brokerHosts,
zkBrokerInfo.Host,
)
brokers = append(
brokers,
brokerInfo,
)
}
instances, err := c.getInstances(ctx, brokerHosts)
if err != nil {
log.Debugf("Could not get instance info from EC2: %+v", err)
}
for b := 0; b < len(brokers); b++ {
instance, ok := instances[brokers[b].Host]
if !ok {
continue
}
brokers[b].InstanceID = aws.StringValue(instance.InstanceId)
brokers[b].InstanceType = aws.StringValue(instance.InstanceType)
brokers[b].AvailabilityZone = aws.StringValue(
instance.Placement.AvailabilityZone,
)
}
sort.Slice(brokers, func(i, j int) bool {
return brokers[i].ID < brokers[j].ID
})
return brokers, nil
}
// GetBrokerIDs returns a slice of all broker IDs.
func (c *ZKAdminClient) GetBrokerIDs(ctx context.Context) ([]int, error) {
zPath := c.zNode(brokersPath)
brokerIDStrs, _, err := c.zkClient.Children(ctx, zPath)
if err != nil {
return nil, fmt.Errorf(
"Error getting children at path %s: %+v",
zPath,
err,
)
}
brokerIDs := []int{}
for _, idStr := range brokerIDStrs {
id, err := strconv.ParseInt(idStr, 10, 32)
if err != nil {
return nil, err
}
brokerIDs = append(brokerIDs, int(id))
}
return brokerIDs, nil
}
// GetControllerID gets ID of the active controller broker
func (c *ZKAdminClient) GetControllerID(
ctx context.Context,
) (int, error) {
zkControllerInfo := zkControllerInfo{}
zkControllerPath := c.zNode(controllerPath)
_, err := c.zkClient.GetJSON(
ctx,
zkControllerPath,
&zkControllerInfo,
)
if err != nil {
return -1, fmt.Errorf("Error getting zookeeper path %s: %+v",
zkControllerPath,
err,
)
}
return zkControllerInfo.BrokerID, nil
}
// GetConnector returns the Connector instance associated with this client.
func (c *ZKAdminClient) GetConnector() *Connector {
return c.Connector
}
// GetTopics gets information about one or more cluster topics from zookeeper.
// If the argument names is unset, then it fetches all topics. The detailed
// parameter determines whether the ISRs and leaders are fetched for each
// partition.
func (c *ZKAdminClient) GetTopics(
ctx context.Context,
names []string,
detailed bool,
) ([]TopicInfo, error) {
var topicNames []string
var err error
if len(names) > 0 {
topicNames = names
} else {
topicNames, err = c.GetTopicNames(ctx)
if err != nil {
return nil, err
}
}
log.Debugf(
"Looking up %d topic names: %+v",
len(topicNames),
topicNames,
)
topics := []TopicInfo{}
type topicReq struct {
name string
detailed bool
}
type topicResp struct {
topic TopicInfo
err error
}
// This operation can be slow if there are a lot of topics, distribute it out
topicReqChan := make(chan topicReq, len(topicNames))
topicRespChan := make(chan topicResp, len(topicNames))
defer close(topicReqChan)
for _, name := range topicNames {
topicReqChan <- topicReq{
name: name,
detailed: detailed,
}
}
poolSize := minInt(len(topicNames), maxPoolSize)
for i := 0; i < poolSize; i++ {
go func() {
for {
topicReq, ok := <-topicReqChan
if !ok {
return
}
topic, err := c.getTopic(ctx, topicReq.name, topicReq.detailed)
topicRespChan <- topicResp{
topic: topic,
err: err,
}
}
}()
}
for i := 0; i < len(topicNames); i++ {
topicResp := <-topicRespChan
if topicResp.err != nil {
return nil, err
}
topics = append(topics, topicResp.topic)
}
sort.Slice(topics, func(i, j int) bool {
return topics[i].Name < topics[j].Name
})
return topics, nil
}
// GetTopicNames gets all topic names from zookeeper.
func (c *ZKAdminClient) GetTopicNames(ctx context.Context) ([]string, error) {
zPath := c.zNode(topicsPath)
topicNames, _, err := c.zkClient.Children(ctx, zPath)
if err != nil {
return nil, fmt.Errorf(
"Error getting children at path %s: %+v",
zPath,
err,
)
}
return topicNames, nil
}
// GetTopic is a wrapper around GetTopics(...) for getting information about
// a single topic.
func (c *ZKAdminClient) GetTopic(
ctx context.Context,
name string,
detailed bool,
) (TopicInfo, error) {
// TODO (maybe): Use Kafka API instead of ZK to get topic info
topics, err := c.GetTopics(ctx, []string{name}, detailed)
if err != nil {
if strings.Contains(err.Error(), "node does not exist") {
return TopicInfo{}, ErrTopicDoesNotExist
}
return TopicInfo{}, err
}
if len(topics) != 1 {
return TopicInfo{}, ErrTopicDoesNotExist
}
return topics[0], nil
}
func (c *ZKAdminClient) GetACLs(
ctx context.Context,
filter kafka.ACLFilter,
) ([]ACLInfo, error) {
return nil, errors.New("ACLs not yet supported with zk access mode; omit zk addresses to fix.")
}
func (c *ZKAdminClient) CreateACLs(
ctx context.Context,
acls []kafka.ACLEntry,
) error {
return errors.New("ACLs not yet supported with zk access mode; omit zk addresses to fix.")
}
func (c *ZKAdminClient) DeleteACLs(
ctx context.Context,
filters []kafka.DeleteACLsFilter,
) (*kafka.DeleteACLsResponse, error) {
return nil, errors.New("ACLs not yet supported with zk access mode; omit zk addresses to fix.")
}
func (c *ZKAdminClient) GetUsers(
ctx context.Context,
names []string,
) ([]UserInfo, error) {
return nil, errors.New("Users not yet supported with zk access mode; omit zk addresses to fix.")
}
func (c *ZKAdminClient) UpsertUser(
ctx context.Context,
user kafka.UserScramCredentialsUpsertion,
) error {
return errors.New("Users not yet supported with zk access mode; omit zk addresses to fix.")
}
// UpdateTopicConfig updates the config JSON for a topic and sets a change
// notification so that the brokers are notified. If overwrite is true, then
// it will overwrite existing config entries.
//
// The function returns the list of keys that were modified. If overwrite is
// set to false, this can be used to determine the subset of entries
// that were already set.
func (c *ZKAdminClient) UpdateTopicConfig(
ctx context.Context,
name string,
configEntries []kafka.ConfigEntry,
overwrite bool,
) ([]string, error) {
var updatedKeys []string
if c.readOnly {
return updatedKeys, errors.New("Cannot update topic in read-only mode")
}
log.Debugf("Updating config for topic %s", name)
configMap := map[string]interface{}{}
zPath := c.zNode(topicConfigsPath, name)
stats, err := c.zkClient.GetJSON(
ctx,
zPath,
&configMap,
)
if err != nil {
return updatedKeys, err
}
updatedKeys, err = updateConfig(configMap, configEntries, overwrite)
if err != nil {
return updatedKeys, err
}
_, err = c.zkClient.SetJSON(ctx, zPath, configMap, stats.Version)
if err != nil {
return updatedKeys, err
}
changeObj := zkChangeNotification{
Version: 2,
EntityPath: fmt.Sprintf("topics/%s", name),
}
log.Debugf("Setting change notification: %+v", changeObj)
return updatedKeys,
c.zkClient.CreateJSON(ctx, c.zNode(configChangesPath), changeObj, true)
}
// UpdateBrokerConfig updates the config JSON for a cluster broker and
// sets a change notification so the cluster brokers are notified. If overwrite is
// true, then it will overwrite existing config entries.
//
// The function returns the list of keys that were modified. If overwrite is
// set to false, this can be used to determine the subset of entries
func (c *ZKAdminClient) UpdateBrokerConfig(
ctx context.Context,
id int,
configEntries []kafka.ConfigEntry,
overwrite bool,
) ([]string, error) {
var updatedKeys []string
if c.readOnly {
return updatedKeys, errors.New("Cannot update topic in read-only mode")
}
log.Debugf("Updating config for broker %d", id)
idStr := fmt.Sprintf("%d", id)
// Broker configs parent might not already exist
zBrokerRoot := c.zNode(brokerConfigsPath)
exists, _, err := c.zkClient.Exists(ctx, zBrokerRoot)
if err != nil {
return nil, err
}
if !exists {
log.Infof("Creating broker configs path: %s", zBrokerRoot)
err := c.zkClient.Create(ctx, zBrokerRoot, nil, false)
if err != nil {
return updatedKeys, err
}
}
// Broker config might not exist
zBrokerPath := c.zNode(brokerConfigsPath, idStr)
exists, _, err = c.zkClient.Exists(ctx, zBrokerPath)
if err != nil {
return nil, err
}
if !exists {
zkBrokerConfigObj := zkBrokerConfig{
Version: 1,
Config: map[string]string{},
}
log.Infof("Creating broker config at %s: %+v", zBrokerPath, zkBrokerConfigObj)
err := c.zkClient.CreateJSON(ctx, zBrokerPath, zkBrokerConfigObj, false)
if err != nil {
return updatedKeys, err
}
}
configMap := map[string]interface{}{}
zPath := c.zNode(brokerConfigsPath, idStr)
stats, err := c.zkClient.GetJSON(
ctx,
zPath,
&configMap,
)
if err != nil {
return updatedKeys, err
}
updatedKeys, err = updateConfig(configMap, configEntries, overwrite)
if err != nil {
return updatedKeys, err
}
_, err = c.zkClient.SetJSON(ctx, zPath, configMap, stats.Version)
if err != nil {
return updatedKeys, err
}
changeObj := zkChangeNotification{
Version: 2,
EntityPath: fmt.Sprintf("brokers/%s", idStr),
}
log.Debugf("Setting change notification: %+v", changeObj)
return updatedKeys,
c.zkClient.CreateJSON(ctx, c.zNode(configChangesPath), changeObj, true)
}
// CreateTopic creates a new topic with the argument config. It uses
// the topic creation API exposed on the controller broker.
func (c *ZKAdminClient) CreateTopic(
ctx context.Context,
config kafka.TopicConfig,
) error {
if c.readOnly {
return errors.New("Cannot create topic in read-only mode")
}
req := kafka.CreateTopicsRequest{
Topics: []kafka.TopicConfig{config},
}
log.Debugf("Creating topic with config %+v", config)
resp, err := c.Connector.KafkaClient.CreateTopics(ctx, &req)
if err != nil {
return err
}
if err = util.KafkaErrorsToErr(resp.Errors); err != nil {
return err
}
return err
}
// AssignPartitions notifies the cluster to begin a partition reassignment.
// This should only be used for existing partitions; to create new partitions,
// use the AddPartitions method.
func (c *ZKAdminClient) AssignPartitions(
ctx context.Context,
topic string,
assignments []PartitionAssignment,
) error {
if c.readOnly {
return errors.New("Cannot assign partitions in read-only mode")
}
zkAssignmentObj := zkAssignment{
Version: 1,
Partitions: []zkAssignmentPartition{},
}
for _, assignment := range assignments {
zkAssignmentObj.Partitions = append(
zkAssignmentObj.Partitions,
zkAssignmentPartition{
Topic: topic,
Partition: assignment.ID,
Replicas: util.CopyInts(assignment.Replicas),
},
)
}
zNode := c.zNode(assignmentPath)
log.Infof(
"Writing reassignment config to zk path %s: %+v",
zNode,
zkAssignmentObj,
)
return c.zkClient.CreateJSON(
ctx,
zNode,
zkAssignmentObj,
false,
)
}
// AddPartitions adds one or more partitions to an existing topic. Unlike
// AssignPartitions, this directly updates the topic's partition config in
// zookeeper.
func (c *ZKAdminClient) AddPartitions(
ctx context.Context,
topic string,
newAssignments []PartitionAssignment,
) error {
if c.readOnly {
return errors.New("Cannot add partitions in read-only mode")
}
// Use raw map[string]interface instead of struct to ensure we don't omit any
// fields in existing config.
topicInfo := map[string]interface{}{}
zNode := c.zNode(topicsPath, topic)
stats, err := c.zkClient.GetJSON(
ctx,
zNode,
&topicInfo,
)
if err != nil {
return err
}
rawPartitions, ok := topicInfo["partitions"]
if !ok {
return fmt.Errorf("Cannot find partitions in topic map: %+v", topicInfo)
}
partititions, ok := rawPartitions.(map[string]interface{})
if !ok {
return errors.New("Cannot convert partitions to map")
}
for _, assignment := range newAssignments {
idStr := fmt.Sprintf("%d", assignment.ID)
if _, ok := partititions[idStr]; ok {
return fmt.Errorf("Partition %s already exists", idStr)
}
partititions[idStr] = assignment.Replicas
}
topicInfo["partitions"] = partititions
log.Infof(
"Overwriting config for topic %s with new version: %+v",
topic,
topicInfo,
)
_, err = c.zkClient.SetJSON(ctx, zNode, topicInfo, stats.Version)
return err
}
// RunLeaderElection triggers a leader election for the argument
// topic and partitions.
func (c *ZKAdminClient) RunLeaderElection(
ctx context.Context,
topic string,
partitions []int,
) error {
if c.readOnly {
return errors.New("Cannot run leader election in read-only mode")
}
zkElectionObj := zkElection{
Version: 1,
Partitions: []zkElectionTopicPartition{},
}
for _, partition := range partitions {
zkElectionObj.Partitions = append(
zkElectionObj.Partitions,
zkElectionTopicPartition{
Topic: topic,
Partition: partition,
},
)
}
zNode := c.zNode(electionPath)
log.Infof(
"Writing leader election config to zk path %s: %+v",
zNode,
zkElectionObj,
)
return c.zkClient.CreateJSON(
ctx,
zNode,
zkElectionObj,
false,
)
}
// AcquireLock acquires and returns a lock from the underlying zookeeper client.
// The Unlock method should be called on the lock when it's safe to release.
func (c *ZKAdminClient) AcquireLock(
ctx context.Context,
path string,
) (zk.Lock, error) {
return c.zkClient.AcquireLock(ctx, path)
}
// LockHeld determines whether the lock with the provided path is held (i.e., has children).
func (c *ZKAdminClient) LockHeld(
ctx context.Context,
path string,
) (bool, error) {
exists, _, err := c.zkClient.Exists(ctx, path)
if err != nil {
return false, err
}
if !exists {
return false, nil
}
children, _, err := c.zkClient.Children(ctx, path)
if err != nil {
return false, err
}
return len(children) > 0, nil
}
// GetSupportedFeatures returns the features that are supported by this client.
func (c *ZKAdminClient) GetSupportedFeatures() SupportedFeatures {
// The zk-based client supports everything except for ACLs.
// Zookeeper can support ACLs, topicctl just hasn't added support for it yet.
return SupportedFeatures{
Reads: true,
Applies: true,
Locks: true,
DynamicBrokerConfigs: true,
ACLs: false,
Users: false,
}
}
// Close closes the connections in the underlying zookeeper client.
func (c *ZKAdminClient) Close() error {
return c.zkClient.Close()
}
// getControllerAddr gets the address of the cluster controller. This is needed
// for creating new topics and other operations.
func (c *ZKAdminClient) getControllerAddr(
ctx context.Context,
) (string, error) {
conn, err := kafka.DefaultDialer.DialContext(ctx, "tcp", c.bootstrapAddrs[0])
if err != nil {
return "", err
}
defer conn.Close()
broker, err := conn.Controller()
if err != nil {
return "", err
}
return fmt.Sprintf("%s:%d", broker.Host, broker.Port), nil
}
func (c *ZKAdminClient) getTopic(
ctx context.Context,
name string,
detailed bool,
) (TopicInfo, error) {
log.Debugf("Getting info for topic %s", name)
topicInfo := TopicInfo{
Name: name,
Partitions: []PartitionInfo{},
}
zkTopicInfo := zkTopicInfo{}
_, err := c.zkClient.GetJSON(
ctx,
c.zNode(topicsPath, name),
&zkTopicInfo,
)
if err != nil {
return topicInfo, err
}
topicInfo.Version = zkTopicInfo.Version
zkTopicConfig := zkTopicConfig{}
_, err = c.zkClient.GetJSON(
ctx,
c.zNode(topicConfigsPath, name),
&zkTopicConfig,
)
if err != nil {
return topicInfo, err
}
topicInfo.Config = zkTopicConfig.Config
type partitionReq struct {
id int
replicas []int
detailed bool
}
type partitionResp struct {
partition PartitionInfo
err error
}
// This operation can be slow if there are a lot of partitions, distribute it out
partitionReqChan := make(chan partitionReq, len(zkTopicInfo.Partitions))
partitionRespChan := make(chan partitionResp, len(zkTopicInfo.Partitions))
for partitionIDStr, replicas := range zkTopicInfo.Partitions {
partitionID, err := strconv.ParseInt(partitionIDStr, 10, 32)
if err != nil {
return topicInfo, err
}
partitionReqChan <- partitionReq{
id: int(partitionID),
replicas: replicas,
detailed: detailed,
}
}
poolSize := minInt(len(zkTopicInfo.Partitions), maxPoolSize)
for i := 0; i < poolSize; i++ {
go func() {
for {
partitionReq, ok := <-partitionReqChan
if !ok {
return
}
partition, err := c.getPartition(
ctx,
partitionReq.id,
name,
partitionReq.detailed,
partitionReq.replicas,
)
partitionRespChan <- partitionResp{
partition: partition,
err: err,
}
}
}()
}
for i := 0; i < len(zkTopicInfo.Partitions); i++ {
partitionResp := <-partitionRespChan
if partitionResp.err != nil {
return topicInfo, err
}
topicInfo.Partitions = append(
topicInfo.Partitions,
partitionResp.partition,
)
}
sort.Slice(topicInfo.Partitions, func(i, j int) bool {
return topicInfo.Partitions[i].ID < topicInfo.Partitions[j].ID
})
return topicInfo, nil
}
func (c *ZKAdminClient) getPartition(
ctx context.Context,
id int,
topicName string,
detailed bool,
replicas []int,
) (PartitionInfo, error) {
partitionInfo := PartitionInfo{
Topic: topicName,
ID: int(id),
Replicas: replicas,
}
if detailed {
zkPartitionInfo := zkPartitionInfo{}
_, err := c.zkClient.GetJSON(
ctx,
c.zNode(
topicsPath,
topicName,
"partitions",
fmt.Sprintf("%d", id),
"state",
),
&zkPartitionInfo,
)
if err != nil {
return partitionInfo, err
}
partitionInfo.ControllerEpoch = zkPartitionInfo.ControllerEpoch
partitionInfo.ISR = zkPartitionInfo.ISR
partitionInfo.Leader = zkPartitionInfo.Leader
partitionInfo.ControllerEpoch = zkPartitionInfo.ControllerEpoch
partitionInfo.LeaderEpoch = zkPartitionInfo.LeaderEpoch
partitionInfo.Version = zkPartitionInfo.Version
}
return partitionInfo, nil
}