-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
allocator.go
2984 lines (2768 loc) · 111 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 allocatorimpl
import (
"context"
"encoding/json"
"fmt"
"math"
"math/rand"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/load"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/storepool"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/constraint"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/raftutil"
"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/metric"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/errors"
"go.etcd.io/raft/v3"
"go.etcd.io/raft/v3/tracker"
)
const (
// 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
)
// 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.
// Made configurable for the sake of testing.
var LeaseRebalanceThreshold = settings.RegisterFloatSetting(
settings.SystemOnly,
"kv.allocator.lease_rebalance_threshold",
"minimum fraction away from the mean a store's lease count can be before "+
"it is considered for lease-transfers",
0.05,
).WithPublic()
// LeaseRebalanceThresholdMin is the absolute number of leases above/below the
// mean lease count that a store can have before considered overfull/underfull.
// Made configurable for the sake of testing.
var LeaseRebalanceThresholdMin = 5.0
// getBaseLoadBasedLeaseRebalanceThreshold returns 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.
func getBaseLoadBasedLeaseRebalanceThreshold(leaseRebalanceThreshold float64) float64 {
return 2 * leaseRebalanceThreshold
}
// 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(
settings.SystemOnly,
"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(
settings.SystemOnly,
"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,
)
// recoveryStoreSelector controls the strategy for choosing a store to recover
// replicas to: either to any valid store ("good") or to a store that has low
// range count ("best"). With this set to "good", recovering from a dead node or
// from a decommissioning node can be faster, because nodes can send replicas to
// more target stores (instead of multiple nodes sending replicas to a few
// stores with a low range count).
var recoveryStoreSelector = settings.RegisterStringSetting(
settings.SystemOnly,
"kv.allocator.recovery_store_selector",
"if set to 'good', the allocator may recover replicas to any valid store, if set "+
"to 'best' it will pick one of the most ideal stores",
"good",
)
// 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
)
// Add indicates an action adding a replica.
func (a AllocatorAction) Add() bool {
return a == AllocatorAddVoter || a == AllocatorAddNonVoter
}
// Replace indicates an action replacing a dead or decommissioning replica.
func (a AllocatorAction) Replace() bool {
return a == AllocatorReplaceDeadVoter ||
a == AllocatorReplaceDeadNonVoter ||
a == AllocatorReplaceDecommissioningVoter ||
a == AllocatorReplaceDecommissioningNonVoter
}
// Remove indicates an action removing a replica, i.e. in overreplication cases.
func (a AllocatorAction) Remove() bool {
return a == AllocatorRemoveVoter ||
a == AllocatorRemoveNonVoter ||
a == AllocatorRemoveDeadVoter ||
a == AllocatorRemoveDeadNonVoter ||
a == AllocatorRemoveDecommissioningVoter ||
a == AllocatorRemoveDecommissioningNonVoter
}
// TargetReplicaType returns that the action is for a voter or non-voter replica.
func (a AllocatorAction) TargetReplicaType() TargetReplicaType {
var t TargetReplicaType
if a == AllocatorRemoveVoter ||
a == AllocatorAddVoter ||
a == AllocatorReplaceDeadVoter ||
a == AllocatorRemoveDeadVoter ||
a == AllocatorReplaceDecommissioningVoter ||
a == AllocatorRemoveDecommissioningVoter {
t = VoterTarget
} else if a == AllocatorRemoveNonVoter ||
a == AllocatorAddNonVoter ||
a == AllocatorReplaceDeadNonVoter ||
a == AllocatorRemoveDeadNonVoter ||
a == AllocatorReplaceDecommissioningNonVoter ||
a == AllocatorRemoveDecommissioningNonVoter {
t = NonVoterTarget
}
return t
}
// ReplicaStatus returns that the action is due to a live, dead, or
// decommissioning replica.
func (a AllocatorAction) ReplicaStatus() ReplicaStatus {
var s ReplicaStatus
if a == AllocatorRemoveVoter ||
a == AllocatorRemoveNonVoter ||
a == AllocatorAddVoter ||
a == AllocatorAddNonVoter {
s = Alive
} else if a == AllocatorReplaceDeadVoter ||
a == AllocatorReplaceDeadNonVoter ||
a == AllocatorRemoveDeadVoter ||
a == AllocatorRemoveDeadNonVoter {
s = Dead
} else if a == AllocatorReplaceDecommissioningVoter ||
a == AllocatorReplaceDecommissioningNonVoter ||
a == AllocatorRemoveDecommissioningVoter ||
a == AllocatorRemoveDecommissioningNonVoter {
s = Decommissioning
}
return s
}
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))
}
}
// TargetReplicaType indicates whether the target replica is a voter or
// non-voter.
type TargetReplicaType int
const (
_ TargetReplicaType = iota
// VoterTarget represents a voting target replica.
VoterTarget
// NonVoterTarget represents a non-voting target replica.
NonVoterTarget
)
// ReplicaStatus represents whether a replica is currently alive,
// dead or decommissioning.
type ReplicaStatus int
const (
_ ReplicaStatus = iota
// Alive represents a replica on a live node.
Alive
// Dead represents a replica on a dead node.
Dead
// Decommissioning represents a replica on a dead node.
Decommissioning
)
// 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))
}
}
func (s ReplicaStatus) String() string {
switch s {
case Alive:
return "live"
case Dead:
return "dead"
case Decommissioning:
return "decommissioning"
default:
panic(fmt.Sprintf("unknown replicaStatus %d", s))
}
}
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) AllocationErrorMarker() {}
func (*allocatorError) PurgatoryErrorMarker() {}
// 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),
}
}
var (
// Load-based lease transfers.
metaLBLeaseTransferCannotFindBetterCandidate = metric.Metadata{
Name: "kv.allocator.load_based_lease_transfers.cannot_find_better_candidate",
Help: "The number times the allocator determined that the lease was on the best" +
" possible replica",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBLeaseTransferExistingNotOverfull = metric.Metadata{
Name: "kv.allocator.load_based_lease_transfers.existing_not_overfull",
Help: "The number times the allocator determined that the lease was not on an" +
" overfull store",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBLeaseTransferDeltaNotSignificant = metric.Metadata{
Name: "kv.allocator.load_based_lease_transfers.delta_not_significant",
Help: "The number times the allocator determined that the delta between the existing" +
" store and the best candidate was not significant",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBLeaseTransferMissingStatsForExistingStore = metric.Metadata{
Name: "kv.allocator.load_based_lease_transfers.missing_stats_for_existing_stores",
Help: "The number times the allocator was missing qps stats for the leaseholder",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBLeaseTransferShouldTransfer = metric.Metadata{
Name: "kv.allocator.load_based_lease_transfers.should_transfer",
Help: "The number times the allocator determined that the lease should be" +
" transferred to another replica for better load distribution",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBLeaseTransferFollowTheWorkload = metric.Metadata{
Name: "kv.allocator.load_based_lease_transfers.follow_the_workload",
Help: "The number times the allocator determined that the lease should be" +
" transferred to another replica for locality.",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
// Load-based replica rebalances.
metaLBReplicaRebalancingCannotFindBetterCandidate = metric.Metadata{
Name: "kv.allocator.load_based_replica_rebalancing.cannot_find_better_candidate",
Help: "The number times the allocator determined that the range was on the best" +
" possible stores",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBReplicaRebalancingExistingNotOverfull = metric.Metadata{
Name: "kv.allocator.load_based_replica_rebalancing.existing_not_overfull",
Help: "The number times the allocator determined that none of the range's replicas" +
" were on overfull stores",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBReplicaRebalancingDeltaNotSignificant = metric.Metadata{
Name: "kv.allocator.load_based_replica_rebalancing.delta_not_significant",
Help: "The number times the allocator determined that the delta between an" +
" existing store and the best replacement candidate was not high enough",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBReplicaRebalancingMissingStatsForExistingStore = metric.Metadata{
Name: "kv.allocator.load_based_replica_rebalancing.missing_stats_for_existing_store",
Help: "The number times the allocator was missing the qps stats for the existing store",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
metaLBReplicaRebalancingShouldTransfer = metric.Metadata{
Name: "kv.allocator.load_based_replica_rebalancing.should_transfer",
Help: "The number times the allocator determined that the replica should be" +
" rebalanced to another store for better load distribution",
Measurement: "Attempts",
Unit: metric.Unit_COUNT,
}
)
type loadBasedLeaseTransferMetrics struct {
CannotFindBetterCandidate *metric.Counter
ExistingNotOverfull *metric.Counter
DeltaNotSignificant *metric.Counter
MissingStatsForExistingStore *metric.Counter
ShouldTransfer *metric.Counter
FollowTheWorkload *metric.Counter
}
type loadBasedReplicaRebalanceMetrics struct {
CannotFindBetterCandidate *metric.Counter
ExistingNotOverfull *metric.Counter
DeltaNotSignificant *metric.Counter
MissingStatsForExistingStore *metric.Counter
ShouldRebalance *metric.Counter
}
// AllocatorMetrics capture metrics about the allocator's decisions.
type AllocatorMetrics struct {
LoadBasedLeaseTransferMetrics loadBasedLeaseTransferMetrics
LoadBasedReplicaRebalanceMetrics loadBasedReplicaRebalanceMetrics
}
// Allocator tries to spread replicas as evenly as possible across the stores
// in the cluster.
type Allocator struct {
st *cluster.Settings
deterministic bool
nodeLatencyFn func(nodeID roachpb.NodeID) (time.Duration, bool)
// TODO(aayush): Let's replace this with a *rand.Rand that has a rand.Source
// wrapped inside a mutex, to avoid misuse.
randGen allocatorRand
Metrics AllocatorMetrics
knobs *allocator.TestingKnobs
}
func makeAllocatorMetrics() AllocatorMetrics {
return AllocatorMetrics{
LoadBasedLeaseTransferMetrics: loadBasedLeaseTransferMetrics{
CannotFindBetterCandidate: metric.NewCounter(metaLBLeaseTransferCannotFindBetterCandidate),
ExistingNotOverfull: metric.NewCounter(metaLBLeaseTransferExistingNotOverfull),
DeltaNotSignificant: metric.NewCounter(metaLBLeaseTransferDeltaNotSignificant),
MissingStatsForExistingStore: metric.NewCounter(metaLBLeaseTransferMissingStatsForExistingStore),
ShouldTransfer: metric.NewCounter(metaLBLeaseTransferShouldTransfer),
FollowTheWorkload: metric.NewCounter(metaLBLeaseTransferFollowTheWorkload),
},
LoadBasedReplicaRebalanceMetrics: loadBasedReplicaRebalanceMetrics{
CannotFindBetterCandidate: metric.NewCounter(metaLBReplicaRebalancingCannotFindBetterCandidate),
ExistingNotOverfull: metric.NewCounter(metaLBReplicaRebalancingExistingNotOverfull),
DeltaNotSignificant: metric.NewCounter(metaLBReplicaRebalancingDeltaNotSignificant),
MissingStatsForExistingStore: metric.NewCounter(metaLBReplicaRebalancingMissingStatsForExistingStore),
ShouldRebalance: metric.NewCounter(metaLBReplicaRebalancingShouldTransfer),
},
}
}
// MakeAllocator creates a new allocator.
// The deterministic flag indicates that this allocator is intended to be used
// with a deterministic store pool.
//
// In test cases where the store pool is nil, deterministic should be false.
// TODO(sarkesian): Eliminate the need for this flag, which is a remnant of
// close coupling with the StorePool.
func MakeAllocator(
st *cluster.Settings,
deterministic bool,
nodeLatencyFn func(nodeID roachpb.NodeID) (time.Duration, bool),
knobs *allocator.TestingKnobs,
) Allocator {
var randSource rand.Source
if deterministic {
randSource = rand.NewSource(777)
} else {
randSource = rand.NewSource(rand.Int63())
}
allocator := Allocator{
st: st,
deterministic: deterministic,
nodeLatencyFn: nodeLatencyFn,
randGen: makeAllocatorRand(randSource),
Metrics: makeAllocatorMetrics(),
knobs: knobs,
}
return allocator
}
// 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
}
// WillHaveFragileQuorum determines, based on the number of existing voters,
// incoming voters, and needed voters, if we will be upreplicating to a state
// in which we don't have enough needed voters and yet will have a fragile quorum
// due to an even number of voter replicas.
func WillHaveFragileQuorum(
numExistingVoters, numNewVoters, zoneConfigVoterCount, clusterNodes int,
) bool {
neededVoters := GetNeededVoters(int32(zoneConfigVoterCount), clusterNodes)
willHave := numExistingVoters + numNewVoters
// NB: If willHave >= neededVoters, then always allow up-replicating as that
// will be the case when up-replicating a range with a decommissioning
// replica.
return numNewVoters > 0 && willHave < neededVoters && willHave%2 == 0
}
// LiveAndDeadVoterAndNonVoterReplicas splits up the replica in the given range
// descriptor by voters vs non-voters and live replicas vs dead replicas.
func LiveAndDeadVoterAndNonVoterReplicas(
storePool storepool.AllocatorStorePool, desc *roachpb.RangeDescriptor,
) (
voterReplicas, nonVoterReplicas, liveVoterReplicas, deadVoterReplicas, liveNonVoterReplicas, deadNonVoterReplicas []roachpb.ReplicaDescriptor,
) {
voterReplicas = desc.Replicas().VoterDescriptors()
nonVoterReplicas = desc.Replicas().NonVoterDescriptors()
liveVoterReplicas, deadVoterReplicas = storePool.LiveAndDeadReplicas(
voterReplicas, true, /* includeSuspectAndDrainingStores */
)
liveNonVoterReplicas, deadNonVoterReplicas = storePool.LiveAndDeadReplicas(
nonVoterReplicas, true, /* includeSuspectAndDrainingStores */
)
return
}
// DetermineReplicaToReplaceAndFilter is used on add or replace allocator actions
// to filter the set of live voter and non-voter replicas to use in determining
// a new allocation target. It identifies a dead or decommissioning replica to
// replace from the list of voters or non-voters, depending on the replica
// status and target type, and returns the filtered live voters and non-voters
// along with the list of existing replicas and the index of the removal candidate.
// In case of an add action, no replicas are removed and a removeIdx of -1 is
// returned, and if no candidates for replacement can be found during a replace
// action, the returned nothingToDo flag will be set to true.
func DetermineReplicaToReplaceAndFilter(
storePool storepool.AllocatorStorePool,
action AllocatorAction,
voters, nonVoters []roachpb.ReplicaDescriptor,
liveVoterReplicas, deadVoterReplicas []roachpb.ReplicaDescriptor,
liveNonVoterReplicas, deadNonVoterReplicas []roachpb.ReplicaDescriptor,
) (
existing, remainingLiveVoters, remainingLiveNonVoters []roachpb.ReplicaDescriptor,
removeIdx int,
nothingToDo bool,
err error,
) {
removeIdx = -1
remainingLiveVoters = liveVoterReplicas
remainingLiveNonVoters = liveNonVoterReplicas
var deadReplicas, removalCandidates []roachpb.ReplicaDescriptor
if !(action.Add() || action.Replace()) {
err = errors.AssertionFailedf(
"unexpected attempt to filter replicas on non-add/non-replacement action %s",
action,
)
return
}
replicaType := action.TargetReplicaType()
replicaStatus := action.ReplicaStatus()
switch replicaType {
case VoterTarget:
existing = voters
deadReplicas = deadVoterReplicas
case NonVoterTarget:
existing = nonVoters
deadReplicas = deadNonVoterReplicas
default:
panic(fmt.Sprintf("unknown targetReplicaType: %s", replicaType))
}
switch replicaStatus {
case Alive:
// NB: Live replicas are not candidates for replacement.
return
case Dead:
removalCandidates = deadReplicas
case Decommissioning:
removalCandidates = storePool.DecommissioningReplicas(existing)
default:
panic(fmt.Sprintf("unknown replicaStatus: %s", replicaStatus))
}
if len(removalCandidates) == 0 {
nothingToDo = true
return
}
removeIdx = getRemoveIdx(existing, removalCandidates[0])
if removeIdx < 0 {
err = errors.AssertionFailedf(
"%s %s %v unexpectedly not found in %v",
replicaStatus, replicaType, removalCandidates[0], existing,
)
return
}
// TODO(sarkesian): Add comment on why this filtering only happens for voters.
if replicaType == VoterTarget {
if len(existing) == 1 {
// If only one replica remains, that replica is the leaseholder and
// we won't be able to swap it out. Ignore the removal and simply add
// a replica.
removeIdx = -1
}
if removeIdx >= 0 {
replToRemove := existing[removeIdx]
for i, r := range liveVoterReplicas {
if r.ReplicaID == replToRemove.ReplicaID {
remainingLiveVoters = append(liveVoterReplicas[:i:i], liveVoterReplicas[i+1:]...)
break
}
}
}
}
return
}
func getRemoveIdx(
repls []roachpb.ReplicaDescriptor, deadOrDecommissioningRepl roachpb.ReplicaDescriptor,
) (removeIdx int) {
removeIdx = -1
for i, rDesc := range repls {
if rDesc.StoreID == deadOrDecommissioningRepl.StoreID {
removeIdx = i
break
}
}
return removeIdx
}
// FilterReplicasForAction converts a range descriptor to the filtered
// voter and non-voter replicas needed to allocate a target for the given action.
// NB: This is a convenience method for callers of allocator.AllocateTarget(..).
func FilterReplicasForAction(
storePool storepool.AllocatorStorePool, desc *roachpb.RangeDescriptor, action AllocatorAction,
) (
filteredVoters, filteredNonVoters []roachpb.ReplicaDescriptor,
replacing *roachpb.ReplicaDescriptor,
nothingToDo bool,
err error,
) {
voterReplicas, nonVoterReplicas,
liveVoterReplicas, deadVoterReplicas,
liveNonVoterReplicas, deadNonVoterReplicas := LiveAndDeadVoterAndNonVoterReplicas(storePool, desc)
removeIdx := -1
var existing []roachpb.ReplicaDescriptor
existing, filteredVoters, filteredNonVoters, removeIdx, nothingToDo, err = DetermineReplicaToReplaceAndFilter(
storePool,
action,
voterReplicas, nonVoterReplicas,
liveVoterReplicas, deadVoterReplicas,
liveNonVoterReplicas, deadNonVoterReplicas,
)
if removeIdx >= 0 {
replacing = &existing[removeIdx]
}
return filteredVoters, filteredNonVoters, replacing, nothingToDo, err
}
// 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,
storePool storepool.AllocatorStorePool,
conf roachpb.SpanConfig,
desc *roachpb.RangeDescriptor,
) (action AllocatorAction, priority float64) {
if 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, storePool, conf, desc.Replicas().VoterDescriptors(),
desc.Replicas().NonVoterDescriptors())
}
func (a *Allocator) computeAction(
ctx context.Context,
storePool storepool.AllocatorStorePool,
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 := storePool.DecommissioningReplicas(voterReplicas)
postDecommissionVoters := haveVoters - len(decommissioningVoters)
// Node count including dead nodes but excluding
// decommissioning/decommissioned nodes.
clusterNodes := 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.KvDistribution.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 := 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.KvDistribution.VEventf(ctx, 1, "unable to take action - live voters %v don't meet quorum of %d",
liveVoters, quorum)
return action, action.Priority()
}
if postDecommissionVoters <= neededVoters && len(deadVoters) > 0 {
// Range has dead voter(s). We should up-replicate to add another 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.KvDistribution.VEventf(ctx, 3, "%s - replacement for %d dead voters priority=%.2f",