-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
allocator.go
2060 lines (1909 loc) · 77.3 KB
/
allocator.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 2014 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.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/APL.txt.
package kvserver
import (
"context"
"encoding/json"
"fmt"
"math"
"math/rand"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/constraint"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/errors"
"go.etcd.io/etcd/raft/v3"
"go.etcd.io/etcd/raft/v3/tracker"
)
const (
// leaseRebalanceThreshold is the minimum ratio of a store's lease surplus
// to the mean range/lease count that permits lease-transfers away from that
// store.
leaseRebalanceThreshold = 0.05
// baseLoadBasedLeaseRebalanceThreshold is the equivalent of
// leaseRebalanceThreshold for load-based lease rebalance decisions (i.e.
// "follow-the-workload"). It's the base threshold for decisions that get
// adjusted based on the load and latency of the involved ranges/nodes.
baseLoadBasedLeaseRebalanceThreshold = 2 * leaseRebalanceThreshold
// minReplicaWeight sets a floor for how low a replica weight can be. This is
// needed because a weight of zero doesn't work in the current lease scoring
// algorithm.
minReplicaWeight = 0.001
)
// MinLeaseTransferStatsDuration configures the minimum amount of time a
// replica must wait for stats about request counts to accumulate before
// making decisions based on them. The higher this is, the less likely
// thrashing is (up to a point).
// Made configurable for the sake of testing.
var MinLeaseTransferStatsDuration = 30 * time.Second
// enableLoadBasedLeaseRebalancing controls whether lease rebalancing is done
// via the new heuristic based on request load and latency or via the simpler
// approach that purely seeks to balance the number of leases per node evenly.
var enableLoadBasedLeaseRebalancing = settings.RegisterBoolSetting(
"kv.allocator.load_based_lease_rebalancing.enabled",
"set to enable rebalancing of range leases based on load and latency",
true,
).WithPublic()
// leaseRebalancingAggressiveness enables users to tweak how aggressive their
// cluster is at moving leases towards the localities where the most requests
// are coming from. Settings lower than 1.0 will make the system less
// aggressive about moving leases toward requests than the default, while
// settings greater than 1.0 will cause more aggressive placement.
//
// Setting this to 0 effectively disables load-based lease rebalancing, and
// settings less than 0 are disallowed.
var leaseRebalancingAggressiveness = settings.RegisterFloatSetting(
"kv.allocator.lease_rebalancing_aggressiveness",
"set greater than 1.0 to rebalance leases toward load more aggressively, "+
"or between 0 and 1.0 to be more conservative about rebalancing leases",
1.0,
settings.NonNegativeFloat,
)
// AllocatorAction enumerates the various replication adjustments that may be
// recommended by the allocator.
type AllocatorAction int
// These are the possible allocator actions.
const (
_ AllocatorAction = iota
AllocatorNoop
AllocatorRemoveVoter
AllocatorRemoveNonVoter
AllocatorAddVoter
AllocatorAddNonVoter
AllocatorReplaceDeadVoter
AllocatorReplaceDeadNonVoter
AllocatorRemoveDeadVoter
AllocatorRemoveDeadNonVoter
AllocatorReplaceDecommissioningVoter
AllocatorReplaceDecommissioningNonVoter
AllocatorRemoveDecommissioningVoter
AllocatorRemoveDecommissioningNonVoter
AllocatorRemoveLearner
AllocatorConsiderRebalance
AllocatorRangeUnavailable
AllocatorFinalizeAtomicReplicationChange
)
var allocatorActionNames = map[AllocatorAction]string{
AllocatorNoop: "noop",
AllocatorRemoveVoter: "remove voter",
AllocatorRemoveNonVoter: "remove non-voter",
AllocatorAddVoter: "add voter",
AllocatorAddNonVoter: "add non-voter",
AllocatorReplaceDeadVoter: "replace dead voter",
AllocatorReplaceDeadNonVoter: "replace dead non-voter",
AllocatorRemoveDeadVoter: "remove dead voter",
AllocatorRemoveDeadNonVoter: "remove dead non-voter",
AllocatorReplaceDecommissioningVoter: "replace decommissioning voter",
AllocatorReplaceDecommissioningNonVoter: "replace decommissioning non-voter",
AllocatorRemoveDecommissioningVoter: "remove decommissioning voter",
AllocatorRemoveDecommissioningNonVoter: "remove decommissioning non-voter",
AllocatorRemoveLearner: "remove learner",
AllocatorConsiderRebalance: "consider rebalance",
AllocatorRangeUnavailable: "range unavailable",
AllocatorFinalizeAtomicReplicationChange: "finalize conf change",
}
func (a AllocatorAction) String() string {
return allocatorActionNames[a]
}
// Priority defines the priorities for various repair operations.
//
// NB: These priorities only influence the replicateQueue's understanding of
// which ranges are to be dealt with before others. In other words, these
// priorities don't influence the relative order of actions taken on a given
// range. Within a given range, the ordering of the various checks inside
// `Allocator.computeAction` determines which repair/rebalancing actions are
// taken before the others.
func (a AllocatorAction) Priority() float64 {
switch a {
case AllocatorFinalizeAtomicReplicationChange:
return 12002
case AllocatorRemoveLearner:
return 12001
case AllocatorReplaceDeadVoter:
return 12000
case AllocatorAddVoter:
return 10000
case AllocatorReplaceDecommissioningVoter:
return 5000
case AllocatorRemoveDeadVoter:
return 1000
case AllocatorRemoveDecommissioningVoter:
return 900
case AllocatorRemoveVoter:
return 800
case AllocatorReplaceDeadNonVoter:
return 700
case AllocatorAddNonVoter:
return 600
case AllocatorReplaceDecommissioningNonVoter:
return 500
case AllocatorRemoveDeadNonVoter:
return 400
case AllocatorRemoveDecommissioningNonVoter:
return 300
case AllocatorRemoveNonVoter:
return 200
case AllocatorConsiderRebalance, AllocatorRangeUnavailable, AllocatorNoop:
return 0
default:
panic(fmt.Sprintf("unknown AllocatorAction: %s", a))
}
}
type targetReplicaType int
const (
_ targetReplicaType = iota
voterTarget
nonVoterTarget
)
// AddChangeType returns the roachpb.ReplicaChangeType corresponding to the
// given targetReplicaType.
//
// TODO(aayush): Clean up usages of ADD_{NON_}VOTER. Use
// targetReplicaType.{Add,Remove}ChangeType methods wherever possible.
func (t targetReplicaType) AddChangeType() roachpb.ReplicaChangeType {
switch t {
case voterTarget:
return roachpb.ADD_VOTER
case nonVoterTarget:
return roachpb.ADD_NON_VOTER
default:
panic(fmt.Sprintf("unknown targetReplicaType %d", t))
}
}
// RemoveChangeType returns the roachpb.ReplicaChangeType corresponding to the
// given targetReplicaType.
func (t targetReplicaType) RemoveChangeType() roachpb.ReplicaChangeType {
switch t {
case voterTarget:
return roachpb.REMOVE_VOTER
case nonVoterTarget:
return roachpb.REMOVE_NON_VOTER
default:
panic(fmt.Sprintf("unknown targetReplicaType %d", t))
}
}
func (t targetReplicaType) String() string {
switch t {
case voterTarget:
return "voter"
case nonVoterTarget:
return "non-voter"
default:
panic(fmt.Sprintf("unknown targetReplicaType %d", t))
}
}
type transferDecision int
const (
_ transferDecision = iota
shouldTransfer
shouldNotTransfer
decideWithoutStats
)
// allocatorError indicates a retryable error condition which sends replicas
// being processed through the replicate_queue into purgatory so that they
// can be retried quickly as soon as new stores come online, or additional
// space frees up.
type allocatorError struct {
constraints []roachpb.ConstraintsConjunction
voterConstraints []roachpb.ConstraintsConjunction
existingVoterCount int
existingNonVoterCount int
aliveStores int
throttledStores int
}
func (ae *allocatorError) Error() string {
var existingVoterStr string
if ae.existingVoterCount == 1 {
existingVoterStr = "1 already has a voter"
} else {
existingVoterStr = fmt.Sprintf("%d already have a voter", ae.existingVoterCount)
}
var existingNonVoterStr string
if ae.existingNonVoterCount == 1 {
existingNonVoterStr = "1 already has a non-voter"
} else {
existingNonVoterStr = fmt.Sprintf("%d already have a non-voter", ae.existingNonVoterCount)
}
var baseMsg string
if ae.throttledStores != 0 {
baseMsg = fmt.Sprintf(
"0 of %d live stores are able to take a new replica for the range (%d throttled, %s, %s)",
ae.aliveStores, ae.throttledStores, existingVoterStr, existingNonVoterStr)
} else {
baseMsg = fmt.Sprintf(
"0 of %d live stores are able to take a new replica for the range (%s, %s)",
ae.aliveStores, existingVoterStr, existingNonVoterStr)
}
if len(ae.constraints) == 0 && len(ae.voterConstraints) == 0 {
if ae.throttledStores > 0 {
return baseMsg
}
return baseMsg + "; likely not enough nodes in cluster"
}
var b strings.Builder
b.WriteString(baseMsg)
b.WriteString("; replicas must match constraints [")
for i := range ae.constraints {
if i > 0 {
b.WriteByte(' ')
}
b.WriteByte('{')
b.WriteString(ae.constraints[i].String())
b.WriteByte('}')
}
b.WriteString("]")
b.WriteString("; voting replicas must match voter_constraints [")
for i := range ae.voterConstraints {
if i > 0 {
b.WriteByte(' ')
}
b.WriteByte('{')
b.WriteString(ae.voterConstraints[i].String())
b.WriteByte('}')
}
b.WriteString("]")
return b.String()
}
func (*allocatorError) purgatoryErrorMarker() {}
var _ purgatoryError = &allocatorError{}
// allocatorRand pairs a rand.Rand with a mutex.
// NOTE: Allocator is typically only accessed from a single thread (the
// replication queue), but this assumption is broken in tests which force
// replication scans. If those tests can be modified to suspend the normal
// replication queue during the forced scan, then this rand could be used
// without a mutex.
type allocatorRand struct {
*syncutil.Mutex
*rand.Rand
}
func makeAllocatorRand(source rand.Source) allocatorRand {
return allocatorRand{
Mutex: &syncutil.Mutex{},
Rand: rand.New(source),
}
}
// RangeUsageInfo contains usage information (sizes and traffic) needed by the
// allocator to make rebalancing decisions for a given range.
type RangeUsageInfo struct {
LogicalBytes int64
QueriesPerSecond float64
WritesPerSecond float64
}
func rangeUsageInfoForRepl(repl *Replica) RangeUsageInfo {
info := RangeUsageInfo{
LogicalBytes: repl.GetMVCCStats().Total(),
}
if queriesPerSecond, dur := repl.leaseholderStats.avgQPS(); dur >= MinStatsDuration {
info.QueriesPerSecond = queriesPerSecond
}
if writesPerSecond, dur := repl.writeStats.avgQPS(); dur >= MinStatsDuration {
info.WritesPerSecond = writesPerSecond
}
return info
}
// Allocator tries to spread replicas as evenly as possible across the stores
// in the cluster.
type Allocator struct {
storePool *StorePool
nodeLatencyFn func(addr string) (time.Duration, bool)
randGen allocatorRand
knobs *AllocatorTestingKnobs
}
// MakeAllocator creates a new allocator using the specified StorePool.
func MakeAllocator(
storePool *StorePool,
nodeLatencyFn func(addr string) (time.Duration, bool),
knobs *AllocatorTestingKnobs,
) Allocator {
var randSource rand.Source
// There are number of test cases that make a test store but don't add
// gossip or a store pool. So we can't rely on the existence of the
// store pool in those cases.
if storePool != nil && storePool.deterministic {
randSource = rand.NewSource(777)
} else {
randSource = rand.NewSource(rand.Int63())
}
return Allocator{
storePool: storePool,
nodeLatencyFn: nodeLatencyFn,
randGen: makeAllocatorRand(randSource),
knobs: knobs,
}
}
// GetNeededVoters calculates the number of voters a range should have given its
// zone config and the number of nodes available for up-replication (i.e. not
// decommissioning).
func GetNeededVoters(zoneConfigVoterCount int32, clusterNodes int) int {
numZoneReplicas := int(zoneConfigVoterCount)
need := numZoneReplicas
// Adjust the replication factor for all ranges if there are fewer
// nodes than replicas specified in the zone config, so the cluster
// can still function.
if clusterNodes < need {
need = clusterNodes
}
// Ensure that we don't up- or down-replicate to an even number of replicas
// unless an even number of replicas was specifically requested by the user
// in the zone config.
//
// Note that in the case of 5 desired replicas and a decommissioning store,
// this prefers down-replicating from 5 to 3 rather than sticking with 4
// desired stores or blocking the decommissioning from completing.
if need == numZoneReplicas {
return need
}
if need%2 == 0 {
need = need - 1
}
if need < 3 {
need = 3
}
if need > numZoneReplicas {
need = numZoneReplicas
}
return need
}
// GetNeededNonVoters calculates the number of non-voters a range should have
// given the number of voting replicas the range has and the number of nodes
// available for up-replication.
//
// NB: This method assumes that we have exactly as many voters as we need, since
// this method should only be consulted after voting replicas have been
// upreplicated / rebalanced off of dead/decommissioning nodes.
func GetNeededNonVoters(numVoters, zoneConfigNonVoterCount, clusterNodes int) int {
need := zoneConfigNonVoterCount
if clusterNodes-numVoters < need {
// We only need non-voting replicas for the nodes that do not have a voting
// replica.
need = clusterNodes - numVoters
}
if need < 0 {
need = 0 // Must be non-negative.
}
return need
}
// ComputeAction determines the exact operation needed to repair the
// supplied range, as governed by the supplied zone configuration. It
// returns the required action that should be taken and a priority.
func (a *Allocator) ComputeAction(
ctx context.Context, conf roachpb.SpanConfig, desc *roachpb.RangeDescriptor,
) (action AllocatorAction, priority float64) {
if a.storePool == nil {
// Do nothing if storePool is nil for some unittests.
action = AllocatorNoop
return action, action.Priority()
}
if desc.Replicas().InAtomicReplicationChange() {
// With a similar reasoning to the learner branch below, if we're in a
// joint configuration the top priority is to leave it before we can
// even think about doing anything else.
action = AllocatorFinalizeAtomicReplicationChange
return action, action.Priority()
}
if learners := desc.Replicas().LearnerDescriptors(); len(learners) > 0 {
// Seeing a learner replica at this point is unexpected because learners are
// a short-lived (ish) transient state in a learner+snapshot+voter cycle,
// which is always done atomically. Only two places could have added a
// learner: the replicate queue or AdminChangeReplicas request.
//
// The replicate queue only operates on leaseholders, which means that only
// one node at a time is operating on a given range except in rare cases
// (old leaseholder could start the operation, and a new leaseholder steps
// up and also starts an overlapping operation). Combined with the above
// atomicity, this means that if the replicate queue sees a learner, either
// the node that was adding it crashed somewhere in the
// learner+snapshot+voter cycle and we're the new leaseholder or we caught a
// race.
//
// In the first case, we could assume the node that was adding it knew what
// it was doing and finish the addition. Or we could leave it and do higher
// priority operations first if there are any. However, this comes with code
// complexity and concept complexity (computing old vs new quorum sizes
// becomes ambiguous, the learner isn't in the quorum but it likely will be
// soon, so do you count it?). Instead, we do the simplest thing and remove
// it before doing any other operations to the range. We'll revisit this
// decision if and when the complexity becomes necessary.
//
// If we get the race where AdminChangeReplicas is adding a replica and the
// queue happens to run during the snapshot, this will remove the learner
// and AdminChangeReplicas will notice either during the snapshot transfer
// or when it tries to promote the learner to a voter. AdminChangeReplicas
// should retry.
//
// On the other hand if we get the race where a leaseholder starts adding a
// replica in the replicate queue and during this loses its lease, it should
// probably not retry.
//
// TODO(dan): Since this goes before anything else, the priority here should
// be influenced by whatever operations would happen right after the learner
// is removed. In the meantime, we don't want to block something important
// from happening (like addDeadReplacementVoterPriority) by queueing this at
// a low priority so until this TODO is done, keep
// removeLearnerReplicaPriority as the highest priority.
action = AllocatorRemoveLearner
return action, action.Priority()
}
return a.computeAction(ctx, conf, desc.Replicas().VoterDescriptors(),
desc.Replicas().NonVoterDescriptors())
}
func (a *Allocator) computeAction(
ctx context.Context,
conf roachpb.SpanConfig,
voterReplicas []roachpb.ReplicaDescriptor,
nonVoterReplicas []roachpb.ReplicaDescriptor,
) (action AllocatorAction, adjustedPriority float64) {
// NB: The ordering of the checks in this method is intentional. The order in
// which these actions are returned by this method determines the relative
// priority of the actions taken on a given range. We want this to be
// symmetric with regards to the priorities defined at the top of this file
// (which influence the replicateQueue's decision of which range it'll pick to
// repair/rebalance before the others).
//
// In broad strokes, we first handle all voting replica-based actions and then
// the actions pertaining to non-voting replicas. Within each replica set, we
// first handle operations that correspond to repairing/recovering the range.
// After that we handle rebalancing related actions, followed by removal
// actions.
haveVoters := len(voterReplicas)
decommissioningVoters := a.storePool.decommissioningReplicas(voterReplicas)
// Node count including dead nodes but excluding
// decommissioning/decommissioned nodes.
clusterNodes := a.storePool.ClusterNodeCount()
neededVoters := GetNeededVoters(conf.GetNumVoters(), clusterNodes)
desiredQuorum := computeQuorum(neededVoters)
quorum := computeQuorum(haveVoters)
// TODO(aayush): When haveVoters < neededVoters but we don't have quorum to
// actually execute the addition of a new replica, we should be returning a
// AllocatorRangeUnavailable.
if haveVoters < neededVoters {
// Range is under-replicated, and should add an additional voter.
// Priority is adjusted by the difference between the current voter
// count and the quorum of the desired voter count.
action = AllocatorAddVoter
adjustedPriority = action.Priority() + float64(desiredQuorum-haveVoters)
log.VEventf(ctx, 3, "%s - missing voter need=%d, have=%d, priority=%.2f",
action, neededVoters, haveVoters, adjustedPriority)
return action, adjustedPriority
}
// NB: For the purposes of determining whether a range has quorum, we
// consider stores marked as "suspect" to be live. This is necessary because
// we would otherwise spuriously consider ranges with replicas on suspect
// stores to be unavailable, just because their nodes have failed a liveness
// heartbeat in the recent past. This means we won't move those replicas
// elsewhere (for a regular rebalance or for decommissioning).
const includeSuspectAndDrainingStores = true
liveVoters, deadVoters := a.storePool.liveAndDeadReplicas(voterReplicas, includeSuspectAndDrainingStores)
if len(liveVoters) < quorum {
// Do not take any replacement/removal action if we do not have a quorum of
// live voters. If we're correctly assessing the unavailable state of the
// range, we also won't be able to add replicas as we try above, but hope
// springs eternal.
action = AllocatorRangeUnavailable
log.VEventf(ctx, 1, "unable to take action - live voters %v don't meet quorum of %d",
liveVoters, quorum)
return action, action.Priority()
}
if haveVoters == neededVoters && len(deadVoters) > 0 {
// Range has dead voter(s). We should up-replicate to add another before
// before removing the dead one. This can avoid permanent data loss in cases
// where the node is only temporarily dead, but we remove it from the range
// and lose a second node before we can up-replicate (#25392).
action = AllocatorReplaceDeadVoter
log.VEventf(ctx, 3, "%s - replacement for %d dead voters priority=%.2f",
action, len(deadVoters), action.Priority())
return action, action.Priority()
}
if haveVoters == neededVoters && len(decommissioningVoters) > 0 {
// Range has decommissioning voter(s), which should be replaced.
action = AllocatorReplaceDecommissioningVoter
log.VEventf(ctx, 3, "%s - replacement for %d decommissioning voters priority=%.2f",
action, len(decommissioningVoters), action.Priority())
return action, action.Priority()
}
// Voting replica removal actions follow.
// TODO(aayush): There's an additional case related to dead voters that we
// should handle above. If there are one or more dead replicas, have < need,
// and there are no available stores to up-replicate to, then we should try to
// remove the dead replica(s) to get down to an odd number of replicas.
if len(deadVoters) > 0 {
// The range has dead replicas, which should be removed immediately.
action = AllocatorRemoveDeadVoter
adjustedPriority = action.Priority() + float64(quorum-len(liveVoters))
log.VEventf(ctx, 3, "%s - dead=%d, live=%d, quorum=%d, priority=%.2f",
action, len(deadVoters), len(liveVoters), quorum, adjustedPriority)
return action, adjustedPriority
}
if len(decommissioningVoters) > 0 {
// Range is over-replicated, and has a decommissioning voter which
// should be removed.
action = AllocatorRemoveDecommissioningVoter
log.VEventf(ctx, 3,
"%s - need=%d, have=%d, num_decommissioning=%d, priority=%.2f",
action, neededVoters, haveVoters, len(decommissioningVoters), action.Priority())
return action, action.Priority()
}
if haveVoters > neededVoters {
// Range is over-replicated, and should remove a voter.
// Ranges with an even number of voters get extra priority because
// they have a more fragile quorum.
action = AllocatorRemoveVoter
adjustedPriority = action.Priority() - float64(haveVoters%2)
log.VEventf(ctx, 3, "%s - need=%d, have=%d, priority=%.2f", action, neededVoters,
haveVoters, adjustedPriority)
return action, adjustedPriority
}
// Non-voting replica actions follow.
//
// Non-voting replica addition / replacement.
haveNonVoters := len(nonVoterReplicas)
neededNonVoters := GetNeededNonVoters(haveVoters, int(conf.GetNumNonVoters()), clusterNodes)
if haveNonVoters < neededNonVoters {
action = AllocatorAddNonVoter
log.VEventf(ctx, 3, "%s - missing non-voter need=%d, have=%d, priority=%.2f",
action, neededNonVoters, haveNonVoters, action.Priority())
return action, action.Priority()
}
liveNonVoters, deadNonVoters := a.storePool.liveAndDeadReplicas(
nonVoterReplicas, includeSuspectAndDrainingStores,
)
if haveNonVoters == neededNonVoters && len(deadNonVoters) > 0 {
// The range has non-voter(s) on a dead node that we should replace.
action = AllocatorReplaceDeadNonVoter
log.VEventf(ctx, 3, "%s - replacement for %d dead non-voters priority=%.2f",
action, len(deadNonVoters), action.Priority())
return action, action.Priority()
}
decommissioningNonVoters := a.storePool.decommissioningReplicas(nonVoterReplicas)
if haveNonVoters == neededNonVoters && len(decommissioningNonVoters) > 0 {
// The range has non-voter(s) on a decommissioning node that we should
// replace.
action = AllocatorReplaceDecommissioningNonVoter
log.VEventf(ctx, 3, "%s - replacement for %d decommissioning non-voters priority=%.2f",
action, len(decommissioningNonVoters), action.Priority())
return action, action.Priority()
}
// Non-voting replica removal.
if len(deadNonVoters) > 0 {
// The range is over-replicated _and_ has non-voter(s) on a dead node. We'll
// just remove these.
action = AllocatorRemoveDeadNonVoter
log.VEventf(ctx, 3, "%s - dead=%d, live=%d, priority=%.2f",
action, len(deadNonVoters), len(liveNonVoters), action.Priority())
return action, action.Priority()
}
if len(decommissioningNonVoters) > 0 {
// The range is over-replicated _and_ has non-voter(s) on a decommissioning
// node. We'll just remove these.
action = AllocatorRemoveDecommissioningNonVoter
log.VEventf(ctx, 3,
"%s - need=%d, have=%d, num_decommissioning=%d, priority=%.2f",
action, neededNonVoters, haveNonVoters, len(decommissioningNonVoters), action.Priority())
return action, action.Priority()
}
if haveNonVoters > neededNonVoters {
// The range is simply over-replicated and should remove a non-voter.
action = AllocatorRemoveNonVoter
log.VEventf(ctx, 3, "%s - need=%d, have=%d, priority=%.2f", action,
neededNonVoters, haveNonVoters, action.Priority())
return action, action.Priority()
}
// Nothing needs to be done, but we may want to rebalance.
action = AllocatorConsiderRebalance
return action, action.Priority()
}
// getReplicasForDiversityCalc returns the set of replica descriptors that
// should be used for computing the diversity scores for a target when
// allocating/removing/rebalancing a replica of `targetType`.
func getReplicasForDiversityCalc(
targetType targetReplicaType, existingVoters, allExistingReplicas []roachpb.ReplicaDescriptor,
) []roachpb.ReplicaDescriptor {
switch t := targetType; t {
case voterTarget:
// When computing the "diversity score" for a given store for a voting
// replica allocation/rebalance/removal, we consider the localities of only
// the stores that contain a voting replica for the range.
//
// Note that if we were to consider all stores that have any kind of replica
// for the range, voting replica allocation would be disincentivized to pick
// stores that (partially or fully) share locality hierarchies with stores
// that contain a non-voting replica. This is undesirable because this could
// inadvertently reduce the fault-tolerance of the range in cases like the
// following:
//
// Consider 3 regions (A, B, C), each with 2 AZs. Suppose that regions A and
// B have a voting replica each, whereas region C has a non-voting replica.
// In cases like these, we would want region C to be picked over regions A
// and B for allocating a new third voting replica since that improves our
// fault tolerance to the greatest degree.
// In the counterfactual (i.e. if we were to compute diversity scores based
// off of all `existingReplicas`), regions A, B, and C would all be equally
// likely to get a new voting replica.
return existingVoters
case nonVoterTarget:
return allExistingReplicas
default:
panic(fmt.Sprintf("unsupported targetReplicaType: %v", t))
}
}
type decisionDetails struct {
Target string
Existing string `json:",omitempty"`
}
func (a *Allocator) allocateTarget(
ctx context.Context,
conf roachpb.SpanConfig,
existingVoters, existingNonVoters []roachpb.ReplicaDescriptor,
targetType targetReplicaType,
) (*roachpb.StoreDescriptor, string, error) {
candidateStoreList, aliveStoreCount, throttled := a.storePool.getStoreList(storeFilterThrottled)
target, details := a.allocateTargetFromList(
ctx,
candidateStoreList,
conf,
existingVoters,
existingNonVoters,
a.scorerOptions(),
// When allocating a *new* replica, we explicitly disregard nodes with any
// existing replicas. This is important for multi-store scenarios as
// otherwise, stores on the nodes that have existing replicas are simply
// discouraged via the diversity heuristic. We want to entirely avoid
// allocating multiple replicas onto different stores of the same node.
false, /* allowMultipleReplsPerNode */
targetType,
)
if target != nil {
return target, details, nil
}
// When there are throttled stores that do match, we shouldn't send
// the replica to purgatory.
if len(throttled) > 0 {
return nil, "", errors.Errorf(
"%d matching stores are currently throttled: %v", len(throttled), throttled,
)
}
return nil, "", &allocatorError{
voterConstraints: conf.VoterConstraints,
constraints: conf.Constraints,
existingVoterCount: len(existingVoters),
existingNonVoterCount: len(existingNonVoters),
aliveStores: aliveStoreCount,
throttledStores: len(throttled),
}
}
// AllocateVoter returns a suitable store for a new allocation of a voting
// replica with the required attributes. Nodes already accommodating existing
// voting replicas are ruled out as targets.
func (a *Allocator) AllocateVoter(
ctx context.Context,
conf roachpb.SpanConfig,
existingVoters, existingNonVoters []roachpb.ReplicaDescriptor,
) (*roachpb.StoreDescriptor, string, error) {
return a.allocateTarget(ctx, conf, existingVoters, existingNonVoters, voterTarget)
}
// AllocateNonVoter returns a suitable store for a new allocation of a
// non-voting replica with the required attributes. Nodes already accommodating
// _any_ existing replicas are ruled out as targets.
func (a *Allocator) AllocateNonVoter(
ctx context.Context,
conf roachpb.SpanConfig,
existingVoters, existingNonVoters []roachpb.ReplicaDescriptor,
) (*roachpb.StoreDescriptor, string, error) {
return a.allocateTarget(ctx, conf, existingVoters, existingNonVoters, nonVoterTarget)
}
func (a *Allocator) allocateTargetFromList(
ctx context.Context,
candidateStores StoreList,
conf roachpb.SpanConfig,
existingVoters, existingNonVoters []roachpb.ReplicaDescriptor,
options rangeCountScorerOptions,
allowMultipleReplsPerNode bool,
targetType targetReplicaType,
) (*roachpb.StoreDescriptor, string) {
existingReplicas := append(existingVoters, existingNonVoters...)
analyzedOverallConstraints := constraint.AnalyzeConstraints(ctx, a.storePool.getStoreDescriptor,
existingReplicas, conf.NumReplicas, conf.Constraints)
analyzedVoterConstraints := constraint.AnalyzeConstraints(ctx, a.storePool.getStoreDescriptor,
existingVoters, conf.GetNumVoters(), conf.VoterConstraints)
var constraintsChecker constraintsCheckFn
switch t := targetType; t {
case voterTarget:
constraintsChecker = voterConstraintsCheckerForAllocation(
analyzedOverallConstraints,
analyzedVoterConstraints,
)
case nonVoterTarget:
constraintsChecker = nonVoterConstraintsCheckerForAllocation(analyzedOverallConstraints)
default:
log.Fatalf(ctx, "unsupported targetReplicaType: %v", t)
}
// We'll consider the targets that have a non-voter as feasible
// relocation/up-replication targets for existing/new voting replicas, since
// we always want voter constraint conformance to take precedence over
// non-voters. For instance, in cases where we can only satisfy constraints
// for either 1 voter or 1 non-voter, we want the voter to be able to displace
// the non-voter.
existingReplicaSet := getReplicasForDiversityCalc(targetType, existingVoters, existingReplicas)
candidates := rankedCandidateListForAllocation(
ctx,
candidateStores,
constraintsChecker,
existingReplicaSet,
a.storePool.getLocalitiesByStore(existingReplicaSet),
a.storePool.isStoreReadyForRoutineReplicaTransfer,
allowMultipleReplsPerNode,
options,
)
log.VEventf(ctx, 3, "allocate %s: %s", targetType, candidates)
if target := candidates.selectGood(a.randGen); target != nil {
log.VEventf(ctx, 3, "add target: %s", target)
details := decisionDetails{Target: target.compactString()}
detailsBytes, err := json.Marshal(details)
if err != nil {
log.Warningf(ctx, "failed to marshal details for choosing allocate target: %+v", err)
}
return &target.store, string(detailsBytes)
}
return nil, ""
}
func (a Allocator) simulateRemoveTarget(
ctx context.Context,
targetStore roachpb.StoreID,
conf roachpb.SpanConfig,
candidates []roachpb.ReplicaDescriptor,
existingVoters []roachpb.ReplicaDescriptor,
existingNonVoters []roachpb.ReplicaDescriptor,
rangeUsageInfo RangeUsageInfo,
targetType targetReplicaType,
options scorerOptions,
) (roachpb.ReplicaDescriptor, string, error) {
// Update statistics first
// TODO(a-robinson): This could theoretically interfere with decisions made by other goroutines,
// but as of October 2017 calls to the Allocator are mostly serialized by the ReplicateQueue
// (with the main exceptions being Scatter and the status server's allocator debug endpoint).
// Try to make this interfere less with other callers.
switch t := targetType; t {
case voterTarget:
a.storePool.updateLocalStoreAfterRebalance(targetStore, rangeUsageInfo, roachpb.ADD_VOTER)
defer a.storePool.updateLocalStoreAfterRebalance(
targetStore,
rangeUsageInfo,
roachpb.REMOVE_VOTER,
)
log.VEventf(ctx, 3, "simulating which voter would be removed after adding s%d",
targetStore)
return a.RemoveVoter(ctx, conf, candidates, existingVoters, existingNonVoters, options)
case nonVoterTarget:
a.storePool.updateLocalStoreAfterRebalance(targetStore, rangeUsageInfo, roachpb.ADD_NON_VOTER)
defer a.storePool.updateLocalStoreAfterRebalance(
targetStore,
rangeUsageInfo,
roachpb.REMOVE_NON_VOTER,
)
log.VEventf(ctx, 3, "simulating which non-voter would be removed after adding s%d",
targetStore)
return a.RemoveNonVoter(ctx, conf, candidates, existingVoters, existingNonVoters, options)
default:
panic(fmt.Sprintf("unknown targetReplicaType: %s", t))
}
}
func (a Allocator) removeTarget(
ctx context.Context,
conf roachpb.SpanConfig,
candidates []roachpb.ReplicationTarget,
existingVoters []roachpb.ReplicaDescriptor,
existingNonVoters []roachpb.ReplicaDescriptor,
targetType targetReplicaType,
options scorerOptions,
) (roachpb.ReplicaDescriptor, string, error) {
if len(candidates) == 0 {
return roachpb.ReplicaDescriptor{}, "", errors.Errorf("must supply at least one" +
" candidate replica to allocator.removeTarget()")
}
existingReplicas := append(existingVoters, existingNonVoters...)
// Retrieve store descriptors for the provided candidates from the StorePool.
candidateStoreIDs := make(roachpb.StoreIDSlice, len(candidates))
for i, exist := range candidates {
candidateStoreIDs[i] = exist.StoreID
}
candidateStoreList, _, _ := a.storePool.getStoreListFromIDs(candidateStoreIDs, storeFilterNone)
analyzedOverallConstraints := constraint.AnalyzeConstraints(ctx, a.storePool.getStoreDescriptor,
existingReplicas, conf.NumReplicas, conf.Constraints)
analyzedVoterConstraints := constraint.AnalyzeConstraints(ctx, a.storePool.getStoreDescriptor,
existingVoters, conf.GetNumVoters(), conf.VoterConstraints)
var constraintsChecker constraintsCheckFn
switch t := targetType; t {
case voterTarget:
// Voting replicas have to abide by both the overall `constraints` (which
// apply to all replicas) and `voter_constraints` which apply only to voting
// replicas.
constraintsChecker = voterConstraintsCheckerForRemoval(
analyzedOverallConstraints,
analyzedVoterConstraints,
)
case nonVoterTarget:
constraintsChecker = nonVoterConstraintsCheckerForRemoval(analyzedOverallConstraints)
default:
log.Fatalf(ctx, "unsupported targetReplicaType: %v", t)
}
replicaSetForDiversityCalc := getReplicasForDiversityCalc(targetType, existingVoters, existingReplicas)
rankedCandidates := candidateListForRemoval(
candidateStoreList,
constraintsChecker,
a.storePool.getLocalitiesByStore(replicaSetForDiversityCalc),
options,
)
log.VEventf(ctx, 3, "remove %s: %s", targetType, rankedCandidates)
if bad := rankedCandidates.selectBad(a.randGen); bad != nil {
for _, exist := range existingReplicas {
if exist.StoreID == bad.store.StoreID {
log.VEventf(ctx, 3, "remove target: %s", bad)
details := decisionDetails{Target: bad.compactString()}
detailsBytes, err := json.Marshal(details)
if err != nil {
log.Warningf(ctx, "failed to marshal details for choosing remove target: %+v", err)
}
return exist, string(detailsBytes), nil
}
}
}
return roachpb.ReplicaDescriptor{}, "", errors.New("could not select an appropriate replica to be removed")
}
// RemoveVoter returns a suitable replica to remove from the provided replica
// set. It first attempts to randomly select a target from the set of stores
// that have greater than the average number of replicas. Failing that, it falls
// back to selecting a random target from any of the existing voting replicas.
func (a Allocator) RemoveVoter(
ctx context.Context,
conf roachpb.SpanConfig,
voterCandidates []roachpb.ReplicaDescriptor,
existingVoters []roachpb.ReplicaDescriptor,
existingNonVoters []roachpb.ReplicaDescriptor,
options scorerOptions,
) (roachpb.ReplicaDescriptor, string, error) {
return a.removeTarget(
ctx,
conf,
roachpb.MakeReplicaSet(voterCandidates).ReplicationTargets(),
existingVoters,
existingNonVoters,
voterTarget,
options,
)
}
// RemoveNonVoter returns a suitable non-voting replica to remove from the
// provided set. It first attempts to randomly select a target from the set of
// stores that have greater than the average number of replicas. Failing that,
// it falls back to selecting a random target from any of the existing
// non-voting replicas.
func (a Allocator) RemoveNonVoter(
ctx context.Context,
conf roachpb.SpanConfig,
nonVoterCandidates []roachpb.ReplicaDescriptor,
existingVoters []roachpb.ReplicaDescriptor,
existingNonVoters []roachpb.ReplicaDescriptor,