-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathtypes.go
More file actions
1369 lines (1147 loc) · 35.6 KB
/
types.go
File metadata and controls
1369 lines (1147 loc) · 35.6 KB
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 (
"encoding/json"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/segmentio/kafka-go"
"github.com/segmentio/topicctl/pkg/util"
log "github.com/sirupsen/logrus"
)
const (
// RetentionKey is the config key used for topic time retention.
RetentionKey = "retention.ms"
// LeaderThrottledKey is the config key for the leader throttle rate.
LeaderThrottledKey = "leader.replication.throttled.rate"
// FollowerThrottledKey is the config key for the follower throttle rate.
FollowerThrottledKey = "follower.replication.throttled.rate"
// LeaderReplicasThrottledKey is the config key for the list of leader replicas
// that should be throttled.
LeaderReplicasThrottledKey = "leader.replication.throttled.replicas"
// FollowerReplicasThrottledKey is the config key for the list of follower replicas
// that should be throttled.
FollowerReplicasThrottledKey = "follower.replication.throttled.replicas"
)
// BrokerInfo represents the information stored about a broker in zookeeper.
type BrokerInfo struct {
ID int `json:"id"`
Endpoints []string `json:"endpoints"`
Host string `json:"host"`
Port int32 `json:"port"`
InstanceID string `json:"instanceID"`
AvailabilityZone string `json:"availabilityZone"`
Rack string `json:"rack"`
InstanceType string `json:"instanceType"`
Version int `json:"version"`
Timestamp time.Time `json:"timestamp"`
Config map[string]string `json:"config"`
}
// TopicInfo represents the information stored about a topic in zookeeper.
type TopicInfo struct {
Name string `json:"name"`
Config map[string]string `json:"config"`
Partitions []PartitionInfo `json:"partitions"`
Version int `json:"version"`
}
// PartitionInfo represents the information stored about a topic
// partition in zookeeper.
type PartitionInfo struct {
Topic string `json:"topic"`
ID int `json:"ID"`
Leader int `json:"leader"`
Version int `json:"version"`
Replicas []int `json:"replicas"`
ISR []int `json:"isr"`
ControllerEpoch int `json:"controllerEpoch"`
LeaderEpoch int `json:"leaderEpoch"`
}
// PartitionAssignment contains the actual or desired assignment of
// replicas in a topic partition.
type PartitionAssignment struct {
ID int `json:"id"`
Replicas []int `json:"replicas"`
}
// PartitionInfo represents the information stored about an ACL
// in zookeeper.
type ACLInfo struct {
ResourceType ResourceType `json:"resourceType"`
ResourceName string `json:"resourceName"`
PatternType PatternType `json:"patternType"`
Principal string `json:"principal"`
Host string `json:"host"`
Operation ACLOperationType `json:"operation"`
PermissionType ACLPermissionType `json:"permissionType"`
}
// FormatACLInfo formats an ACLInfo struct as a string, using the
// string version of all the fields.
func FormatACLInfo(a ACLInfo) string {
alias := struct {
ResourceType string
ResourceName string
PatternType string
Principal string
Host string
Operation string
PermissionType string
}{
ResourceType: a.ResourceType.String(),
ResourceName: a.ResourceName,
PatternType: a.PatternType.String(),
Principal: a.Principal,
Host: a.Host,
Operation: a.Operation.String(),
PermissionType: a.PermissionType.String(),
}
content, err := json.MarshalIndent(alias, "", " ")
if err != nil {
log.Warnf("Error marshalling acls: %+v", err)
return "Error"
}
return string(content)
}
// ResourceType presents the Kafka resource type.
// We need to subtype this to be able to define methods to
// satisfy the Value interface from Cobra so we can use it
// as a Cobra flag.
type ResourceType kafka.ResourceType
var resourceTypeMap = map[string]kafka.ResourceType{
"any": kafka.ResourceTypeAny,
"topic": kafka.ResourceTypeTopic,
"group": kafka.ResourceTypeGroup,
"cluster": kafka.ResourceTypeCluster,
"transactionalid": kafka.ResourceTypeTransactionalID,
"delegationtoken": kafka.ResourceTypeDelegationToken,
}
// String is used both by fmt.Print and by Cobra in help text.
func (r *ResourceType) String() string {
switch kafka.ResourceType(*r) {
case kafka.ResourceTypeAny:
return "any"
case kafka.ResourceTypeTopic:
return "topic"
case kafka.ResourceTypeGroup:
return "group"
case kafka.ResourceTypeCluster:
return "cluster"
case kafka.ResourceTypeTransactionalID:
return "transactionalid"
case kafka.ResourceTypeDelegationToken:
return "delegationtoken"
default:
return "unknown"
}
}
// Set is used by Cobra to set the value of a variable from a Cobra flag.
func (r *ResourceType) Set(v string) error {
rt, ok := resourceTypeMap[strings.ToLower(v)]
if !ok {
return errors.New(`must be one of "any", "topic", "group", "cluster", "transactionalid", or "delegationtoken"`)
}
*r = ResourceType(rt)
return nil
}
// Type is used by Cobra in help text.
func (r *ResourceType) Type() string {
return "ResourceType"
}
// PatternType presents the Kafka pattern type.
// We need to subtype this to be able to define methods to
// satisfy the Value interface from Cobra so we can use it
// as a Cobra flag.
type PatternType kafka.PatternType
var patternTypeMap = map[string]kafka.PatternType{
"any": kafka.PatternTypeAny,
"match": kafka.PatternTypeMatch,
"literal": kafka.PatternTypeLiteral,
"prefixed": kafka.PatternTypePrefixed,
}
// String is used both by fmt.Print and by Cobra in help text.
func (p *PatternType) String() string {
switch kafka.PatternType(*p) {
case kafka.PatternTypeAny:
return "any"
case kafka.PatternTypeMatch:
return "match"
case kafka.PatternTypeLiteral:
return "literal"
case kafka.PatternTypePrefixed:
return "prefixed"
default:
return "unknown"
}
}
// Set is used by Cobra to set the value of a variable from a Cobra flag.
func (p *PatternType) Set(v string) error {
pt, ok := patternTypeMap[strings.ToLower(v)]
if !ok {
return errors.New(`must be one of "any", "match", "literal", or "prefixed"`)
}
*p = PatternType(pt)
return nil
}
// Type is used by Cobra in help text.
func (r *PatternType) Type() string {
return "PatternType"
}
// ACLOperationType presents the Kafka operation type.
// We need to subtype this to be able to define methods to
// satisfy the Value interface from Cobra so we can use it
// as a Cobra flag.
type ACLOperationType kafka.ACLOperationType
var aclOperationTypeMap = map[string]kafka.ACLOperationType{
"any": kafka.ACLOperationTypeAny,
"all": kafka.ACLOperationTypeAll,
"read": kafka.ACLOperationTypeRead,
"write": kafka.ACLOperationTypeWrite,
"create": kafka.ACLOperationTypeCreate,
"delete": kafka.ACLOperationTypeDelete,
"alter": kafka.ACLOperationTypeAlter,
"describe": kafka.ACLOperationTypeDescribe,
"clusteraction": kafka.ACLOperationTypeClusterAction,
"describeconfigs": kafka.ACLOperationTypeDescribeConfigs,
"alterconfigs": kafka.ACLOperationTypeAlterConfigs,
"idempotentwrite": kafka.ACLOperationTypeIdempotentWrite,
}
// String is used both by fmt.Print and by Cobra in help text.
func (o *ACLOperationType) String() string {
switch kafka.ACLOperationType(*o) {
case kafka.ACLOperationTypeAny:
return "any"
case kafka.ACLOperationTypeAll:
return "all"
case kafka.ACLOperationTypeRead:
return "read"
case kafka.ACLOperationTypeWrite:
return "write"
case kafka.ACLOperationTypeCreate:
return "create"
case kafka.ACLOperationTypeDelete:
return "delete"
case kafka.ACLOperationTypeAlter:
return "alter"
case kafka.ACLOperationTypeDescribe:
return "describe"
case kafka.ACLOperationTypeClusterAction:
return "clusteraction"
case kafka.ACLOperationTypeDescribeConfigs:
return "describeconfigs"
case kafka.ACLOperationTypeAlterConfigs:
return "alterconfigs"
case kafka.ACLOperationTypeIdempotentWrite:
return "idempotentwrite"
default:
return "unknown"
}
}
// Set is used by Cobra to set the value of a variable from a Cobra flag.
func (o *ACLOperationType) Set(v string) error {
ot, ok := aclOperationTypeMap[strings.ToLower(v)]
if !ok {
return errors.New(`must be one of "any", "all", "read", "write", "create", "delete", "alter", "describe", "clusteraction", "describeconfigs", "alterconfigs" or "idempotentwrite"`)
}
*o = ACLOperationType(ot)
return nil
}
// Type is used by Cobra in help text.
func (o *ACLOperationType) Type() string {
return "ACLOperationType"
}
// ACLPermissionType presents the Kafka operation type.
// We need to subtype this to be able to define methods to
// satisfy the Value interface from Cobra so we can use it
// as a Cobra flag.
type ACLPermissionType kafka.ACLPermissionType
var aclPermissionTypeMap = map[string]kafka.ACLPermissionType{
"any": kafka.ACLPermissionTypeAny,
"allow": kafka.ACLPermissionTypeAllow,
"deny": kafka.ACLPermissionTypeDeny,
}
// String is used both by fmt.Print and by Cobra in help text.
func (p *ACLPermissionType) String() string {
switch kafka.ACLPermissionType(*p) {
case kafka.ACLPermissionTypeAny:
return "any"
case kafka.ACLPermissionTypeDeny:
return "deny"
case kafka.ACLPermissionTypeAllow:
return "allow"
default:
return "unknown"
}
}
// Set is used by Cobra to set the value of a variable from a Cobra flag.
func (p *ACLPermissionType) Set(v string) error {
pt, ok := aclPermissionTypeMap[strings.ToLower(v)]
if !ok {
return errors.New(`must be one of "any", "allow", or "deny"`)
}
*p = ACLPermissionType(pt)
return nil
}
// Type is used by Cobra in help text.
func (p *ACLPermissionType) Type() string {
return "ACLPermissionType"
}
// UserInfo represents the information stored about a user
// in zookeeper.
type UserInfo struct {
Name string `json:"name"`
CredentialInfos []CredentialInfo `json:"credentialInfos"`
}
// CredentialInfo represents read only information about
// a users credentials in zookeeper.
type CredentialInfo struct {
ScramMechanism ScramMechanism `json:"scramMechanism"`
Iterations int `json:"iterations"`
}
// ScramMechanism represents the ScramMechanism used
// for a users credential in zookeeper.
type ScramMechanism kafka.ScramMechanism
func (s *ScramMechanism) String() string {
switch kafka.ScramMechanism(*s) {
case kafka.ScramMechanismSha256:
return "sha256"
case kafka.ScramMechanismSha512:
return "sha512"
default:
return "unknown"
}
}
type zkClusterID struct {
Version string `json:"version"`
ID string `json:"id"`
}
type zkControllerInfo struct {
Version int `json:"version"`
BrokerID int `json:"brokerid"`
Timestamp string `json:"timestamp"`
}
type zkBrokerInfo struct {
Endpoints []string `json:"endpoints"`
Host string `json:"host"`
Port int32 `json:"port"`
Rack string `json:"rack"`
TimestampStr string `json:"timestamp"`
Version int `json:"version"`
}
type zkBrokerConfig struct {
Version int `json:"version"`
Config map[string]string `json:"config"`
}
type zkTopicInfo struct {
Version int `json:"version"`
Partitions map[string][]int `json:"partitions"`
}
type zkTopicConfig struct {
Version int `json:"version"`
Config map[string]string `json:"config"`
}
type zkPartitionInfo struct {
Leader int `json:"leader"`
Version int `json:"version"`
ISR []int `json:"isr"`
ControllerEpoch int `json:"controller_epoch"`
LeaderEpoch int `json:"leader_epoch"`
}
type zkAssignment struct {
Version int `json:"version"`
Partitions []zkAssignmentPartition `json:"partitions"`
}
type zkAssignmentPartition struct {
Topic string `json:"topic"`
Partition int `json:"partition"`
Replicas []int `json:"replicas"`
}
type zkElection struct {
Version int `json:"version"`
Partitions []zkElectionTopicPartition `json:"partitions"`
}
type zkElectionTopicPartition struct {
Topic string `json:"topic"`
Partition int `json:"partition"`
}
type zkChangeNotification struct {
Version int `json:"version"`
EntityPath string `json:"entity_path"`
}
type PartitionStatus string
const (
Ok PartitionStatus = "OK"
Offline PartitionStatus = "Offline"
UnderReplicated PartitionStatus = "Under-replicated"
)
type PartitionLeaderState string
const (
CorrectLeader PartitionLeaderState = "OK"
WrongLeader PartitionLeaderState = "Wrong"
)
type PartitionStatusInfo struct {
Topic string
Partition kafka.Partition
Status PartitionStatus
LeaderState PartitionLeaderState
}
const (
ListenerNotFoundError kafka.Error = 72
)
// Addr returns the address of the current BrokerInfo.
func (b BrokerInfo) Addr() string {
return fmt.Sprintf("%s:%d", b.Host, b.Port)
}
// IsThrottled determines whether the broker has any throttles in its config.
func (b BrokerInfo) IsThrottled() bool {
_, leaderOk := b.Config[LeaderThrottledKey]
_, followerOk := b.Config[FollowerThrottledKey]
return leaderOk || followerOk
}
// BrokerIDs returns a slice of the IDs of the argument brokers.
func BrokerIDs(brokers []BrokerInfo) []int {
brokerIDs := []int{}
for _, broker := range brokers {
brokerIDs = append(brokerIDs, broker.ID)
}
return brokerIDs
}
// ThrottledBrokerIDs returns a slice of the IDs of the subset of
// argument brokers that have throttles on them.
func ThrottledBrokerIDs(brokers []BrokerInfo) []int {
brokerIDs := []int{}
for _, broker := range brokers {
if broker.IsThrottled() {
brokerIDs = append(brokerIDs, broker.ID)
}
}
return brokerIDs
}
// BrokerRacks returns a mapping of broker ID -> rack.
func BrokerRacks(brokers []BrokerInfo) map[int]string {
brokerRacks := map[int]string{}
for _, broker := range brokers {
brokerRacks[broker.ID] = broker.Rack
}
return brokerRacks
}
// BrokersPerRack returns a mapping of rack -> broker IDs.
func BrokersPerRack(brokers []BrokerInfo) map[string][]int {
brokersPerRack := map[string][]int{}
for _, broker := range brokers {
rack := broker.Rack
brokersPerRack[rack] = append(
brokersPerRack[rack],
broker.ID,
)
}
return brokersPerRack
}
// BrokerCountsPerRack returns a mapping of rack -> number of brokers.
func BrokerCountsPerRack(brokers []BrokerInfo) map[string]int {
brokersPerRack := BrokersPerRack(brokers)
brokerCountsPerRack := map[string]int{}
for rack, brokers := range brokersPerRack {
brokerCountsPerRack[rack] = len(brokers)
}
return brokerCountsPerRack
}
// DistinctRacks returns a sorted slice of all the distinct racks in the cluster.
func DistinctRacks(brokers []BrokerInfo) []string {
brokersPerRack := BrokersPerRack(brokers)
racks := []string{}
for rack := range brokersPerRack {
racks = append(racks, rack)
}
sort.Slice(racks, func(a, b int) bool {
return racks[a] < racks[b]
})
return racks
}
// LeadersPerRack returns a mapping of rack -> number of partitions with a leader
// in that rack.
func LeadersPerRack(brokers []BrokerInfo, topic TopicInfo) map[string]int {
leadersPerRack := map[string]int{}
brokerRacks := BrokerRacks(brokers)
for _, partition := range topic.Partitions {
leaderRack := brokerRacks[partition.Leader]
leadersPerRack[leaderRack]++
}
return leadersPerRack
}
// Retention returns the retention duration implied by a topic config. If
// unset, it returns 0.
func (t TopicInfo) Retention() time.Duration {
retentionStr, ok := t.Config[RetentionKey]
if !ok {
return 0
}
retention, err := strconv.ParseInt(retentionStr, 10, 64)
if err != nil {
return 0
}
return time.Duration(retention) * time.Millisecond
}
// PartitionIDs returns an ordered slice of partition IDs for a topic.
func (t TopicInfo) PartitionIDs() []int {
ids := []int{}
for _, partition := range t.Partitions {
ids = append(ids, partition.ID)
}
return ids
}
// MaxReplication returns the maximum number of replicas across all partitions
// in a topic.
func (t TopicInfo) MaxReplication() int {
maxReplication := 0
for _, partition := range t.Partitions {
if len(partition.Replicas) > maxReplication {
maxReplication = len(partition.Replicas)
}
}
return maxReplication
}
// MaxISR returns the maximum number of in-sync replicas across all partitions
// in a topic.
func (t TopicInfo) MaxISR() int {
maxISR := 0
for _, partition := range t.Partitions {
if len(partition.ISR) > maxISR {
maxISR = len(partition.ISR)
}
}
return maxISR
}
// RackCounts returns the minimum and maximum distinct rack counts across
// all partitions in a topic.
func (t TopicInfo) RackCounts(brokerRacks map[int]string) (int, int, error) {
var minRacks, maxRacks int
for p, partition := range t.Partitions {
numRacks, err := partition.NumRacks(brokerRacks)
if err != nil {
return 0, 0, err
}
if p == 0 {
minRacks = numRacks
maxRacks = numRacks
} else {
if numRacks < minRacks {
minRacks = numRacks
}
if numRacks > maxRacks {
maxRacks = numRacks
}
}
}
return minRacks, maxRacks, nil
}
// AllReplicasInSync returns whether all partitions have ISR == replicas
// (ignoring order).
func (t TopicInfo) AllReplicasInSync() bool {
for _, partition := range t.Partitions {
if !util.SameElements(partition.Replicas, partition.ISR) {
return false
}
}
return true
}
// OutOfSyncPartitions returns the partitions for which ISR != replicas
// (ignoring order).
func (t TopicInfo) OutOfSyncPartitions(subset []int) []PartitionInfo {
outOfSync := []PartitionInfo{}
subsetMap := map[int]struct{}{}
for _, id := range subset {
subsetMap[id] = struct{}{}
}
for _, partition := range t.Partitions {
if _, ok := subsetMap[partition.ID]; len(subset) > 0 && !ok {
continue
}
if !util.SameElements(partition.Replicas, partition.ISR) {
outOfSync = append(outOfSync, partition)
}
}
return outOfSync
}
// AllLeadersCorrect returns whether leader == replicas[0] for all partitions.
func (t TopicInfo) AllLeadersCorrect() bool {
for _, partition := range t.Partitions {
if partition.Leader != partition.Replicas[0] {
return false
}
}
return true
}
// WrongLeaderPartitions returns the partitions where leader != replicas[0].
func (t TopicInfo) WrongLeaderPartitions(subset []int) []PartitionInfo {
wrongLeaders := []PartitionInfo{}
subsetMap := map[int]struct{}{}
for _, id := range subset {
subsetMap[id] = struct{}{}
}
for _, partition := range t.Partitions {
if _, ok := subsetMap[partition.ID]; len(subset) > 0 && !ok {
continue
}
if partition.Leader != partition.Replicas[0] {
wrongLeaders = append(wrongLeaders, partition)
}
}
return wrongLeaders
}
// IsThrottled determines whether the topic has any throttles in its config.
func (t TopicInfo) IsThrottled() bool {
_, leaderOk := t.Config[LeaderReplicasThrottledKey]
_, followerOk := t.Config[FollowerReplicasThrottledKey]
return leaderOk || followerOk
}
// MaxReplication returns the maximum amount of replication across all partitions
// in the argument topics.
func MaxReplication(topics []TopicInfo) int {
maxReplication := 0
for _, topic := range topics {
topicReplication := topic.MaxReplication()
if topicReplication > maxReplication {
maxReplication = topicReplication
}
}
return maxReplication
}
// HasLeaders returns whether at least one partition in the argument topics has
// a non-zero leader set. Used for formatting purposes.
func HasLeaders(topics []TopicInfo) bool {
for _, topic := range topics {
for _, partition := range topic.Partitions {
if partition.Leader > 0 {
return true
}
}
}
return false
}
// ThrottledTopicNames returns the names of topics in the argument slice that
// have throttles on them.
func ThrottledTopicNames(topics []TopicInfo) []string {
throttledNames := []string{}
for _, topic := range topics {
if topic.IsThrottled() {
throttledNames = append(throttledNames, topic.Name)
}
}
return throttledNames
}
// Racks returns a slice of all racks for the partition replicas.
func (p PartitionInfo) Racks(brokerRacks map[int]string) ([]string, error) {
racks := []string{}
for _, brokerID := range p.Replicas {
rack, ok := brokerRacks[brokerID]
if !ok {
return nil, fmt.Errorf("Unrecognized broker ID: %d", brokerID)
}
racks = append(racks, rack)
}
return racks, nil
}
// Racks returns a slice of all racks for the partition replicas.
func (p PartitionStatusInfo) Racks(brokerRacks map[int]string) []string {
racks := []string{}
for _, replica := range p.Partition.Replicas {
rack, ok := brokerRacks[replica.ID]
if ok {
racks = append(racks, rack)
}
}
return racks
}
// NumRacks returns the number of distinct racks in the partition.
func (p PartitionInfo) NumRacks(brokerRacks map[int]string) (int, error) {
racksMap := map[string]struct{}{}
for _, brokerID := range p.Replicas {
rack, ok := brokerRacks[brokerID]
if !ok {
return 0, fmt.Errorf("Unrecognized broker ID: %d", brokerID)
}
racksMap[rack] = struct{}{}
}
return len(racksMap), nil
}
// ToAssignments converts a topic to a slice of partition assignments.
func (t TopicInfo) ToAssignments() []PartitionAssignment {
assignments := []PartitionAssignment{}
for _, partitionInfo := range t.Partitions {
assignments = append(
assignments,
PartitionAssignment{
ID: partitionInfo.ID,
Replicas: util.CopyInts(partitionInfo.Replicas),
},
)
}
return assignments
}
// PartitionIDs returns the IDs from the argument partitions.
func PartitionIDs(partitions []PartitionInfo) []int {
ids := []int{}
for _, partition := range partitions {
ids = append(ids, partition.ID)
}
return ids
}
// Index returns the index of the argument replica, or -1 if it can't
// be found.
func (a PartitionAssignment) Index(replica int) int {
for v, value := range a.Replicas {
if value == replica {
return v
}
}
return -1
}
// Copy returns a deep copy of this PartitionAssignment.
func (a PartitionAssignment) Copy() PartitionAssignment {
return PartitionAssignment{
ID: a.ID,
Replicas: util.CopyInts(a.Replicas),
}
}
// CopyAssignments returns a deep copy of the argument PartitionAssignment
// slice.
func CopyAssignments(
curr []PartitionAssignment,
) []PartitionAssignment {
copied := []PartitionAssignment{}
for _, assignment := range curr {
copied = append(copied, assignment.Copy())
}
return copied
}
// DistinctRacks returns a map of the distinct racks in this PartitionAssignment.
func (a PartitionAssignment) DistinctRacks(
brokerRacks map[int]string,
) map[string]struct{} {
racksMap := map[string]struct{}{}
for _, replica := range a.Replicas {
racksMap[brokerRacks[replica]] = struct{}{}
}
return racksMap
}
// CheckAssignments does some basic sanity checks on the assignments
// that are passed into an Assigner or extender so that we can fail early
// if something is obviously wrong.
func CheckAssignments(assignments []PartitionAssignment) error {
if len(assignments) == 0 {
return errors.New("Got zero-length slice")
}
var minReplicas, maxReplicas int
for a, assignment := range assignments {
numReplicas := len(assignment.Replicas)
if a == 0 {
minReplicas = numReplicas
maxReplicas = numReplicas
} else {
if numReplicas < minReplicas {
minReplicas = numReplicas
}
if numReplicas > maxReplicas {
maxReplicas = numReplicas
}
}
if a != assignment.ID {
return errors.New("Slice elements not in order")
}
if hasRepeats(assignment) {
return fmt.Errorf(
"Found repeated partition in assignment: %+v",
assignment,
)
}
}
if minReplicas != maxReplicas {
return fmt.Errorf(
"Partition replicas do not have consistent length (min: %d, max: %d)",
minReplicas,
maxReplicas,
)
}
return nil
}
func hasRepeats(assignment PartitionAssignment) bool {
replicasMap := map[int]struct{}{}
for _, replica := range assignment.Replicas {
if _, ok := replicasMap[replica]; ok {
return true
}
replicasMap[replica] = struct{}{}
}
return false
}
// ReplicasToAssignments converts a slice of slices to a slice of PartitionAssignments,
// assuming that the argument slices are in partition order. Used for unit tests.
func ReplicasToAssignments(
replicaSlices [][]int,
) []PartitionAssignment {
assignments := []PartitionAssignment{}
for p, replicas := range replicaSlices {
assignments = append(
assignments,
PartitionAssignment{
ID: p,
Replicas: util.CopyInts(replicas),
},
)
}
return assignments
}
// AssignmentsToReplicas is the inverse of ReplicasToAssignments. Used for unit
// tests.
func AssignmentsToReplicas(assignments []PartitionAssignment) ([][]int, error) {
replicaSlices := [][]int{}
for a, assignment := range assignments {
if a != assignment.ID {
return nil, errors.New("Assignments are not in order")
}
replicaSlices = append(
replicaSlices,
assignment.Replicas,
)
}
return replicaSlices, nil
}
// MaxPartitionsPerBroker calculates the number of partitions that each broker may
// need to handle during a migration.
func MaxPartitionsPerBroker(
allAssignments ...[]PartitionAssignment,
) map[int]int {
assignmentsPerPartition := map[int][]PartitionAssignment{}
for _, assignments := range allAssignments {
for _, assignment := range assignments {
assignmentsPerPartition[assignment.ID] = append(
assignmentsPerPartition[assignment.ID],
assignment,
)
}
}
partitionsPerBrokerMap := map[int]map[int]struct{}{}
for partition, assignments := range assignmentsPerPartition {
partitionsPerBrokerMap[partition] = map[int]struct{}{}
for _, assignment := range assignments {
for _, replica := range assignment.Replicas {
partitionsPerBrokerMap[partition][replica] = struct{}{}
}
}