-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathdata_placement_mgr.go
More file actions
2508 lines (2364 loc) · 78.8 KB
/
data_placement_mgr.go
File metadata and controls
2508 lines (2364 loc) · 78.8 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 consistence
import (
"container/heap"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/twmb/murmur3"
"github.com/youzan/nsq/nsqd"
)
// new topic can have an advice load factor to give the suggestion about the
// future load. While the topic data is small the load compute is not precise,
// so we use the advised load to determine the actual topic load.
// use 1~10 to advise from lowest to highest. The 1 or 10 should be used with much careful.
// TODO: separate the high peak topics to avoid too much high peak on node
// left consume data size level: 0~1GB low, < 5GB medium, < 50GB high , >=50GB very high
// left data size level: <5GB low, <50GB medium , <200GB high, >=200GB very high
// for common topic we do not allow the partition large than nodes,
// To balance the load across nodes, we make the leader across each nodes from
// the idle node to the busy node.
// and to avoid the data migration, we should keep the data as much as possible
// algorithm as below:
// 1. sort node id by the load factor;
// 2. sort the topic partitions
// 3. choose the leader for each partition (ignore the partition already assigned)
// start from the begin index of the current available node array
// 4. choose the followers for each partition,
// start from the begin index of node array and filter out the already assigned node
// for the other partitions.
// l -> leader, f-> follower
// nodeA nodeB nodeC nodeD
// p1 l f f
// p2 l f f
// p3 f l f
// after nodeB is down, keep the data no move, and
// choose the node for the missing leader from isr list (filter out the node which
// is assigned to other partition leaders) with the lowest load factor.
// if alive nodes less than partitions we will fail to elect the new leader
// and choose the missing isr with the lowest load node from current alive nodes (filter out the
// node already exist other partitions)
// nodeA xxxx nodeC nodeD
// p1 l x f x-f
// p2 x-f x f f-l
// p3 f l f
var (
ErrBalanceNodeUnavailable = errors.New("can not find a node to be balanced")
ErrNodeIsExcludedForTopicData = errors.New("destination node is excluded for topic")
ErrClusterBalanceRunning = errors.New("another balance is running, should wait")
errMoveTopicWaitTimeout = errors.New("timeout waiting move topic")
)
var topicTopNLimit = 100
var topNBalanceDiff = 3
var moveWaitTimeout = time.Minute * 10
const (
RATIO_BETWEEN_LEADER_FOLLOWER = 0.7
defaultTopicLoadFactor = 3
HIGHEST_PUB_QPS_LEVEL = 100
HIGHEST_LEFT_CONSUME_MB_SIZE = 50 * 1024
HIGHEST_LEFT_DATA_MB_SIZE = 200 * 1024
busyTopicLevel = 15
)
type balanceOpLevel int
const (
moveAny balanceOpLevel = iota
moveTryIdle
moveMinLFOnly
)
// pub qps level : 1~13 low (< 30 KB/sec), 13 ~ 31 medium (<1000 KB/sec), 31 ~ 74 high (<8 MB/sec), >74 very high (>8 MB/sec)
func convertQPSLevel(hourlyPubSize int64) float64 {
qps := hourlyPubSize / 3600 / 1024
if qps <= 3 {
return 1.0 + float64(qps)
} else if qps <= 30 {
return 4.0 + float64(qps-3)/3
} else if qps <= 300 {
return 13.0 + float64(qps-30)/15
} else if qps <= 1000 {
return 31.0 + float64(qps-300)/35
} else if qps <= 2000 {
return 51.0 + math.Log2(1.0+float64(qps-1000))
} else if qps <= 8000 {
return 61.0 + math.Log2(1.0+float64(qps-2000))
} else if qps <= 16000 {
return 74.0 + math.Log2(1.0+float64(qps-8000))
}
return HIGHEST_PUB_QPS_LEVEL
}
func splitTopicPartitionID(topicFullName string) (string, int, error) {
partIndex := strings.LastIndex(topicFullName, "-")
if partIndex == -1 {
return "", 0, fmt.Errorf("invalid topic full name: %v", topicFullName)
}
topicName := topicFullName[:partIndex]
partitionID, err := strconv.Atoi(topicFullName[partIndex+1:])
return topicName, partitionID, err
}
// An IntHeap is a min-heap of ints.
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
type WrapChannelConsumerOffset struct {
Name string
ChannelConsumerOffset
}
type cachedNodeTopicStats struct {
stats *NodeTopicStats
lastTime time.Time
}
type NodeTopicStats struct {
NodeID string
// the data (MB) need to be consumed on the leader for all channels in the topic.
ChannelDepthData map[string]int64
// the data left on disk. unit: MB
TopicLeaderDataSize map[string]int64
TopicTotalDataSize map[string]int64
NodeCPUs int
// the pub stat for past 24hr
TopicHourlyPubDataList map[string][24]int64
ChannelNum map[string]int
ChannelList map[string][]string
ChannelMetas map[string][]nsqd.ChannelMetaInfo
ChannelOffsets map[string][]WrapChannelConsumerOffset
}
func getNodeNameList(nodes []NodeTopicStats) []string {
nameList := make([]string, 0, len(nodes))
for _, s := range nodes {
nameList = append(nameList, s.NodeID)
}
return nameList
}
func getTopicInfoMap(topicList []TopicPartitionMetaInfo) map[string]TopicPartitionMetaInfo {
tinfoMap := make(map[string]TopicPartitionMetaInfo, len(topicList))
for _, tinfo := range topicList {
tinfoMap[tinfo.GetTopicDesp()] = tinfo
}
return tinfoMap
}
func NewNodeTopicStats(nid string, cap int, cpus int) *NodeTopicStats {
return &NodeTopicStats{
NodeID: nid,
ChannelDepthData: make(map[string]int64, cap),
TopicLeaderDataSize: make(map[string]int64, cap),
TopicTotalDataSize: make(map[string]int64, cap),
TopicHourlyPubDataList: make(map[string][24]int64, cap),
ChannelNum: make(map[string]int, cap),
ChannelList: make(map[string][]string),
ChannelMetas: make(map[string][]nsqd.ChannelMetaInfo),
ChannelOffsets: make(map[string][]WrapChannelConsumerOffset),
NodeCPUs: cpus,
}
}
// the load factor is something like cpu load factor that
// stand for the busy/idle state for this node.
// the larger means busier.
// 80% recent avg load in 24hr + 10% left need to be consumed + 10% data size left
func (nts *NodeTopicStats) GetNodeLoadFactor() (float64, float64) {
leaderLF := nts.GetNodeLeaderLoadFactor()
totalDataSize := int64(0)
for _, v := range nts.TopicTotalDataSize {
totalDataSize += v
}
totalDataSize += int64(len(nts.TopicTotalDataSize))
if totalDataSize > HIGHEST_LEFT_DATA_MB_SIZE {
totalDataSize = HIGHEST_LEFT_DATA_MB_SIZE
}
return leaderLF, leaderLF + float64(totalDataSize)/HIGHEST_LEFT_DATA_MB_SIZE*5
}
func (nts *NodeTopicStats) GetNodeLeaderLoadFactor() float64 {
leftConsumed := int64(0)
for _, t := range nts.ChannelDepthData {
leftConsumed += t
}
leftConsumed += int64(len(nts.ChannelDepthData))
if leftConsumed > HIGHEST_LEFT_CONSUME_MB_SIZE {
leftConsumed = HIGHEST_LEFT_CONSUME_MB_SIZE
}
totalLeaderDataSize := int64(0)
for _, v := range nts.TopicLeaderDataSize {
totalLeaderDataSize += v
}
totalLeaderDataSize += int64(len(nts.TopicLeaderDataSize))
if totalLeaderDataSize > HIGHEST_LEFT_DATA_MB_SIZE {
totalLeaderDataSize = HIGHEST_LEFT_DATA_MB_SIZE
}
avgWrite := nts.GetNodeAvgWriteLevel()
if avgWrite > HIGHEST_PUB_QPS_LEVEL {
avgWrite = HIGHEST_PUB_QPS_LEVEL
}
return avgWrite/HIGHEST_PUB_QPS_LEVEL*80.0 + float64(leftConsumed)/HIGHEST_LEFT_CONSUME_MB_SIZE*10.0 + float64(totalLeaderDataSize)/HIGHEST_LEFT_DATA_MB_SIZE*10.0
}
func (nts *NodeTopicStats) GetNodePeakLevelList() []int64 {
levelList := make([]int64, 8)
for _, dataList := range nts.TopicHourlyPubDataList {
peak := int64(10)
for _, data := range dataList {
if data > peak {
peak = data
}
}
index := int(convertQPSLevel(peak))
if index > HIGHEST_PUB_QPS_LEVEL {
index = HIGHEST_PUB_QPS_LEVEL
}
levelList[index]++
}
return levelList
}
func (nts *NodeTopicStats) GetNodeAvgWriteLevel() float64 {
level := int64(0)
tmp := make(IntHeap, 0, 24)
for _, dataList := range nts.TopicHourlyPubDataList {
sum := int64(10)
cnt := 0
tmp = tmp[:0]
heap.Init(&tmp)
for _, data := range dataList {
sum += data
cnt++
heap.Push(&tmp, int(data))
}
// remove the lowest 1/4 (at midnight all topics are low)
for i := 0; i < len(dataList)/4; i++ {
v := heap.Pop(&tmp)
sum -= int64(v.(int))
cnt--
}
sum = sum / int64(cnt)
level += sum
}
return convertQPSLevel(level)
}
func (nts *NodeTopicStats) GetNodeAvgReadLevel() float64 {
level := float64(0)
tmp := make(IntHeap, 0, 24)
for topicName, dataList := range nts.TopicHourlyPubDataList {
sum := int64(10)
cnt := 0
tmp = tmp[:0]
heap.Init(&tmp)
for _, data := range dataList {
sum += data
cnt++
heap.Push(&tmp, int(data))
}
for i := 0; i < len(dataList)/4; i++ {
v := heap.Pop(&tmp)
sum -= int64(v.(int))
cnt--
}
sum = sum / int64(cnt)
num, ok := nts.ChannelNum[topicName]
if ok {
level += math.Log2(1.0+float64(num)) * float64(sum)
}
}
return convertQPSLevel(int64(level))
}
func (nts *NodeTopicStats) GetTopicLoadFactor(topicFullName string) float64 {
data := nts.TopicTotalDataSize[topicFullName]
if data > HIGHEST_LEFT_DATA_MB_SIZE {
data = HIGHEST_LEFT_DATA_MB_SIZE
}
return nts.GetTopicLeaderLoadFactor(topicFullName) + float64(data)/HIGHEST_LEFT_DATA_MB_SIZE*5.0
}
func (nts *NodeTopicStats) GetTopicLeaderLoadFactor(topicFullName string) float64 {
writeLevel := nts.GetTopicAvgWriteLevel(topicFullName)
depth := nts.ChannelDepthData[topicFullName]
if depth > HIGHEST_LEFT_CONSUME_MB_SIZE {
depth = HIGHEST_LEFT_CONSUME_MB_SIZE
}
data := nts.TopicLeaderDataSize[topicFullName]
if data > HIGHEST_LEFT_DATA_MB_SIZE {
data = HIGHEST_LEFT_DATA_MB_SIZE
}
return writeLevel/HIGHEST_PUB_QPS_LEVEL*80.0 + float64(depth)/HIGHEST_LEFT_CONSUME_MB_SIZE*10.0 + float64(data)/HIGHEST_LEFT_DATA_MB_SIZE*10.0
}
func (nts *NodeTopicStats) GetTopicAvgWriteLevel(topicFullName string) float64 {
dataList, ok := nts.TopicHourlyPubDataList[topicFullName]
if ok {
sum := int64(10)
cnt := 0
tmp := make(IntHeap, 0, len(dataList))
heap.Init(&tmp)
for _, data := range dataList {
sum += data
cnt++
heap.Push(&tmp, int(data))
}
for i := 0; i < len(dataList)/4; i++ {
v := heap.Pop(&tmp)
sum -= int64(v.(int))
cnt--
}
sum = sum / int64(cnt)
return convertQPSLevel(sum)
}
return 1.0
}
type loadFactorInfo struct {
name string
topic string
loadFactor float64
}
func (lf *loadFactorInfo) GetTopic() string {
return lf.topic
}
func (lf *loadFactorInfo) GetLF() float64 {
return lf.loadFactor
}
type LFListT []loadFactorInfo
func (s LFListT) Len() int {
return len(s)
}
func (s LFListT) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s LFListT) Less(i, j int) bool {
if math.Abs(s[i].loadFactor-s[j].loadFactor) < 1 {
return s[i].topic < s[j].topic
}
return s[i].loadFactor < s[j].loadFactor
}
func (nts *NodeTopicStats) GetSortedTopicWriteLevel(leaderOnly bool) LFListT {
topicLFList := make(LFListT, 0)
for topicName := range nts.TopicHourlyPubDataList {
d, ok := nts.TopicLeaderDataSize[topicName]
if leaderOnly {
if !ok || d <= 0 {
continue
}
}
lf := 0.0
if leaderOnly {
lf = nts.GetTopicLeaderLoadFactor(topicName)
} else {
lf = nts.GetTopicLoadFactor(topicName)
}
topicLFList = append(topicLFList, loadFactorInfo{
topic: topicName,
loadFactor: lf,
})
}
sort.Sort(topicLFList)
return topicLFList
}
func (nts *NodeTopicStats) GetMostBusyAndIdleTopicWriteLevel(leaderOnly bool) (string, string, float64, float64) {
busy := float64(0.0)
busyTopic := ""
idle := float64(math.MaxInt32)
idleTopic := ""
for topicName := range nts.TopicHourlyPubDataList {
d, ok := nts.TopicLeaderDataSize[topicName]
if leaderOnly {
if !ok || d <= 0 {
continue
}
} else {
if ok && d > 0 {
continue
}
}
sum := 0.0
if leaderOnly {
sum = nts.GetTopicLeaderLoadFactor(topicName)
} else {
sum = nts.GetTopicLoadFactor(topicName)
}
if sum > busy {
busy = sum
busyTopic = topicName
}
if sum < idle {
idle = sum
idleTopic = topicName
}
}
return idleTopic, busyTopic, idle, busy
}
func (nts *NodeTopicStats) GetTopicPeakLevel(topic TopicPartitionID) float64 {
selectedTopic := topic.String()
dataList, ok := nts.TopicHourlyPubDataList[selectedTopic]
if ok {
peak := int64(10)
for _, data := range dataList {
if data > peak {
peak = data
}
}
return convertQPSLevel(peak)
}
return 1.0
}
func (nts *NodeTopicStats) LeaderLessLoader(other *NodeTopicStats) bool {
left := nts.GetNodeLeaderLoadFactor()
right := other.GetNodeLeaderLoadFactor()
if math.Abs(left-right) < 0.5 {
left := float64(len(nts.TopicLeaderDataSize)) + float64(len(nts.TopicTotalDataSize)-len(nts.TopicLeaderDataSize))*RATIO_BETWEEN_LEADER_FOLLOWER
right := float64(len(other.TopicLeaderDataSize)) + float64(len(other.TopicTotalDataSize)-len(other.TopicLeaderDataSize))*RATIO_BETWEEN_LEADER_FOLLOWER
return left < right
}
if left < right {
return true
}
return false
}
func (nts *NodeTopicStats) SlaveLessLoader(other *NodeTopicStats) bool {
_, left := nts.GetNodeLoadFactor()
_, right := other.GetNodeLoadFactor()
if math.Abs(left-right) < 0.5 {
left := float64(len(nts.TopicLeaderDataSize)) + float64(len(nts.TopicTotalDataSize)-len(nts.TopicLeaderDataSize))*RATIO_BETWEEN_LEADER_FOLLOWER
right := float64(len(other.TopicLeaderDataSize)) + float64(len(other.TopicTotalDataSize)-len(other.TopicLeaderDataSize))*RATIO_BETWEEN_LEADER_FOLLOWER
return left < right
}
if left < right {
return true
}
return false
}
type By func(l, r *NodeTopicStats) bool
func (by By) Sort(statList []NodeTopicStats) {
sorter := &StatsSorter{
stats: statList,
by: by,
}
sort.Sort(sorter)
}
type StatsSorter struct {
stats []NodeTopicStats
by By
}
func (s *StatsSorter) Len() int {
return len(s.stats)
}
func (s *StatsSorter) Swap(i, j int) {
s.stats[i], s.stats[j] = s.stats[j], s.stats[i]
}
func (s *StatsSorter) Less(i, j int) bool {
return s.by(&s.stats[i], &s.stats[j])
}
type DataPlacement struct {
balanceInterval [2]int
lookupCoord *NsqLookupCoordinator
}
func NewDataPlacement(coord *NsqLookupCoordinator) *DataPlacement {
return &DataPlacement{
lookupCoord: coord,
balanceInterval: [2]int{2, 4},
}
}
func (dpm *DataPlacement) SetBalanceInterval(start int, end int) {
if start == end && start == 0 {
return
}
dpm.balanceInterval[0] = start
dpm.balanceInterval[1] = end
}
type nodeLoadInfo struct {
avgLeaderLoad float64
minLeaderLoad float64
maxLeaderLoad float64
avgNodeLoad float64
minNodeLoad float64
maxNodeLoad float64
validNum int
mostLeaderStats *NodeTopicStats
mostLeaderNum int
leastLeaderStats *NodeTopicStats
leastLeaderNum int
}
func newLoadInfo() nodeLoadInfo {
return nodeLoadInfo{
avgLeaderLoad: 0.0,
minLeaderLoad: float64(math.MaxInt32),
maxLeaderLoad: 0.0,
avgNodeLoad: 0.0,
minNodeLoad: float64(math.MaxInt32),
maxNodeLoad: 0.0,
leastLeaderNum: math.MaxInt32,
}
}
func (dpm *DataPlacement) getLeaderSortedNodeTopicStats(currentNodes map[string]NsqdNodeInfo, nodeTopicStats []NodeTopicStats) []NodeTopicStats {
nodeTopicStats = nodeTopicStats[:0]
for nodeID, nodeInfo := range currentNodes {
topicStat, err := dpm.lookupCoord.getNsqdTopicStat(nodeInfo)
if err != nil {
coordLog.Infof("failed to get node topic status while checking balance: %v", nodeID)
continue
}
nodeTopicStats = append(nodeTopicStats, *topicStat)
}
leaderSort := func(l, r *NodeTopicStats) bool {
return l.LeaderLessLoader(r)
}
By(leaderSort).Sort(nodeTopicStats)
return nodeTopicStats
}
func computeNodeLoadInfo(nodeTopicStats []NodeTopicStats, topicStatsMinMax []*NodeTopicStats) ([]*NodeTopicStats, nodeLoadInfo) {
nload := newLoadInfo()
for _, tstat := range nodeTopicStats {
topicStat := tstat
nodeID := topicStat.NodeID
leaderLF, nodeLF := topicStat.GetNodeLoadFactor()
coordLog.Infof("nsqd node %v load factor is : (%v, %v)", nodeID, leaderLF, nodeLF)
if leaderLF < nload.minLeaderLoad {
topicStatsMinMax[0] = &topicStat
nload.minLeaderLoad = leaderLF
}
nload.minNodeLoad = math.Min(nodeLF, nload.minNodeLoad)
if leaderLF > nload.maxLeaderLoad {
topicStatsMinMax[1] = &topicStat
nload.maxLeaderLoad = leaderLF
}
nload.maxNodeLoad = math.Max(nodeLF, nload.maxNodeLoad)
nload.avgLeaderLoad += leaderLF
nload.avgNodeLoad += nodeLF
nload.validNum++
leaderNum := len(topicStat.TopicLeaderDataSize)
if leaderNum > nload.mostLeaderNum {
nload.mostLeaderNum = leaderNum
nload.mostLeaderStats = &topicStat
}
if leaderNum < nload.leastLeaderNum {
nload.leastLeaderNum = leaderNum
nload.leastLeaderStats = &topicStat
}
}
return topicStatsMinMax, nload
}
func (dpm *DataPlacement) isTopNBalanceEnabled() bool {
return atomic.LoadInt32(&dpm.lookupCoord.enableTopNBalance) == 1
}
func (dpm *DataPlacement) DoBalance(monitorChan chan struct{}) {
//check period for the data balance.
ticker := time.NewTicker(balanceInterval)
defer func() {
ticker.Stop()
coordLog.Infof("balance check exit.")
}()
topicStatsMinMax := make([]*NodeTopicStats, 2)
nodeTopicStats := make([]NodeTopicStats, 0, 10)
for {
select {
case <-monitorChan:
return
case <-ticker.C:
// only balance at given interval
if time.Now().Hour() > dpm.balanceInterval[1] || time.Now().Hour() < dpm.balanceInterval[0] {
continue
}
if !dpm.lookupCoord.IsMineLeader() {
coordLog.Infof("not leader while checking balance")
continue
}
if !dpm.lookupCoord.IsClusterStable() {
coordLog.Infof("no balance since cluster is not stable while checking balance")
continue
}
// if max load is 4 times more than avg load, we need move some
// leader from max to min load node one by one.
// if min load is 4 times less than avg load, we can move some
// leader to this min load node.
coordLog.Infof("begin checking balance of topic data...")
moved, _ := dpm.rebalanceMultiPartTopic(monitorChan)
if moved {
continue
}
currentNodes := dpm.lookupCoord.getCurrentNodes()
nodeTopicStats = dpm.getLeaderSortedNodeTopicStats(currentNodes, nodeTopicStats)
topicList, err := dpm.lookupCoord.leadership.ScanTopics()
if err != nil {
coordLog.Infof("scan topics error: %v", err)
continue
}
if len(topicList) <= len(currentNodes)*2 {
coordLog.Infof("the topics less than nodes, no need balance: %v ", len(topicList))
continue
}
var topNTopics LFListT
if dpm.isTopNBalanceEnabled() {
topNBalanced := false
//topNBalanced, _, topNTopics = dpm.rebalanceTopNTopics(monitorChan, nodeTopicStats)
topNBalanced, _, topNTopics = dpm.rebalanceTopNTopicsByLoad(monitorChan,
topicList, nodeTopicStats, currentNodes)
if !topNBalanced {
continue
}
}
// filter out topN topics
for _, s := range nodeTopicStats {
beforeCnt := len(s.TopicTotalDataSize)
for _, t := range topNTopics {
topicName := t.topic
delete(s.ChannelDepthData, topicName)
delete(s.ChannelList, topicName)
delete(s.ChannelNum, topicName)
delete(s.ChannelOffsets, topicName)
delete(s.TopicHourlyPubDataList, topicName)
delete(s.TopicLeaderDataSize, topicName)
delete(s.TopicTotalDataSize, topicName)
}
afterCnt := len(s.TopicTotalDataSize)
coordLog.Infof("node %v filter topn from %v to %v", s.NodeID, beforeCnt, afterCnt)
}
var nload nodeLoadInfo
topicStatsMinMax, nload = computeNodeLoadInfo(nodeTopicStats, topicStatsMinMax)
avgLeaderLoad := nload.avgLeaderLoad
minLeaderLoad := nload.minLeaderLoad
maxLeaderLoad := nload.maxLeaderLoad
avgNodeLoad := nload.avgNodeLoad
minNodeLoad := nload.minNodeLoad
maxNodeLoad := nload.maxNodeLoad
validNum := nload.validNum
mostLeaderStats := nload.mostLeaderStats
mostLeaderNum := nload.mostLeaderNum
leastLeaderStats := nload.leastLeaderStats
leastLeaderNum := nload.leastLeaderNum
if validNum < 2 || topicStatsMinMax[0] == nil || topicStatsMinMax[1] == nil {
continue
}
midLeaderLoad, _ := nodeTopicStats[len(nodeTopicStats)/2].GetNodeLoadFactor()
nodeTopicStatsSortedSlave := make([]NodeTopicStats, len(nodeTopicStats))
copy(nodeTopicStatsSortedSlave, nodeTopicStats)
nodeSort := func(l, r *NodeTopicStats) bool {
return l.SlaveLessLoader(r)
}
By(nodeSort).Sort(nodeTopicStatsSortedSlave)
_, midNodeLoad := nodeTopicStatsSortedSlave[len(nodeTopicStatsSortedSlave)/2].GetNodeLoadFactor()
avgLeaderLoad = avgLeaderLoad / float64(validNum)
avgNodeLoad = avgNodeLoad / float64(validNum)
coordLog.Infof("min/avg/mid/max leader load %v, %v, %v, %v", minLeaderLoad, avgLeaderLoad, midLeaderLoad, maxLeaderLoad)
coordLog.Infof("min/avg/mid/max node load %v, %v, %v, %v", minNodeLoad, avgNodeLoad, midNodeLoad, maxNodeLoad)
if len(topicStatsMinMax[1].TopicHourlyPubDataList) <= 2 {
coordLog.Infof("the topic number is so less on both nodes, no need balance: %v", topicStatsMinMax[1])
continue
}
moveLeader := false
avgTopicNum := len(topicList) / len(currentNodes)
if len(topicStatsMinMax[1].TopicLeaderDataSize) > int(1.2*float64(avgTopicNum)) {
// too many leader topics on this node, try move leader topic
coordLog.Infof("move leader topic since leader is more than follower on node")
moveLeader = true
} else {
// too many replica topics on this node, try move replica topic to others
coordLog.Infof("move follower topic since follower is more than leader on node")
}
if minLeaderLoad*4 < avgLeaderLoad {
// move some topic from the most busy node to the most idle node
dpm.balanceTopicLeaderBetweenNodes(monitorChan, moveLeader, moveMinLFOnly, minLeaderLoad,
maxLeaderLoad, topicStatsMinMax, nodeTopicStats)
} else if avgLeaderLoad < 4 && maxLeaderLoad < 8 {
// all nodes in the cluster are under low load, no need balance
continue
} else if avgLeaderLoad*2 < maxLeaderLoad {
dpm.balanceTopicLeaderBetweenNodes(monitorChan, moveLeader, moveAny, minLeaderLoad,
maxLeaderLoad, topicStatsMinMax, nodeTopicStats)
} else if avgLeaderLoad >= 20 &&
((minLeaderLoad*1.5 < maxLeaderLoad) || (maxLeaderLoad > avgLeaderLoad*1.3)) {
dpm.balanceTopicLeaderBetweenNodes(monitorChan, moveLeader,
moveTryIdle, minLeaderLoad, maxLeaderLoad,
topicStatsMinMax, nodeTopicStats)
} else if minNodeLoad*4 < avgNodeLoad {
topicStatsMinMax[0] = &nodeTopicStatsSortedSlave[0]
topicStatsMinMax[1] = &nodeTopicStatsSortedSlave[len(nodeTopicStatsSortedSlave)-1]
moveLeader = len(topicStatsMinMax[1].TopicLeaderDataSize) > len(topicStatsMinMax[1].TopicTotalDataSize)/2
dpm.balanceTopicLeaderBetweenNodes(monitorChan, moveLeader, moveMinLFOnly, minNodeLoad,
maxNodeLoad, topicStatsMinMax, nodeTopicStatsSortedSlave)
} else if avgNodeLoad*2 < maxNodeLoad {
topicStatsMinMax[0] = &nodeTopicStatsSortedSlave[0]
topicStatsMinMax[1] = &nodeTopicStatsSortedSlave[len(nodeTopicStatsSortedSlave)-1]
moveLeader = len(topicStatsMinMax[1].TopicLeaderDataSize) > len(topicStatsMinMax[1].TopicTotalDataSize)/2
dpm.balanceTopicLeaderBetweenNodes(monitorChan, moveLeader, moveAny, minNodeLoad,
maxNodeLoad, topicStatsMinMax, nodeTopicStatsSortedSlave)
} else if avgNodeLoad >= 20 &&
(minNodeLoad*1.5 < maxNodeLoad || maxNodeLoad > avgNodeLoad*1.3) {
topicStatsMinMax[0] = &nodeTopicStatsSortedSlave[0]
topicStatsMinMax[1] = &nodeTopicStatsSortedSlave[len(nodeTopicStatsSortedSlave)-1]
moveLeader = len(topicStatsMinMax[1].TopicLeaderDataSize) > len(topicStatsMinMax[1].TopicTotalDataSize)/2
dpm.balanceTopicLeaderBetweenNodes(monitorChan, moveLeader,
moveTryIdle, minNodeLoad, maxNodeLoad,
topicStatsMinMax, nodeTopicStatsSortedSlave)
} else {
if mostLeaderStats != nil && avgTopicNum > 10 && mostLeaderNum > int(float64(avgTopicNum)*1.3) {
needMove := checkMoveLotsOfTopics(true, mostLeaderNum, mostLeaderStats,
avgTopicNum, topicStatsMinMax, midLeaderLoad)
if needMove {
topicStatsMinMax[1] = mostLeaderStats
leaderLF, _ := mostLeaderStats.GetNodeLoadFactor()
maxLeaderLoad = leaderLF
dpm.balanceTopicLeaderBetweenNodes(monitorChan, true, moveTryIdle, minLeaderLoad,
maxLeaderLoad, topicStatsMinMax, nodeTopicStats)
continue
}
}
// so less leader topics maybe means too much replicas on this node
if leastLeaderStats != nil && avgTopicNum > 10 && leastLeaderNum < int(float64(avgTopicNum)*0.7) {
// TODO: check if we can move a follower topic to leader from other nodes
leaderLF, nodeLF := leastLeaderStats.GetNodeLoadFactor()
needMove := true
moveLeader = true
followerNum := len(leastLeaderStats.TopicTotalDataSize) - leastLeaderNum
moveToMinLF := moveTryIdle
if nodeLF > avgNodeLoad || leaderLF > midLeaderLoad {
// maybe too much topic followers on this node
if leastLeaderStats.NodeID == topicStatsMinMax[1].NodeID && followerNum > avgTopicNum {
moveLeader = false
} else if followerNum > int(float64(avgTopicNum)*1.3) {
// too much followers
coordLog.Infof("move follower topic since less leader and much follower on node: %v, %v, avg %v",
leastLeaderStats.NodeID, followerNum, avgTopicNum)
moveLeader = false
topicStatsMinMax[1] = leastLeaderStats
maxLeaderLoad = nodeLF
} else {
needMove = false
}
} else if leaderLF < midLeaderLoad {
topicStatsMinMax[0] = leastLeaderStats
minLeaderLoad = leaderLF
moveToMinLF = moveMinLFOnly
coordLog.Infof("so less topic leader (%v) on idle node: %v, try move some topic leader to this node",
leastLeaderNum, leastLeaderStats.NodeID)
} else {
needMove = false
}
if needMove {
dpm.balanceTopicLeaderBetweenNodes(monitorChan, moveLeader, moveToMinLF, minLeaderLoad,
maxLeaderLoad, topicStatsMinMax, nodeTopicStats)
continue
}
}
mostTopicNum := len(nodeTopicStatsSortedSlave[len(nodeTopicStatsSortedSlave)-1].TopicTotalDataSize)
if mostTopicNum > 10 {
leastTopicNum := mostTopicNum
for index, s := range nodeTopicStatsSortedSlave {
if len(s.TopicTotalDataSize) < leastTopicNum {
leastTopicNum = len(s.TopicTotalDataSize)
topicStatsMinMax[0] = &nodeTopicStatsSortedSlave[index]
_, minNodeLoad = s.GetNodeLoadFactor()
}
}
if float64(mostTopicNum) > float64(leastTopicNum)*1.3 && minNodeLoad < midNodeLoad {
topicStatsMinMax[1] = &nodeTopicStatsSortedSlave[len(nodeTopicStatsSortedSlave)-1]
coordLog.Infof("node %v has too much topics: %v, the least has only %v", topicStatsMinMax[1].NodeID, mostTopicNum, leastTopicNum)
moveLeader = len(topicStatsMinMax[1].TopicLeaderDataSize) > len(topicStatsMinMax[1].TopicTotalDataSize)*2/3
dpm.balanceTopicLeaderBetweenNodes(monitorChan, moveLeader, moveMinLFOnly, minNodeLoad,
maxNodeLoad, topicStatsMinMax, nodeTopicStatsSortedSlave)
}
}
}
}
}
}
func checkMoveLotsOfTopics(moveLeader bool, moveTopicNum int, moveNodeStats *NodeTopicStats, avgTopicNum int,
topicStatsMinMax []*NodeTopicStats, midLeaderLoad float64) bool {
if moveNodeStats.NodeID == topicStatsMinMax[0].NodeID ||
len(topicStatsMinMax[0].TopicLeaderDataSize) > avgTopicNum {
return false
}
coordLog.Infof("too many topic on node: %v, num: %v", moveNodeStats.NodeID, moveTopicNum)
leaderLF, _ := moveNodeStats.GetNodeLoadFactor()
//we should avoid move leader topic if the load is not so much
if leaderLF < midLeaderLoad && float64(moveTopicNum) < float64(avgTopicNum)*1.5 {
coordLog.Infof("although many topics , the load is not much: %v", leaderLF)
return false
}
return true
}
func (dpm *DataPlacement) balanceTopicLeaderBetweenNodes(monitorChan chan struct{}, moveLeader bool, moveOp balanceOpLevel,
minLF float64, maxLF float64, statsMinMax []*NodeTopicStats, sortedNodeTopicStats []NodeTopicStats) {
if !atomic.CompareAndSwapInt32(&dpm.lookupCoord.balanceWaiting, 0, 1) {
coordLog.Infof("another balance is running, should wait")
return
}
defer atomic.StoreInt32(&dpm.lookupCoord.balanceWaiting, 0)
idleTopic, busyTopic, _, busyLevel := statsMinMax[1].GetMostBusyAndIdleTopicWriteLevel(moveLeader)
if busyTopic == "" && idleTopic == "" {
coordLog.Infof("no idle or busy topic found")
return
}
// never balance the ordered multi partitions, these partitions should be the same on the all nodes
moveFromNode := statsMinMax[1].NodeID
coordLog.Infof("balance topic: %v, %v(%v) from node: %v, move : %v ", idleTopic,
busyTopic, busyLevel, moveFromNode, moveOp)
coordLog.Infof("balance topic current max: %v, min: %v ", maxLF, minLF)
checkMoveOK := false
topicName := ""
partitionID := 0
var err error
// avoid move the too busy topic to reduce the impaction of the online service.
// if the busiest topic is not so busy, we try move this topic to avoid move too much idle topics
if busyTopic != "" && busyLevel < busyTopicLevel && (busyLevel*2 < maxLF-minLF) {
topicName, partitionID, err = splitTopicPartitionID(busyTopic)
if err != nil {
coordLog.Warningf("split topic name and partition %v failed: %v", busyTopic, err)
} else {
checkMoveOK = dpm.checkAndPrepareMove(monitorChan, moveFromNode, topicName, partitionID,
statsMinMax,
sortedNodeTopicStats, moveOp, moveLeader)
if checkMoveOK {
return
}
}
}
if idleTopic != "" {
topicName, partitionID, err = splitTopicPartitionID(idleTopic)
if err != nil {
coordLog.Warningf("split topic name and partition %v failed: %v", idleTopic, err)
} else {
checkMoveOK = dpm.checkAndPrepareMove(monitorChan, moveFromNode, topicName, partitionID,
statsMinMax,
sortedNodeTopicStats, moveOp, moveLeader)
if checkMoveOK {
return
}
}
}
// maybe we can move some other topic if both idle/busy is not movable
sortedTopics := statsMinMax[1].GetSortedTopicWriteLevel(moveLeader)
coordLog.Infof("check %v for moving , all sorted topic number: %v, %v, %v", moveFromNode, len(sortedTopics),
len(statsMinMax[1].TopicHourlyPubDataList), len(statsMinMax[1].TopicLeaderDataSize))
for _, t := range sortedTopics {
if t.topic == idleTopic || t.topic == busyTopic {
continue
}
if checkMoveOK {
break
}
// do not move the topic with very busy load
if t.loadFactor > busyTopicLevel || t.loadFactor > maxLF-minLF {
coordLog.Infof("check topic for moving , all busy : %v, %v", t, sortedTopics)
break
}
topicName, partitionID, err = splitTopicPartitionID(t.topic)
if err != nil {
coordLog.Warningf("split topic %v failed: %v", t.topic, err)
} else {
coordLog.Infof("check topic %v for moving ", t)
checkMoveOK = dpm.checkAndPrepareMove(monitorChan, moveFromNode, topicName, partitionID,
statsMinMax,
sortedNodeTopicStats, moveOp, moveLeader)
}
}
}
func (dpm *DataPlacement) checkAndPrepareMove(monitorChan chan struct{}, fromNode string, topicName string, partitionID int,
statsMinMax []*NodeTopicStats,
sortedNodeTopicStats []NodeTopicStats, moveOp balanceOpLevel, moveLeader bool) bool {
topicInfo, err := dpm.lookupCoord.leadership.GetTopicInfo(topicName, partitionID)
if err != nil {
coordLog.Infof("failed to get topic %v info: %v", topicName, err)
return false
}
checkMoveOK := false
if topicInfo.AllowMulti() {
coordLog.Debugf("topic %v is configured as multi ordered, no balance", topicName)
return false
}
if moveOp > moveAny {
leaderNodeLF, _ := statsMinMax[0].GetNodeLoadFactor()
coordLog.Infof("check the min load node first: %v, %v", statsMinMax[0].NodeID, leaderNodeLF)
// check first for the specific min load node
if moveLeader {
if FindSlice(topicInfo.ISR, statsMinMax[0].NodeID) != -1 {
checkMoveOK = true
}
}
if !checkMoveOK {
if leaderNodeLF < sortedNodeTopicStats[len(sortedNodeTopicStats)/2].GetNodeLeaderLoadFactor() {
nlist := make([]string, 0)
nlist = append(nlist, statsMinMax[0].NodeID)
err := dpm.addToCatchupAndWaitISRReady(monitorChan, false, fromNode, topicName, partitionID,
nlist,
getNodeNameList(sortedNodeTopicStats), false)
if err == nil {
return true
}
}
}
}
if moveOp == moveMinLFOnly {
// no try other node
} else if moveOp > moveAny || (len(topicInfo.ISR)-1 <= topicInfo.Replica/2) {
if moveLeader {
// check if any of current isr nodes is already idle for move
for _, nid := range topicInfo.ISR {
if checkMoveOK {
break
}
if nid == fromNode {
continue
}
for index, stat := range sortedNodeTopicStats {
if index >= len(sortedNodeTopicStats)/3 {
break
}
if stat.NodeID == nid {
checkMoveOK = true
break
}
}
}
}
if !checkMoveOK {
// the isr not so idle , we try add a new idle node to the isr.
// and make sure that node can accept the topic (no other leader/follower for this topic)
err := dpm.addToCatchupAndWaitISRReady(monitorChan, false, fromNode, topicName, partitionID, nil,