-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathdriver.go
More file actions
1683 lines (1498 loc) · 51.5 KB
/
driver.go
File metadata and controls
1683 lines (1498 loc) · 51.5 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 driver implements a priority queue that drives Raft range management
// decisions. It periodically examines ranges and partitions, determines what
// action (if any) is needed, and executes the appropriate change.
//
// For ranges, the driver handles:
// - Up-replication: adding replicas when a range has fewer than the configured minimum.
// - Down-replication: removing replicas when a range exceeds the minimum.
// - Dead replica replacement and removal.
// - Range splitting when a range exceeds the target size.
// - Replica rebalancing to distribute ranges evenly across stores.
// - Lease rebalancing to distribute lease ownership evenly across stores.
// - Finishing replica removal by cleaning up data on removed nodes.
//
// For partitions, the driver handles initialization of new partitions by
// creating the required Raft shards across available nodes.
//
// Actions are prioritized so that critical operations (e.g. replacing dead
// replicas) run before less urgent ones (e.g. rebalancing). Failed actions are
// retried with exponential backoff up to a maximum retry count.
package driver
import (
"cmp"
"container/heap"
"context"
"flag"
"maps"
"math"
"math/rand"
"slices"
"strconv"
"sync"
"time"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/raft/config"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/raft/constants"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/raft/header"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/raft/replica"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/raft/sender"
"github.com/buildbuddy-io/buildbuddy/enterprise/server/raft/storemap"
"github.com/buildbuddy-io/buildbuddy/server/interfaces"
"github.com/buildbuddy-io/buildbuddy/server/metrics"
"github.com/buildbuddy-io/buildbuddy/server/util/alert"
"github.com/buildbuddy-io/buildbuddy/server/util/disk"
"github.com/buildbuddy-io/buildbuddy/server/util/log"
"github.com/buildbuddy-io/buildbuddy/server/util/priority_queue"
"github.com/buildbuddy-io/buildbuddy/server/util/status"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sync/errgroup"
rfpb "github.com/buildbuddy-io/buildbuddy/proto/raft"
rfspb "github.com/buildbuddy-io/buildbuddy/proto/raft_service"
)
var (
minReplicasPerRange = flag.Int("cache.raft.min_replicas_per_range", 3, "The minimum number of replicas each range should have")
minMetaRangeReplicas = flag.Int("cache.raft.min_meta_range_replicas", 5, "The minimum number of replicas the meta range should have")
missingLeaseCountThreshold = flag.Int("cache.raft.missing_lease_count_threshold", 5, "When the number of ranges without leases is greater than this number, don't rebalance leases")
newReplicaGracePeriod = flag.Duration("cache.raft.new_replica_grace_period", 5*time.Minute, "The amount of time we allow for a new replica to catch up to the leader's before we start to consider it to be behind.")
)
const (
// If a node's disk is fuller than this (by percentage), it is not
// eligible to be used for a rebalance or allocation target and we will
// actively try to move replicas from this node.
maximumDiskCapacity = .95
// If a node's disk is fuller than this (by percentage), it is not
// eligible to be used as a rebalance target.
maxDiskCapacityForRebalance = .925
// The max number of retries per action. When a driver operation failed, we
// will put the replica back on the queue to retry during post-process. An
// alert will be fired once the max number of retries have reached, and we
// won't put the replica back on to the queue during post-process. However,
// the store periodically scan the replicas and add to the queue if a driver
// action is needed.
maxRetry = 10
)
type DriverAction int
const (
_ DriverAction = iota
DriverNoop
DriverSplitRange
DriverFinishReplicaRemoval
DriverRemoveReplica
DriverRemoveDeadReplica
DriverAddReplica
DriverReplaceDeadReplica
DriverRebalanceReplica
DriverRebalanceLease
// Partition-level actions
DriverInitializePartition
)
type RequeueType int
const (
_ RequeueType = iota
// Do not requeue.
RequeueNoop
// Current operation succeeded, but we want to requeue to see if we need to
// perform other driver actions.
RequeueCheckOtherActions
// Current operation failed, but we want to retry.
RequeueRetry
// We need to wait to perform the current operation.
RequeueWait
)
func (r RequeueType) String() string {
switch r {
case RequeueNoop:
return "requeue-noop"
case RequeueCheckOtherActions:
return "requeue-check-other-actions"
case RequeueRetry:
return "requeue-retry"
case RequeueWait:
return "requeue-wait"
default:
return "requeue-unknown"
}
}
const (
// how long do we wait until we process the next item
queueWaitDuration = 1 * time.Second
// This is a ratio used in determining whether a store is above, around or
// below the mean. If a store has range count that is greater than the mean
// plus the product of the mean and this ratio, it is considered above the
// mean; and if the range count is less than the mean minus the product of
// the mean and this ratio, it is considered below the mean. Otherwise, it's
// considered around the mean.
replicaCountMeanRatioThreshold = .05
// The minimum number of ranges by which a store must deviate from the mean
// to be considered above or below the mean.
minReplicaCountThreshold = 2
// Similar to replica count mean ration Threshold; but for lease count
// instead.
leaseCountMeanRatioThreshold = .05
// The minimum number of leases by which a store must deviate from the mean
// to be considered above or below the mean.
minLeaseCountThreshold = 2
)
func (a DriverAction) Priority() float64 {
switch a {
case DriverInitializePartition:
return 800
case DriverReplaceDeadReplica:
return 700
case DriverAddReplica:
return 600
case DriverFinishReplicaRemoval:
return 500
case DriverRemoveDeadReplica:
return 400
case DriverRemoveReplica:
return 300
case DriverSplitRange:
return 200
case DriverRebalanceReplica, DriverRebalanceLease, DriverNoop:
return 0
default:
alert.UnexpectedEvent("unknown-driver-action", "unknown driver action %s", a)
return -1
}
}
func (a DriverAction) String() string {
switch a {
case DriverRemoveDeadReplica:
return "remove-dead-replica"
case DriverAddReplica:
return "add-replica"
case DriverRemoveReplica:
return "remove-replica"
case DriverReplaceDeadReplica:
return "replace-dead-replica"
case DriverFinishReplicaRemoval:
return "finish-replica-removal"
case DriverSplitRange:
return "split-range"
case DriverRebalanceReplica:
return "consider-rebalance-replica"
case DriverRebalanceLease:
return "consider-rebalance-lease"
case DriverNoop:
return "no-op"
case DriverInitializePartition:
return "initialize-partition"
default:
return "unknown"
}
}
type IReplica interface {
ReplicaID() uint64
RangeID() uint64
Usage() (*rfpb.ReplicaUsage, error)
}
type IStore interface {
GetReplica(rangeID uint64) (*replica.Replica, error)
GetRange(rangeID uint64) *rfpb.RangeDescriptor
HaveLease(ctx context.Context, rangeID uint64) bool
AddReplica(ctx context.Context, req *rfpb.AddReplicaRequest) (*rfpb.AddReplicaResponse, error)
RemoveReplica(ctx context.Context, req *rfpb.RemoveReplicaRequest) (*rfpb.RemoveReplicaResponse, error)
GetReplicaStates(ctx context.Context, rd *rfpb.RangeDescriptor) map[uint64]constants.ReplicaState
SplitRange(ctx context.Context, req *rfpb.SplitRangeRequest) (*rfpb.SplitRangeResponse, error)
TransferLeadership(ctx context.Context, req *rfpb.TransferLeadershipRequest) (*rfpb.TransferLeadershipResponse, error)
NHID() string
ReserveRangeIDs(ctx context.Context, n int) ([]uint64, error)
InitializeShardsForPartition(ctx context.Context, nodeGrpcAddrs map[string]string, partition disk.Partition) error
}
type IClient interface {
HaveReadyConnections(ctx context.Context, rd *rfpb.ReplicaDescriptor) (bool, error)
GetForReplica(ctx context.Context, rd *rfpb.ReplicaDescriptor) (rfspb.ApiClient, error)
}
// computeQuorum computes a quorum, which a majority of members from a peer set.
// In raft, when a quorum of nodes is unavailable, the cluster becomes
// unavailable.
func computeQuorum(numNodes int) int {
return (numNodes / 2) + 1
}
type attemptRecord struct {
action DriverAction
attempts int
nextAttemptTime time.Time
}
type TaskType int
const (
_ TaskType = iota
RangeTaskType
PartitionTaskType
)
type taskKey struct {
taskType TaskType
rangeID uint64 // used for range tasks
partitionID string // used for partition tasks
}
type rangeTask struct {
repl IReplica
}
type partitionTask struct {
config disk.Partition
pd *rfpb.PartitionDescriptor
}
type driverTask struct {
key taskKey
// Task-type-specific data
rangeTask *rangeTask
partitionTask *partitionTask
processing bool
requeue bool
attemptRecord attemptRecord
item *priority_queue.Item[taskKey]
}
type queueImpl interface {
processTask(ctx context.Context, task *driverTask, action DriverAction) RequeueType
computeAction(ctx context.Context, task *driverTask) (DriverAction, float64)
getReplica(rangeID uint64) (IReplica, error)
}
type baseQueue struct {
impl queueImpl
maxSize int
stop chan struct{}
mu sync.Mutex //protects pq, taskMap
pq *priority_queue.PriorityQueue[taskKey]
taskMap map[taskKey]*driverTask
clock clockwork.Clock
log log.Logger
eg *errgroup.Group
egCtx context.Context
egCancel context.CancelFunc
}
func newBaseQueue(nhlog log.Logger, clock clockwork.Clock, impl queueImpl) *baseQueue {
ctx, cancelFunc := context.WithCancel(context.Background())
eg, gctx := errgroup.WithContext(ctx)
return &baseQueue{
clock: clock,
log: nhlog,
maxSize: 1000,
pq: &priority_queue.PriorityQueue[taskKey]{},
taskMap: make(map[taskKey]*driverTask),
eg: eg,
egCtx: gctx,
egCancel: cancelFunc,
impl: impl,
}
}
func (bq *baseQueue) pop() *driverTask {
bq.mu.Lock()
defer bq.mu.Unlock()
item := heap.Pop(bq.pq).(*priority_queue.Item[taskKey])
key := item.Value()
task, ok := bq.taskMap[key]
if !ok {
alert.UnexpectedEvent("unexpected_task_not_found", "task not found for key %+v", key)
return nil
}
task.processing = true
return task
}
func (bq *baseQueue) pushLocked(task *driverTask, priority float64) {
item := priority_queue.NewItem(task.key, priority)
heap.Push(bq.pq, item)
task.item = item
bq.taskMap[task.key] = task
}
func (bq *baseQueue) removeItemWithMinPriority() {
item := bq.pq.RemoveItemWithMinPriority()
if item == nil {
return
}
key := item.Value()
task, ok := bq.taskMap[key]
if !ok {
alert.UnexpectedEvent("unexpected_task_not_found", "task not found for key %+v", key)
return
}
if task.processing {
task.requeue = false
return
}
delete(bq.taskMap, key)
}
func (bq *baseQueue) Len() int {
bq.mu.Lock()
defer bq.mu.Unlock()
return bq.pq.Len()
}
func (bq *baseQueue) postProcess(ctx context.Context, task *driverTask, requeueType RequeueType) {
ar := attemptRecord{}
if requeueType == RequeueRetry {
ar = task.attemptRecord
ar.attempts++
ar.nextAttemptTime = bq.nextAttemptTime(ar.attempts)
} else if requeueType == RequeueWait {
ar = task.attemptRecord
}
bq.mu.Lock()
delete(bq.taskMap, task.key)
bq.mu.Unlock()
if ar.attempts >= maxRetry {
if task.key.taskType == RangeTaskType {
alert.UnexpectedEvent("driver_action_retries_exceeded", "c%dn%d action: %s retries exceeded", task.key.rangeID, task.rangeTask.repl.ReplicaID(), ar.action)
} else if task.key.taskType == PartitionTaskType {
alert.UnexpectedEvent("driver_action_retries_exceeded", "partition %s action: %s retries exceeded", task.key.partitionID, ar.action)
}
// do not add it to the queue
} else if requeueType != RequeueNoop || task.requeue {
if task.key.taskType == RangeTaskType {
bq.maybeAddRangeTask(ctx, task.rangeTask, ar)
} else if task.key.taskType == PartitionTaskType {
bq.maybeAddPartitionTask(ctx, task.partitionTask, ar)
}
}
}
func (bq *baseQueue) nextAttemptTime(attemptNumber int) time.Time {
backoff := float64(1*time.Second) * math.Pow(2, float64(attemptNumber))
return bq.clock.Now().Add(time.Duration(backoff))
}
func (bq *baseQueue) process(ctx context.Context, task *driverTask) RequeueType {
action, _ := bq.impl.computeAction(ctx, task)
if task.key.taskType == RangeTaskType {
rangeID := task.key.rangeID
if task.rangeTask == nil {
bq.log.Errorf("task is nil for range %d", rangeID)
return RequeueNoop
}
replicaID := task.rangeTask.repl.ReplicaID()
bq.log.Debugf("start to process c%dn%d", rangeID, replicaID)
} else if task.key.taskType == PartitionTaskType {
bq.log.Debugf("start to process partition %s", task.key.partitionID)
if task.partitionTask == nil {
bq.log.Errorf("task is nil for partition %s", task.key.partitionID)
return RequeueNoop
}
}
ar := task.attemptRecord
if action == ar.action && !ar.nextAttemptTime.IsZero() {
if bq.clock.Now().Before(ar.nextAttemptTime) {
// Do nothing until nextAttemptTime becomes current
return RequeueWait
}
}
return bq.impl.processTask(ctx, task, action)
}
// The Queue is responsible for up-replicate, down-replicate and reblance ranges
// across the stores.
type Queue struct {
*baseQueue
storeMap storemap.IStoreMap
store IStore
sender *sender.Sender
apiClient IClient
minReplicasPerRange int
minMetaRangeReplicas int
efp interfaces.ExperimentFlagProvider
}
func NewQueue(store IStore, sender *sender.Sender, gossipManager interfaces.GossipService, nhlog log.Logger, apiClient IClient, clock clockwork.Clock, efp interfaces.ExperimentFlagProvider) *Queue {
storeMap := storemap.New(gossipManager, clock, nhlog, *minReplicasPerRange, *minMetaRangeReplicas, *missingLeaseCountThreshold)
q := &Queue{
storeMap: storeMap,
store: store,
apiClient: apiClient,
sender: sender,
minReplicasPerRange: *minReplicasPerRange,
minMetaRangeReplicas: *minMetaRangeReplicas,
efp: efp,
}
q.baseQueue = newBaseQueue(nhlog, clock, q)
return q
}
func (rq *Queue) getReplica(rangeID uint64) (IReplica, error) {
return rq.store.GetReplica(rangeID)
}
const driverEnabledFlag = "cache.raft.enable_driver"
const splitEnabledFlag = "cache.raft.enable_split"
// isDriverEnabled checks if the driver is enabled via the experiment flag.
// By default, the driver is enabled (returns true).
func (rq *Queue) isDriverEnabled(ctx context.Context) bool {
if rq.efp == nil {
return true
}
return rq.efp.Boolean(ctx, driverEnabledFlag, true)
}
// isSplitEnabled checks if split is enabled via the experiment flag.
// By default, split is enabled (returns true).
func (rq *Queue) isSplitEnabled(ctx context.Context) bool {
if rq.efp == nil {
return true
}
return rq.efp.Boolean(ctx, splitEnabledFlag, true)
}
// computeActionForRangeTask computes the drive action needed for range task and its priority.
func (rq *Queue) computeActionForRangeTask(ctx context.Context, task *rangeTask) (DriverAction, float64) {
// Handle range tasks
repl := task.repl
rangeID := repl.RangeID()
rd := rq.store.GetRange(rangeID)
action := DriverNoop
if rd == nil || !rq.store.HaveLease(ctx, rd.GetRangeId()) {
return action, action.Priority()
}
if rd.GetDeleted() {
// If the range descriptor is marked as deleted, we don't want to do
// any up/down-replicate and reblance actions, except for finish the
// cleanup.
return action, action.Priority()
}
needsRemoveData := false
if len(rd.GetRemoved()) > 0 {
// There is no point to call to finish replica removal if the node is
// dead.
byStatus := rq.storeMap.DivideByStatus(rd.GetRemoved())
if len(byStatus.LiveReplicas)+len(byStatus.SuspectReplicas) > 0 {
needsRemoveData = true
action = DriverFinishReplicaRemoval
}
}
if rq.storeMap == nil {
return action, action.Priority()
}
replicas := rd.GetReplicas()
curReplicas := len(replicas)
if curReplicas == 0 {
return action, action.Priority()
}
minReplicas := rq.minReplicasPerRange
if rangeID == constants.MetaRangeID {
minReplicas = rq.minMetaRangeReplicas
}
desiredQuorum := computeQuorum(minReplicas)
quorum := computeQuorum(curReplicas)
if curReplicas < minReplicas || len(rd.GetStaging()) > 0 {
action = DriverAddReplica
adjustedPriority := action.Priority() + float64(desiredQuorum-curReplicas)
change := rq.addReplica(rd)
if change == nil {
// not able to find target node for allocation; if there is
// in-progress replica removal, complete it so this can be a target
// for allocation
if needsRemoveData {
return DriverFinishReplicaRemoval, adjustedPriority
}
}
return action, adjustedPriority
}
replicasByStatus := rq.storeMap.DivideByStatus(replicas)
numLiveReplicas := len(replicasByStatus.LiveReplicas) + len(replicasByStatus.SuspectReplicas)
numDeadReplicas := len(replicasByStatus.DeadReplicas)
if numLiveReplicas < quorum {
// We don't have enough live nodes to do any cluster membership change;
// However, RemoveData doesn't require cluster membership change
if needsRemoveData {
return DriverFinishReplicaRemoval, action.Priority()
}
log.Debugf("noop because num live replicas of range %d = %d less than quorum =%d", rd.GetRangeId(), numLiveReplicas, quorum)
action = DriverNoop
return action, action.Priority()
}
if curReplicas <= minReplicas && numDeadReplicas > 0 {
action = DriverReplaceDeadReplica
// not able to find target node for allocation; if there is
// in-progress replica removal, complete it so this can be a target
// for allocation
if needsRemoveData {
return DriverFinishReplicaRemoval, action.Priority()
}
return action, action.Priority()
}
if numDeadReplicas > 0 {
action = DriverRemoveDeadReplica
return action, action.Priority()
}
if curReplicas > minReplicas {
action = DriverRemoveReplica
adjustedPriority := action.Priority() - float64(curReplicas%2)
return action, adjustedPriority
}
if needsRemoveData {
action = DriverFinishReplicaRemoval
return action, action.Priority()
}
if rd.GetRangeId() == constants.MetaRangeID {
// Do not try to re-balance meta-range.
//
// When meta-range is moved onto a different node, range cache has to
// update its range descriptor. Before the range descriptor get updated,
// SyncPropose to all other ranges can fail temporarily because the range
// descriptor is not current. Therefore, we should only move meta-range
// when it's absolutely necessary.
action = DriverNoop
return action, action.Priority()
}
// Do not split when there is a store that's unavailable and a replica is
// in the middle of a removal.
isClusterHealthy := rq.storeMap.AllStoresAvailableAndReady()
if isClusterHealthy && rq.isSplitEnabled(ctx) {
if targetRangeSizeBytes := config.TargetRangeSizeBytes(); targetRangeSizeBytes > 0 {
usage, err := repl.Usage()
if err != nil {
rq.log.Errorf("failed to get Usage of replica c%dn%d", repl.RangeID(), repl.ReplicaID())
} else {
jitterFactor := config.RangeSizeJitterFactor()
lowerBound := (1 - jitterFactor) * float64(targetRangeSizeBytes)
jitter := (rand.Float64()*2 - 1) * jitterFactor * float64(targetRangeSizeBytes)
threshold := float64(targetRangeSizeBytes) + jitter
if sizeUsed := usage.GetEstimatedDiskBytesUsed(); float64(sizeUsed) >= threshold {
action = DriverSplitRange
adjustedPriority := action.Priority() + (float64(sizeUsed)-lowerBound)/float64(sizeUsed)*100.0
return action, adjustedPriority
}
}
}
}
// Do not try to rebalance replica or leases when there is a store that's
// unavailable because it can make the system more unstable.
if isClusterHealthy {
// For DriverConsiderRebalance check if there are rebalance opportunities.
storesWithStats := rq.storeMap.GetStoresWithStats()
op := rq.findRebalanceReplicaOp(rd, storesWithStats, repl.ReplicaID())
if op != nil {
log.Debugf("find rebalancing opportunities: from (nhid=%q, replicaCount=%d, isReady=%t) to (nhid=%q, replicaCount=%d, isReady=%t)", op.from.nhid, op.from.replicaCount, op.from.usage.GetIsReady(), op.to.nhid, op.to.replicaCount, op.to.usage.GetIsReady())
action = DriverRebalanceReplica
return action, action.Priority()
}
}
if rq.findRebalanceLeaseOp(ctx, rd, repl.ReplicaID()) != nil {
action = DriverRebalanceLease
return action, action.Priority()
}
action = DriverNoop
return action, action.Priority()
}
// computeActionForPartitionTask computes the action needed for a partition task and its priority.
func (rq *Queue) computeActionForPartitionTask(ctx context.Context, task *partitionTask) (DriverAction, float64) {
if task.pd == nil || task.pd.GetState() == rfpb.PartitionDescriptor_INITIALIZING {
a := DriverInitializePartition
rq.log.Infof("action: %s for partition: %q", a, task.config.ID)
return a, a.Priority()
}
return DriverNoop, DriverNoop.Priority()
}
// computeAction computes the action needed and its priority.
func (rq *Queue) computeAction(ctx context.Context, task *driverTask) (DriverAction, float64) {
switch task.key.taskType {
case RangeTaskType:
return rq.computeActionForRangeTask(ctx, task.rangeTask)
case PartitionTaskType:
return rq.computeActionForPartitionTask(ctx, task.partitionTask)
}
return DriverNoop, DriverNoop.Priority()
}
func (bq *baseQueue) maybeAddTask(ctx context.Context, newTask *driverTask, ar attemptRecord) {
bq.mu.Lock()
defer bq.mu.Unlock()
task, ok := bq.taskMap[newTask.key]
if !ok {
task = newTask
}
action, priority := bq.impl.computeAction(ctx, task)
if action == DriverNoop {
return
}
if ok {
// The item is processing. Mark to be requeued.
if task.processing {
task.requeue = true
return
}
if task.attemptRecord.action != action {
// clear the attempt record if action is different
task.attemptRecord = attemptRecord{
action: action,
}
}
bq.pq.Update(task.item, priority)
return
}
if action == ar.action {
task.attemptRecord = ar
} else {
task.attemptRecord = attemptRecord{
action: action,
}
}
bq.pushLocked(task, priority)
// If the priroityQueue if full, let's remove the item with the lowest priority.
if pqLen := bq.pq.Len(); pqLen > bq.maxSize {
bq.removeItemWithMinPriority()
}
}
func (bq *baseQueue) maybeAddRangeTask(ctx context.Context, rt *rangeTask, ar attemptRecord) {
if rt.repl == nil {
return
}
rangeID := rt.repl.RangeID()
key := taskKey{taskType: RangeTaskType, rangeID: rangeID}
newTask := &driverTask{
key: key,
rangeTask: rt,
}
bq.maybeAddTask(ctx, newTask, ar)
}
func (bq *baseQueue) maybeAddPartitionTask(ctx context.Context, pt *partitionTask, ar attemptRecord) {
key := taskKey{taskType: PartitionTaskType, partitionID: pt.config.ID}
newTask := &driverTask{
key: key,
partitionTask: pt,
}
bq.maybeAddTask(ctx, newTask, ar)
}
func (rq *Queue) MaybeAddPartitionTask(ctx context.Context, p disk.Partition, pd *rfpb.PartitionDescriptor) {
if !rq.isDriverEnabled(ctx) {
return
}
rq.log.Infof("maybe add partition task for %q", p.ID)
rq.maybeAddPartitionTask(ctx, &partitionTask{config: p, pd: pd}, attemptRecord{})
}
func (rq *Queue) MaybeAddRangeTask(ctx context.Context, replica IReplica) {
if !rq.isDriverEnabled(ctx) {
return
}
rq.maybeAddRangeTask(ctx, &rangeTask{repl: replica}, attemptRecord{})
}
func (bq *baseQueue) Start() {
bq.eg.Go(func() error {
queueDelay := bq.clock.NewTicker(queueWaitDuration)
defer queueDelay.Stop()
for {
select {
case <-bq.egCtx.Done():
return nil
case <-queueDelay.Chan():
bq.processQueue()
}
}
})
}
func (bq *baseQueue) Stop() {
bq.log.Infof("Driver shutdown started")
now := time.Now()
defer func() {
bq.log.Infof("Driver shutdown finished in %s", time.Since(now))
}()
bq.egCancel()
bq.eg.Wait()
}
func (bq *baseQueue) processQueue() {
if bq.Len() == 0 {
return
}
task := bq.pop()
if task == nil {
return
}
requeueType := bq.process(bq.egCtx, task)
bq.postProcess(bq.egCtx, task, requeueType)
}
// findDeadReplica finds a dead replica to be removed.
func findDeadReplica(replicas []*rfpb.ReplicaDescriptor, replicaByStatus *storemap.ReplicasByStatus) *rfpb.ReplicaDescriptor {
if len(replicaByStatus.DeadReplicas) == 0 {
// nothing to be removed
return nil
}
if len(replicas) == 1 {
// only one replica remains, don't remove the replica
return nil
}
return replicaByStatus.DeadReplicas[0]
}
func storeHasReplica(node *rfpb.NodeDescriptor, existing []*rfpb.ReplicaDescriptor) bool {
for _, repl := range existing {
if repl.GetNhid() == node.GetNhid() {
return true
}
}
return false
}
func (rq *Queue) findNodesForAllocation(storesWithStats *storemap.StoresWithStats) []*rfpb.NodeDescriptor {
var candidates []*candidate
for _, su := range storesWithStats.Usages {
if isDiskFull(su) {
rq.log.Debugf("skip node %+v because the disk is full", su)
continue
}
rq.log.Debugf("add node %+v to candidate list", su.GetNode())
candidates = append(candidates, &candidate{
nhid: su.GetNode().GetNhid(),
usage: su,
replicaCount: su.GetReplicaCount(),
replicaCountMeanLevel: replicaCountMeanLevel(storesWithStats, su),
})
}
quorum := computeQuorum(rq.minReplicasPerRange)
if len(candidates) < quorum {
log.Info("we don't have enough nodes to bring up a new raft cluster")
// We don't have enough nodes to bring up a new raft cluster.
return nil
}
slices.SortFunc(candidates, func(a, b *candidate) int {
// Best targets are up front.
return -compareByScoreAndID(a, b)
})
res := make([]*rfpb.NodeDescriptor, 0, rq.minReplicasPerRange)
for i := 0; i < min(rq.minReplicasPerRange, len(candidates)); i++ {
res = append(res, candidates[i].usage.GetNode())
}
return res
}
// findNodeForAllocation finds a target node for the range to up-replicate.
func (rq *Queue) findNodeForAllocation(rd *rfpb.RangeDescriptor, storesWithStats *storemap.StoresWithStats) *rfpb.NodeDescriptor {
var candidates []*candidate
existing := append(rd.GetReplicas(), rd.GetRemoved()...)
for _, su := range storesWithStats.Usages {
if storeHasReplica(su.GetNode(), rd.GetStaging()) {
// There is a staging replica, complete it.
return su.GetNode()
}
if storeHasReplica(su.GetNode(), existing) {
rq.log.Debugf("skip node %+v because the replica is already on the node", su.GetNode())
continue
}
if isDiskFull(su) {
rq.log.Debugf("skip node %+v because the disk is full", su)
continue
}
rq.log.Debugf("add node %+v to candidate list", su.GetNode())
candidates = append(candidates, &candidate{
nhid: su.GetNode().GetNhid(),
usage: su,
replicaCount: su.GetReplicaCount(),
replicaCountMeanLevel: replicaCountMeanLevel(storesWithStats, su),
})
}
if len(candidates) == 0 {
return nil
}
slices.SortFunc(candidates, func(a, b *candidate) int {
// Best targets are up front.
return -compareByScoreAndID(a, b)
})
return candidates[0].usage.GetNode()
}
type removeDataOp struct {
replDesc *rfpb.ReplicaDescriptor
rd *rfpb.RangeDescriptor
}
type change struct {
addOp *rfpb.AddReplicaRequest
removeOp *rfpb.RemoveReplicaRequest
removeDataOp *removeDataOp
splitOp *rfpb.SplitRangeRequest
transferLeadershipOp *rfpb.TransferLeadershipRequest
}
func (rq *Queue) finishReplicaRemoval(rd *rfpb.RangeDescriptor) *change {
if len(rd.GetRemoved()) == 0 {
return nil
}
return &change{
removeDataOp: &removeDataOp{
replDesc: rd.GetRemoved()[0],
rd: rd,
},
}
}
func (rq *Queue) splitRange(rd *rfpb.RangeDescriptor) *change {
return &change{
splitOp: &rfpb.SplitRangeRequest{
Header: header.New(rd, rd.GetReplicas()[0], rfpb.Header_LINEARIZABLE),
Range: rd,
},
}
}
func (rq *Queue) addReplica(rd *rfpb.RangeDescriptor) *change {
storesWithStats := rq.storeMap.GetStoresWithStats()
target := rq.findNodeForAllocation(rd, storesWithStats)
if target == nil {
rq.log.Debugf("cannot find targets for range descriptor:%+v", rd)
return nil
}
return &change{
addOp: &rfpb.AddReplicaRequest{
Range: rd,
Node: target,
},
}
}
func (rq *Queue) initializePartition(ctx context.Context, p disk.Partition) error {
rq.log.Infof("initialize partitions: %q", p.ID)
storesWithStats := rq.storeMap.GetStoresWithStats()
nodes := rq.findNodesForAllocation(storesWithStats)
if nodes == nil {
return status.InternalErrorf("cannot find nodes to initialize partition %q", p.ID)
}
nodeGrpcAddrs := make(map[string]string, len(nodes))
for _, n := range nodes {
nodeGrpcAddrs[n.GetNhid()] = n.GetGrpcAddress()
}
return rq.store.InitializeShardsForPartition(ctx, nodeGrpcAddrs, p)
}
func (rq *Queue) replaceDeadReplica(rd *rfpb.RangeDescriptor) *change {
replicasByStatus := rq.storeMap.DivideByStatus(rd.GetReplicas())
dead := findDeadReplica(rd.GetReplicas(), replicasByStatus)
if dead == nil {
// nothing to remove
return nil
}
change := rq.addReplica(rd)
if change == nil {
rq.log.Debug("replaceDeadReplica cannot find node for allocation")
return nil
}
change.removeOp = &rfpb.RemoveReplicaRequest{
Range: rd,
ReplicaId: dead.GetReplicaId(),
}
return change
}
func (rq *Queue) removeDeadReplica(rd *rfpb.RangeDescriptor) *change {
replicasByStatus := rq.storeMap.DivideByStatus(rd.GetReplicas())
dead := findDeadReplica(rd.GetReplicas(), replicasByStatus)
if dead == nil {
// nothing to remove
return nil
}
return &change{
removeOp: &rfpb.RemoveReplicaRequest{
Range: rd,
ReplicaId: dead.GetReplicaId(),
},
}
}
type rebalanceChoice struct {
existing *candidate
candidates []*candidate
}
type rebalanceOp struct {
from *candidate
to *candidate
}
func compareOp(op1 *rebalanceOp, op2 *rebalanceOp) int {
c1 := compareByScore(op1.to, op1.from)
c2 := compareByScore(op2.to, op2.from)
if c1 != c2 {
return cmp.Compare(c1, c2)
}
return compareByScore(op1.to, op2.to)
}
func canConvergeByRebalanceReplica(existingStores map[string]*candidate, targets []*candidate, allStores *storemap.StoresWithStats) bool {
overfullThreshold := int64(math.Ceil(aboveMeanReplicaCountThreshold(allStores.ReplicaCount.Mean)))
// The existing store is too far above the mean.
aboveMean := false