/
rebalance.go
1820 lines (1516 loc) · 53.2 KB
/
rebalance.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
// Copyright 2015-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package rebalance
import (
"errors"
"fmt"
"net/http"
"reflect"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/couchbase/blance"
"github.com/couchbase/cbgt"
"github.com/couchbase/cbgt/rest/monitor"
log "github.com/couchbase/clog"
)
var ErrorNotPausable = errors.New("not pausable")
var ErrorNotResumable = errors.New("not resumable")
var ErrorNoIndexDefinitionFound = errors.New("no index definition found")
var ErrorConcurrentPlannerInProgress = errors.New("concurrent planner in progress")
// StatsSampleErrorThreshold defines the default upper limit for
// the ephemeral stats monitoring errors tolerated / ignored
// during a heavy rebalance scenario.
var StatsSampleErrorThreshold = uint8(3)
// ProgressSamplingRate defines the default sampling rate at
// which the rebalance progressCh is bumped upon receiving the
// partition stats from the node monitor threads.
// Lack of sampling results in very frequent rebalance progress state
// updates which is cumbersome with large number of indexes.
var ProgressSamplingRate = uint(3)
// RebalanceProgress represents progress status information as the
// Rebalance() operation proceeds.
type RebalanceProgress struct {
Error error
Index string
OrchestratorProgress blance.OrchestratorProgress
// Map of pindex -> transfer progress in range of 0 to 1.
TransferProgress map[string]float64
}
type RebalanceOptions struct {
// See blance.CalcPartitionMoves(favorMinNodes).
FavorMinNodes bool
MaxConcurrentPartitionMovesPerNode int
// AddPrimaryDirectly, when true, means the rebalancer should
// assign a pindex as primary to a node directly, and not use a
// replica-promotion maneuver (e.g., assign replica first, wait
// until replica is caught up, then promote replica to primary).
AddPrimaryDirectly bool
DryRun bool // When true, no changes, for analysis/planning.
Log RebalanceLogFunc
Verbose int
// Optional, defaults to http.Get(); this is used, for example,
// for unit testing.
HttpGet func(url string) (resp *http.Response, err error)
SkipSeqChecks bool // For unit-testing.
// SeqChecksTimeoutInSec is an optional configurable timeout value,
// which when set would timeout to unblock any of the partition catch
// related wait loops. It is applicable to both the sequence number
// initialization and catch up wait loops for the formerPrimary as well
// as the new partition node.
SeqChecksTimeoutInSec int
// a flag to decide whether we allow the replica to catchup till a certain
// sequence number or not
EnableReplicaCatchup bool
Manager *cbgt.Manager
StatsSampleErrorThreshold *int
ExistingNodes []string
}
type RebalanceLogFunc func(format string, v ...interface{})
// A Rebalancer struct holds all the tracking information for the
// Rebalance operation.
type Rebalancer struct {
version string // See cbgt.Manager's version.
cfg cbgt.Cfg // See cbgt.Manager's cfg.
server string // See cbgt.Manager's server.
optionsMgr map[string]string // See cbgt.Manager's options.
optionsReb RebalanceOptions
progressCh chan RebalanceProgress
monitor *monitor.MonitorNodes
monitorDoneCh chan struct{}
monitorSampleCh chan monitor.MonitorSample
monitorSampleWantCh chan chan monitor.MonitorSample
nodesAll []string // Array of node UUID's.
nodesToAdd []string // Array of node UUID's.
nodesToRemove []string // Array of node UUID's.
nodeWeights map[string]int // Keyed by node UUID.
nodeHierarchy map[string]string // Keyed by node UUID.
begIndexDefs *cbgt.IndexDefs
begNodeDefs *cbgt.NodeDefs
begPlanPIndexes *cbgt.PlanPIndexes
begPlanPIndexesCAS uint64
// The updated plans computed during the rebalance iterations.
existingPlanPIndexes *cbgt.PlanPIndexes
recoveryPlanPIndexes *cbgt.PlanPIndexes
m sync.Mutex // Protects the mutable fields that follow.
endPlanPIndexes *cbgt.PlanPIndexes
// We start a new blance.Orchestrator for each index.
o *blance.Orchestrator
// Map of index -> pindex -> node -> StateOp.
currStates CurrStates
// Map of pindex -> (source) partition -> node -> cbgt.UUIDSeq.
currSeqs CurrSeqs
// Map of pindex -> (source) partition -> node -> cbgt.UUIDSeq.
wantSeqs WantSeqs
stopCh chan struct{} // Closed by app or when there's an error.
transferProgress map[string]float64 // pindex -> file transfer progress
}
// Map of index -> pindex -> node -> StateOp.
type CurrStates map[string]map[string]map[string]StateOp
// A StateOp is used to track state transitions and associates a state
// (i.e., "primary") with an op (e.g., "add", "del").
type StateOp struct {
State string
Op string // May be "" for unknown or no in-flight op.
}
// Map of pindex -> (source) partition -> node -> cbgt.UUIDSeq.
type CurrSeqs map[string]map[string]map[string]cbgt.UUIDSeq
// Map of pindex -> (source) partition -> node -> cbgt.UUIDSeq.
type WantSeqs map[string]map[string]map[string]cbgt.UUIDSeq
// --------------------------------------------------------
// checkpoints the rebalance status in the cfg
func CheckPointRebalanceStatus(cfg cbgt.Cfg, status cbgt.LastRebalanceStatus) error {
_, cas, err := cbgt.CfgGetLastRebalanceStatus(cfg)
if err != nil {
log.Errorf("rebalance_checkpoint: GetLastRebalanceStatus, err: %v",
err)
return err
}
_, err = cbgt.CfgSetLastRebalanceStatus(cfg, status, cas)
if err != nil {
log.Errorf("rebalance_checkpoint: SetLastRebalanceStatus:%v, "+
"err:%v", status, err)
return err
}
return nil
}
// StartRebalance begins a concurrent, cluster-wide rebalancing of all
// the indexes (and their index partitions) on a cluster of cbgt
// nodes. StartRebalance utilizes the blance library for calculating
// and orchestrating partition reassignments and the cbgt/rest/monitor
// library to watch for progress and errors.
func StartRebalance(version string, cfg cbgt.Cfg, server string,
optionsMgr map[string]string,
nodesToRemoveParam []string,
optionsReb RebalanceOptions) (
*Rebalancer, error) {
CheckPointRebalanceStatus(cfg, cbgt.RebStarted)
// TODO: Need timeouts on moves.
//
uuid := "" // We don't have a uuid, as we're not a node.
begIndexDefs, begNodeDefs, begPlanPIndexes, begPlanPIndexesCAS, err :=
cbgt.PlannerGetPlan(cfg, version, uuid)
if err != nil {
return nil, err
}
existingPlans := cbgt.NewPlanPIndexes(version)
nodeUUIDs, nodeWeights, nodeHierarchy :=
cbgt.GetNodeWeightsAndHierarchy(begNodeDefs)
nodesAll, nodesToAdd, nodesToRemove :=
cbgt.CalcNodesToAddRemove(nodeUUIDs, optionsReb.ExistingNodes)
nodesUnknown := cbgt.StringsRemoveStrings(nodesToRemoveParam, nodesAll)
if len(nodesUnknown) > 0 {
return nil, fmt.Errorf("rebalance:"+
" unknown nodes in nodesToRemoveParam: %#v",
nodesUnknown)
}
nodesToRemove = append(nodesToRemove, nodesToRemoveParam...)
nodesToRemove = cbgt.StringsIntersectStrings(nodesToRemove, nodesToRemove)
nodesToAdd = cbgt.StringsRemoveStrings(nodesToAdd, nodesToRemove)
if RebalanceHook != nil {
_, err := RebalanceHook(RebalanceHookInfo{
Phase: RebalanceHookPhaseInit,
})
if err != nil {
return nil, fmt.Errorf("rebalance: rebalanceHook init phase,"+
" err: %v", err)
}
}
// --------------------------------------------------------
urlUUIDs := monitor.NodeDefsUrlUUIDs(begNodeDefs)
monitorSampleCh := make(chan monitor.MonitorSample)
monitorOptions := monitor.MonitorNodesOptions{
DiagSampleDisable: true,
HttpGet: optionsReb.HttpGet,
}
monitorInst, err := monitor.StartMonitorNodes(urlUUIDs,
monitorSampleCh, monitorOptions)
if err != nil {
return nil, err
}
// --------------------------------------------------------
stopCh := make(chan struct{})
r := &Rebalancer{
version: version,
cfg: cfg,
server: server,
optionsMgr: optionsMgr,
optionsReb: optionsReb,
progressCh: make(chan RebalanceProgress),
monitor: monitorInst,
monitorDoneCh: make(chan struct{}),
monitorSampleCh: monitorSampleCh,
monitorSampleWantCh: make(chan chan monitor.MonitorSample),
nodesAll: nodesAll,
nodesToAdd: nodesToAdd,
nodesToRemove: nodesToRemove,
nodeWeights: nodeWeights,
nodeHierarchy: nodeHierarchy,
begIndexDefs: begIndexDefs,
begNodeDefs: begNodeDefs,
begPlanPIndexes: begPlanPIndexes,
begPlanPIndexesCAS: begPlanPIndexesCAS,
existingPlanPIndexes: existingPlans,
endPlanPIndexes: cbgt.NewPlanPIndexes(version),
currStates: map[string]map[string]map[string]StateOp{},
currSeqs: map[string]map[string]map[string]cbgt.UUIDSeq{},
wantSeqs: map[string]map[string]map[string]cbgt.UUIDSeq{},
stopCh: stopCh,
transferProgress: map[string]float64{},
}
r.Logf("rebalance: nodesAll: %#v", nodesAll)
r.Logf("rebalance: nodesToAdd: %#v", nodesToAdd)
r.Logf("rebalance: nodesToRemove: %#v", nodesToRemove)
r.Logf("rebalance: nodeWeights: %#v", nodeWeights)
r.Logf("rebalance: nodeHierarchy: %#v", nodeHierarchy)
// r.Logf("rebalance: begIndexDefs: %#v", begIndexDefs)
// r.Logf("rebalance: begNodeDefs: %#v", begNodeDefs)
r.Logf("rebalance: monitor urlUUIDs: %#v", urlUUIDs)
r.initPlansForRecoveryRebalance(nodesToAdd)
// begPlanPIndexesJSON, _ := cbgt.MarshalJSON(begPlanPIndexes)
//
// r.Logf("rebalance: begPlanPIndexes: %s, cas: %v",
// begPlanPIndexesJSON, begPlanPIndexesCAS)
// TODO: Prepopulate currStates so that we can double-check that
// our state transitions in assignPartition are valid.
go r.runMonitor(stopCh)
go r.runRebalanceIndexes(stopCh)
return r, nil
}
// Calculate and Returns
//
// (*) Difference between the number of partitions required as per
// the index definitions and the actual number of partitions, for both primary
// and replica partitions, across all the indexes.
//
// (*) NumReplicas of the index with the maximum number of required replicas.
func compareIndexDefsWithPlan(indexDefs *cbgt.IndexDefs,
planPIndexes *cbgt.PlanPIndexes) (int, int, int) {
if indexDefs == nil || len(indexDefs.IndexDefs) == 0 {
return 0, 0, 0
}
// count of active and replica partitions required as per the index
// definitions
totActivesReq, totReplicasReq := 0, 0
// count of active and replica partitions available as per the planPIndexes
totActivesAvail, totReplicasAvail := 0, 0
// replica count of the index with the maximum number of required replicas
maxReplicaCount := 0
for _, indexDef := range indexDefs.IndexDefs {
activesReq := indexDef.PlanParams.IndexPartitions
replicasReq := indexDef.PlanParams.IndexPartitions *
indexDef.PlanParams.NumReplicas
totActivesReq += activesReq
totReplicasReq += replicasReq
if maxReplicaCount < indexDef.PlanParams.NumReplicas {
maxReplicaCount = indexDef.PlanParams.NumReplicas
}
}
if planPIndexes == nil || len(planPIndexes.PlanPIndexes) == 0 {
// return the total partitions count as per the index definitions
// as there are no planPIndexes yet.
return totActivesReq, totReplicasReq, maxReplicaCount
}
for _, planPIndex := range planPIndexes.PlanPIndexes {
for _, nodes := range planPIndex.Nodes {
if nodes.Priority == 0 {
totActivesAvail++
} else {
totReplicasAvail++
}
}
}
return totActivesReq - totActivesAvail, totReplicasReq - totReplicasAvail,
maxReplicaCount
}
// Stop asynchronously requests a stop to the rebalance operation.
// Callers can look for the closing of the ProgressCh() to see when
// the rebalance operation has actually stopped.
func (r *Rebalancer) Stop() {
r.m.Lock()
if r.stopCh != nil {
close(r.stopCh)
r.stopCh = nil
}
if r.o != nil {
r.o.Stop()
r.o = nil
}
r.m.Unlock()
}
// ProgressCh() returns a channel that is updated occasionally when
// the rebalance has made some progress on one or more partition
// reassignments, or has reached an error. The channel is closed when
// the rebalance operation is finished, either naturally, or due to an
// error, or via a Stop(), and all the rebalance-related resources
// have been released.
func (r *Rebalancer) ProgressCh() chan RebalanceProgress {
return r.progressCh
}
// PauseNewAssignments pauses any new assignments. Any inflight
// assignments, however, will continue to completion or error.
func (r *Rebalancer) PauseNewAssignments() (err error) {
err = ErrorNotPausable
r.m.Lock()
if r.o != nil {
err = r.o.PauseNewAssignments()
}
r.m.Unlock()
return err
}
// ResumeNewAssignments resumes new assignments.
func (r *Rebalancer) ResumeNewAssignments() (err error) {
err = ErrorNotResumable
r.m.Lock()
if r.o != nil {
err = r.o.ResumeNewAssignments()
}
r.m.Unlock()
return err
}
type VisitFunc func(CurrStates, CurrSeqs, WantSeqs, map[string]float64,
map[string]*blance.NextMoves)
// Visit invokes the visitor callback with the current,
// read-only CurrStates, CurrSeqs and WantSeqs.
func (r *Rebalancer) Visit(visitor VisitFunc) {
r.m.Lock()
if r.o != nil {
r.o.VisitNextMoves(func(m map[string]*blance.NextMoves) {
visitor(r.currStates, r.currSeqs, r.wantSeqs, r.transferProgress, m)
})
} else {
visitor(r.currStates, r.currSeqs, r.wantSeqs, r.transferProgress, nil)
}
r.m.Unlock()
}
// --------------------------------------------------------
func (r *Rebalancer) Logf(fmt string, v ...interface{}) {
if r.optionsReb.Verbose < 0 {
return
}
if r.optionsReb.Verbose < len(fmt) &&
fmt[r.optionsReb.Verbose] == ' ' {
return
}
f := r.optionsReb.Log
if f == nil {
f = log.Printf
}
f(fmt, v...)
}
// --------------------------------------------------------
// GetEndPlanPIndexes return value should be treated as immutable.
func (r *Rebalancer) GetEndPlanPIndexes() *cbgt.PlanPIndexes {
r.m.Lock()
ppi := *r.endPlanPIndexes
r.m.Unlock()
return &ppi
}
// --------------------------------------------------------
// rebalanceIndexes rebalances each index, one at a time.
func (r *Rebalancer) runRebalanceIndexes(stopCh chan struct{}) {
defer func() {
// Completion of rebalance operation, whether naturally or due
// to error/Stop(), needs this cleanup. Wait for runMonitor()
// to finish as it may have more sends to progressCh.
//
r.Stop()
r.monitor.Stop()
<-r.monitorDoneCh
close(r.progressCh)
// TODO: Need to close monitorSampleWantCh?
}()
i := 1
n := len(r.begIndexDefs.IndexDefs)
var indexDefNames []string
for _, indexDef := range r.begIndexDefs.IndexDefs {
indexDefNames = append(indexDefNames, indexDef.Name)
}
slices.Sort(indexDefNames)
for _, indexName := range indexDefNames {
select {
case <-stopCh:
return
default:
// NO-OP.
}
r.Logf("=====================================")
r.Logf("runRebalanceIndexes: %d of %d", i, n)
indexDef := r.begIndexDefs.IndexDefs[indexName]
_, err := r.rebalanceIndex(stopCh, indexDef)
if err != nil {
r.Logf("run: indexDef.Name: %s, err: %#v",
indexDef.Name, err)
return
}
i++
}
}
// --------------------------------------------------------
// GetMovingPartitionsCount returns the total partitions
// to be moved as a part of the rebalance operation.
func (r *Rebalancer) GetMovingPartitionsCount() int {
count := 0
r.m.Lock()
if r.o != nil {
r.o.VisitNextMoves(func(m map[string]*blance.NextMoves) {
if m != nil {
for _, nextMoves := range m {
if len(nextMoves.Moves) > 0 {
count++
}
}
}
})
}
r.m.Unlock()
if r.begIndexDefs != nil && r.begIndexDefs.IndexDefs != nil {
// upfront approximation to get the total partitions
// based on the assumption that index partitions are evenly
// distributed which may not quite true, due to chronology of
// index creations and the corresponding topology changes
return len(r.begIndexDefs.IndexDefs) * count
}
return 0
}
// --------------------------------------------------------
// rebalanceIndex rebalances a single index.
func (r *Rebalancer) rebalanceIndex(stopCh chan struct{},
indexDef *cbgt.IndexDef) (
changed bool, err error) {
r.Logf(" rebalanceIndex: indexDef.Name: %s", indexDef.Name)
r.m.Lock()
if cbgt.CasePlanFrozen(indexDef, r.begPlanPIndexes, r.endPlanPIndexes) {
r.m.Unlock()
r.Logf(" plan frozen: indexDef.Name: %s,"+
" cloned previous plan", indexDef.Name)
return false, nil
}
r.m.Unlock()
// Skip indexDef's with no instantiatable pindexImplType, such
// as index aliases.
pindexImplType, exists := cbgt.PIndexImplTypes[indexDef.Type]
if !exists ||
pindexImplType == nil ||
pindexImplType.New == nil ||
pindexImplType.Open == nil {
return false, nil
}
partitionModel, begMap, endMap, err := r.calcBegEndMaps(indexDef)
if err != nil {
return false, err
}
if reflect.DeepEqual(begMap, endMap) {
r.Logf("rebalanceIndex: skipping indexDef.Name: %s"+
" as the begin and end plans are same", indexDef.Name)
return true, nil
}
assignPartitionsFunc := func(stopCh2 chan struct{}, node string,
partitions, states, ops []string) error {
r.Logf("rebalance: assignPIndexes, index: %s, node: %s, partitions: %v,"+
" states: %v, ops: %v, starts", indexDef.Name, node, partitions,
states, ops)
err2 := r.assignPIndexes(stopCh, stopCh2,
indexDef.Name, node, partitions, states, ops)
r.Logf("rebalance: assignPIndexes, index: %s, node: %s, partitions: %v,"+
" states: %v, ops: %v, finished", indexDef.Name, node, partitions,
states, ops)
if err2 != nil {
r.Logf("rebalance: assignPartitionsFunc, err: %v", err2)
// Stop rebalance for all other errors.
if !errors.Is(err2, ErrorNoIndexDefinitionFound) {
r.progressCh <- RebalanceProgress{Error: err2}
r.Stop()
return err2
}
}
return nil
}
o, err := blance.OrchestrateMoves(
partitionModel,
blance.OrchestratorOptions{
MaxConcurrentPartitionMovesPerNode: r.optionsReb.MaxConcurrentPartitionMovesPerNode,
FavorMinNodes: r.optionsReb.FavorMinNodes,
},
r.nodesAll,
begMap,
endMap,
assignPartitionsFunc,
blance.LowestWeightPartitionMoveForNode) // TODO: concurrency.
if err != nil {
return false, err
}
r.m.Lock()
r.o = o
r.m.Unlock()
numProgress := 0
var lastProgress blance.OrchestratorProgress
var firstErr error
for progress := range o.ProgressCh() {
if len(progress.Errors) > 0 &&
firstErr == nil {
firstErr = progress.Errors[0]
}
progressChanges := cbgt.StructChanges(lastProgress, progress)
r.Logf(" index: %s, #%d %+v",
indexDef.Name, numProgress, progressChanges)
r.Logf(" progress: %+v", progress)
r.progressCh <- RebalanceProgress{
Error: firstErr,
Index: indexDef.Name,
OrchestratorProgress: progress,
}
numProgress++
lastProgress = progress
}
o.Stop()
// TDOO: Check that the plan in the cfg should match our endMap...
//
// _, err = cbgt.CfgSetPlanPIndexes(cfg, planPIndexesFFwd, cas)
// if err != nil {
// return false, fmt.Errorf("rebalance: could not save new plan,"+
// " perhaps a concurrent planner won, cas: %d, err: %v",
// cas, err)
// }
// TODO: Propagate all errors better.
// TODO: Compute proper change response.
return true, firstErr
}
// initPlansForRecoveryRebalance attempts to figure out whether the
// current rebalance operation is a recovery one or not and sets the
// recoveryPlanPIndexes accordingly.
func (r *Rebalancer) initPlansForRecoveryRebalance(nodesToAdd []string) {
if len(nodesToAdd) == 0 || r.optionsReb.Manager == nil {
return
}
// check whether the previous cluster contained the nodesToAdd to
// figure out whether it is a recovery operation.
begPlanPIndexesCopy := r.optionsReb.Manager.GetStableLocalPlanPIndexes()
if begPlanPIndexesCopy != nil {
var prevNodes []string
for _, pp := range begPlanPIndexesCopy.PlanPIndexes {
for uuid := range pp.Nodes {
prevNodes = append(prevNodes, uuid)
}
}
// check whether all the nodes to get added were a part of the cluster.
cNodes := cbgt.StringsIntersectStrings(prevNodes, nodesToAdd)
sort.Strings(cNodes)
if len(cNodes) != len(nodesToAdd) {
return
}
for i := range nodesToAdd {
if cNodes[i] != nodesToAdd[i] {
return
}
}
r.recoveryPlanPIndexes = begPlanPIndexesCopy
}
}
// --------------------------------------------------------
// calcBegEndMaps calculates the before and after maps for an index.
func (r *Rebalancer) calcBegEndMaps(indexDef *cbgt.IndexDef) (
partitionModel blance.PartitionModel,
begMap blance.PartitionMap,
endMap blance.PartitionMap,
err error) {
r.m.Lock()
defer r.m.Unlock()
// The endPlanPIndexesForIndex is a working data structure that's
// mutated as calcBegEndMaps progresses.
endPlanPIndexesForIndex, err := cbgt.SplitIndexDefIntoPlanPIndexes(
indexDef, r.server, r.optionsMgr, r.endPlanPIndexes)
if err != nil {
r.Logf(" calcBegEndMaps: indexDef.Name: %s,"+
" could not SplitIndexDefIntoPlanPIndexes,"+
" server: %s, err: %v", indexDef.Name, r.server, err)
return partitionModel, begMap, endMap, err
}
var warnings map[string][]string
if r.recoveryPlanPIndexes != nil {
// During the failover, cbgt ignores the new nextMap from blance
// and just promotes the replica partitions to primary.
// Hence during the failover-recovery rebalance operation,
// feed the pre failover plan to the blance so that it would
// be able to come up with the same exact plan for the
// same set of nodes and the original planPIndexes.
r.Logf(" calcBegEndMaps: recovery rebalance for index: %s", indexDef.Name)
warnings = cbgt.BlancePlanPIndexes("", indexDef,
endPlanPIndexesForIndex, r.recoveryPlanPIndexes,
r.nodesAll, []string{}, r.nodesToRemove,
r.nodeWeights, r.nodeHierarchy, false)
} else {
var enablePartitionNodeStickiness bool
if r.optionsReb.Manager != nil {
options := r.optionsReb.Manager.GetOptions()
if enabled, found := options["enablePartitionNodeStickiness"]; found &&
enabled == "true" {
enablePartitionNodeStickiness = true
}
}
nodeWeights := r.adjustNodeWeights(indexDef, endPlanPIndexesForIndex,
enablePartitionNodeStickiness)
// Updating this here since plans for index have been assigned to nodes.
// PlanPIndexes for Index should include existing partitions placements
// Using the beginning plans since they haven't changed for this index yet.
for planName, plan := range r.begPlanPIndexes.PlanPIndexes {
if plan.IndexUUID == indexDef.UUID {
r.existingPlanPIndexes.PlanPIndexes[planName] = plan
}
}
// Invoke blance to assign the endPlanPIndexesForIndex to nodes;
// Do not account for existing planPIndexes, if
// enablePartitionNodeStickiness is enabled, giving full control
// to the rebalanceHook to influence node weights.
warnings = cbgt.BlancePlanPIndexes("", indexDef,
endPlanPIndexesForIndex, r.existingPlanPIndexes,
r.nodesAll, r.nodesToAdd, r.nodesToRemove,
nodeWeights, r.nodeHierarchy, enablePartitionNodeStickiness)
// Updating this here since plans for index have been assigned to nodes.
// Will use this to pass context to blance.
for k, v := range endPlanPIndexesForIndex {
r.existingPlanPIndexes.PlanPIndexes[k] = v
}
}
for partitionName, partitionWarning := range warnings {
if _, exists := r.endPlanPIndexes.PlanPIndexes[partitionName]; exists {
if r.endPlanPIndexes.PlanPIndexes[partitionName].IndexName == indexDef.Name {
r.endPlanPIndexes.Warnings[indexDef.Name] =
append(r.endPlanPIndexes.Warnings[indexDef.Name], partitionWarning...)
}
}
}
for _, warning := range r.endPlanPIndexes.Warnings[indexDef.Name] {
r.Logf(" calcBegEndMaps: indexDef.Name: %s,"+
" BlancePlanPIndexes warning: %q",
indexDef.Name, warning)
}
j, _ := cbgt.MarshalJSON(r.endPlanPIndexes)
r.Logf(" calcBegEndMaps: indexDef.Name: %s,"+
" endPlanPIndexes: %s", indexDef.Name, j)
partitionModel, _ = cbgt.BlancePartitionModel(indexDef)
begMap = cbgt.BlanceMap(endPlanPIndexesForIndex, r.begPlanPIndexes, true)
endMap = cbgt.BlanceMap(endPlanPIndexesForIndex, r.endPlanPIndexes, true)
return partitionModel, begMap, endMap, nil
}
// --------------------------------------------------------
// RebalanceHook allows advanced applications to register a callback
// into the planning computation, in order to adjust the rebalancing plan
// outcome. For example, an advanced appplication migh adjust node weights
// more dynamically in order to achieve a custom layout of pindexes across
// the cluster. This should be set only during the init()'ialization phase
// of the process.
var RebalanceHook func(in RebalanceHookInfo) (out RebalanceHookInfo, err error)
// Rebalance hook phases.
const (
// Invoked before instantiating the rebalancer, to allow the application to
// decide to skip the rebalance operation
RebalanceHookPhaseInit = 1 << iota
RebalanceHookPhaseAdjustNodeWeights
)
// RebalanceHookInfo is the in/out information provided to the
// RebalanceHook. If the RebalanceHook wishes to modify any of these
// fields to affect the planning outcome, it must copy the field value
// (e.g, copy-on-write).
type RebalanceHookInfo struct {
Phase int
IndexDefs *cbgt.IndexDefs
IndexDef *cbgt.IndexDef
BegNodeDefs *cbgt.NodeDefs
NodeUUIDsAll []string
NodeUUIDsToAdd []string
NodeUUIDsToRemove []string
NodeWeights map[string]int
NodeHierarchy map[string]string
BegPlanPIndexes *cbgt.PlanPIndexes
EndPlanPIndexes *cbgt.PlanPIndexes
ExistingPlanPIndexes *cbgt.PlanPIndexes
PlanPIndexesForIndex map[string]*cbgt.PlanPIndex
}
// adjustNodeWeights overrides the node weights reflective of the
// existing partition count on those nodes. It helps in balanced
// partition assignments across nodes for the single partitioned indexes.
func (r *Rebalancer) adjustNodeWeights(
indexDef *cbgt.IndexDef,
planPIndexesForIndex map[string]*cbgt.PlanPIndex,
enablePartitionNodeStickiness bool) map[string]int {
nodeWeights := r.nodeWeights
if RebalanceHook != nil {
rho, err := RebalanceHook(RebalanceHookInfo{
Phase: RebalanceHookPhaseAdjustNodeWeights,
IndexDefs: r.begIndexDefs,
IndexDef: indexDef,
BegNodeDefs: r.begNodeDefs,
NodeUUIDsAll: r.nodesAll,
NodeUUIDsToAdd: r.nodesToAdd,
NodeUUIDsToRemove: r.nodesToRemove,
NodeWeights: r.nodeWeights,
NodeHierarchy: r.nodeHierarchy,
ExistingPlanPIndexes: r.existingPlanPIndexes,
BegPlanPIndexes: r.begPlanPIndexes,
EndPlanPIndexes: r.endPlanPIndexes,
PlanPIndexesForIndex: planPIndexesForIndex,
})
if err == nil {
nodeWeights = rho.NodeWeights
}
}
return nodeWeights
}
// --------------------------------------------------------
// pindexMoves is a wrapper for a pindex movement containing
// the detailed/multi-step stateOps transitions.
type pindexMoves struct {
name string
stateOps []StateOp
}
// --------------------------------------------------------
// assignPIndex is invoked when blance.OrchestrateMoves() wants to
// synchronously change one or more pindex/node/state/op for an index.
func (r *Rebalancer) assignPIndexes(stopCh, stopCh2 chan struct{},
index string, node string, pindexes, states, ops []string) error {
pindexesMoves := r.createPindexesMoves(pindexes, states, ops)
r.Logf(" assignPIndex: index: %s,"+
" pindexes: %v, node: %s, target states: %v, target ops: %v",
index, pindexes, node, states, ops)
// Move multiple partitions one step at a time. There could be a
// few potential multi-step partition movements.
var next int
for len(pindexesMoves) > 0 {
r.m.Lock() // Reduce but not eliminate CAS conflicts.
indexDef, planPIndexes, formerPrimaryNodes, err := r.assignPIndexesLOCKED(
index, node, pindexesMoves, next)
r.m.Unlock()
if err != nil {
if !errors.Is(err, ErrorNoIndexDefinitionFound) {
return fmt.Errorf("assignPIndex: update plan,"+
" perhaps a concurrent planner won, err: %w", err)
}
r.Logf("assignPIndex: update plan,"+
" perhaps a concurrent planner won, no indexDef,"+
" index: %s, pindexes: %v, node: %s, states: %v, ops: %v",
index, pindexes, node, states, ops)
return err
}
// start workers per pindex for tracking the partition assignment
// completion.
var wg sync.WaitGroup
doneCh := make(chan error, len(pindexesMoves))
for i := 0; i < len(pindexesMoves); i++ {
wg.Add(1)
go func(pm *pindexMoves, formerPrimaryNode string) {
err := r.waitAssignPIndexDone(stopCh, stopCh2,
indexDef, planPIndexes, pm.name, node,
pm.stateOps[next].State,
pm.stateOps[next].Op,
formerPrimaryNode,
len(pm.stateOps) > 1)
doneCh <- err
wg.Done()
}(pindexesMoves[i], formerPrimaryNodes[i])
}
wg.Wait()
close(doneCh)
var errs []string
indexMissingErrsOnly := true
for err := range doneCh {
if err != nil {
errs = append(errs, err.Error())
if indexMissingErrsOnly && !errors.Is(err, ErrorNoIndexDefinitionFound) {
indexMissingErrsOnly = false
}
}
}
if len(errs) > 0 {
// with index definition missing errors rebalance would continue further.
if indexMissingErrsOnly {
return fmt.Errorf("rebalance: waitAssignPIndexDone missing index: %s,"+
" errors: %w", index, ErrorNoIndexDefinitionFound)
}
return fmt.Errorf("rebalance: waitAssignPIndexDone errors: %d, %#v",
len(errs), errs)
}
// pindexesMoves might contain partition movements with single/two-step
// maneuvers for completion. So filter out any of the already completed
// single step pindex movements.
next++
pindexesMoves = removeShortMoves(pindexesMoves, next)
}
return nil
}
// --------------------------------------------------------
func (r *Rebalancer) createPindexesMoves(pindexes, states,
ops []string) []*pindexMoves {
pindexesMoves := make([]*pindexMoves, len(pindexes))
for i := 0; i < len(pindexes); i++ {
pm := &pindexMoves{name: pindexes[i]}
if !r.optionsReb.AddPrimaryDirectly &&
states[i] == "primary" && ops[i] == "add" {
// If we want to add a pindex to a node as a primary, then
// perform a 2-step maneuver by first adding the pindex as a
// replica, then promote that replica to master.