-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
store_pool.go
791 lines (714 loc) · 27.5 KB
/
store_pool.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
// Copyright 2015 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 storage
import (
"bytes"
"context"
"fmt"
"sort"
"time"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage/storagepb"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/humanizeutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/shuffle"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/pkg/errors"
)
const (
// TestTimeUntilStoreDead is the test value for TimeUntilStoreDead to
// quickly mark stores as dead.
TestTimeUntilStoreDead = 5 * time.Millisecond
// TestTimeUntilStoreDeadOff is the test value for TimeUntilStoreDead that
// prevents the store pool from marking stores as dead.
TestTimeUntilStoreDeadOff = 24 * time.Hour
)
// DeclinedReservationsTimeout specifies a duration during which the local
// replicate queue will not consider stores which have rejected a reservation a
// viable target.
var DeclinedReservationsTimeout = settings.RegisterNonNegativeDurationSetting(
"server.declined_reservation_timeout",
"the amount of time to consider the store throttled for up-replication after a reservation was declined",
1*time.Second,
)
// FailedReservationsTimeout specifies a duration during which the local
// replicate queue will not consider stores which have failed a reservation a
// viable target.
var FailedReservationsTimeout = settings.RegisterNonNegativeDurationSetting(
"server.failed_reservation_timeout",
"the amount of time to consider the store throttled for up-replication after a failed reservation call",
5*time.Second,
)
const timeUntilStoreDeadSettingName = "server.time_until_store_dead"
// TimeUntilStoreDead wraps "server.time_until_store_dead".
var TimeUntilStoreDead = func() *settings.DurationSetting {
s := settings.RegisterValidatedDurationSetting(
timeUntilStoreDeadSettingName,
"the time after which if there is no new gossiped information about a store, it is considered dead",
5*time.Minute,
func(v time.Duration) error {
// Setting this to less than the interval for gossiping stores is a big
// no-no, since this value is compared to the age of the most recent gossip
// from each store to determine whether that store is live. Put a buffer of
// 15 seconds on top to allow time for gossip to propagate.
const minTimeUntilStoreDead = gossip.StoresInterval + 15*time.Second
if v < minTimeUntilStoreDead {
return errors.Errorf("cannot set %s to less than %v: %v",
timeUntilStoreDeadSettingName, minTimeUntilStoreDead, v)
}
return nil
},
)
s.SetVisibility(settings.Public)
return s
}()
// The NodeCountFunc returns a count of the total number of nodes the user
// intends for their to be in the cluster. The count includes dead nodes, but
// not decommissioned nodes.
type NodeCountFunc func() int
// A NodeLivenessFunc accepts a node ID and current time and returns whether or
// not the node is live. A node is considered dead if its liveness record has
// expired by more than TimeUntilStoreDead.
type NodeLivenessFunc func(
nid roachpb.NodeID, now time.Time, timeUntilStoreDead time.Duration,
) storagepb.NodeLivenessStatus
// MakeStorePoolNodeLivenessFunc returns a function which determines
// the status of a node based on information provided by the specified
// NodeLiveness.
func MakeStorePoolNodeLivenessFunc(nodeLiveness *NodeLiveness) NodeLivenessFunc {
return func(
nodeID roachpb.NodeID, now time.Time, timeUntilStoreDead time.Duration,
) storagepb.NodeLivenessStatus {
liveness, err := nodeLiveness.GetLiveness(nodeID)
if err != nil {
return storagepb.NodeLivenessStatus_UNAVAILABLE
}
return LivenessStatus(liveness, now, timeUntilStoreDead)
}
}
// LivenessStatus returns a NodeLivenessStatus enumeration value for the
// provided Liveness based on the provided timestamp and threshold.
//
// See the note on IsLive() for considerations on what should be passed in as
// `now`.
//
// The timeline of the states that a liveness goes through as time passes after
// the respective liveness record is written is the following:
//
// -----|-------LIVE---|------UNAVAILABLE---|------DEAD------------> time
// tWrite tExp tExp+threshold
//
// Explanation:
//
// - Let's say a node write its liveness record at tWrite. It sets the
// Expiration field of the record as tExp=tWrite+livenessThreshold.
// The node is considered LIVE (or DECOMISSIONING or UNAVAILABLE if draining).
// - At tExp, the IsLive() method starts returning false. The state becomes
// UNAVAILABLE (or stays DECOMISSIONING or UNAVAILABLE if draining).
// - Once threshold passes, the node is considered DEAD (or DECOMMISSIONED).
func LivenessStatus(
l storagepb.Liveness, now time.Time, deadThreshold time.Duration,
) storagepb.NodeLivenessStatus {
if l.IsDead(now, deadThreshold) {
if l.Decommissioning {
return storagepb.NodeLivenessStatus_DECOMMISSIONED
}
return storagepb.NodeLivenessStatus_DEAD
}
if l.Decommissioning {
return storagepb.NodeLivenessStatus_DECOMMISSIONING
}
if l.Draining {
return storagepb.NodeLivenessStatus_UNAVAILABLE
}
if l.IsLive(now) {
return storagepb.NodeLivenessStatus_LIVE
}
return storagepb.NodeLivenessStatus_UNAVAILABLE
}
type storeDetail struct {
desc *roachpb.StoreDescriptor
// throttledUntil is when a throttled store can be considered available again
// due to a failed or declined snapshot.
throttledUntil time.Time
// throttledBecause is set to the most recent reason for which a store was
// marked as throttled.
throttledBecause string
// lastUpdatedTime is set when a store is first consulted and every time
// gossip arrives for a store.
lastUpdatedTime time.Time
}
// isThrottled returns whether the store is currently throttled.
func (sd storeDetail) isThrottled(now time.Time) bool {
return sd.throttledUntil.After(now)
}
// storeStatus is the current status of a store.
type storeStatus int
// These are the possible values for a storeStatus.
const (
_ storeStatus = iota
// The store's node is not live or no gossip has been received from
// the store for more than the timeUntilStoreDead threshold.
storeStatusDead
// The store isn't available because it hasn't gossiped yet. This
// status lasts until either gossip is received from the store or
// the timeUntilStoreDead threshold has passed, at which point its
// status will change to dead.
storeStatusUnknown
// The store is alive but it is throttled.
storeStatusThrottled
// The store is alive but a replica for the same rangeID was recently
// discovered to be corrupt.
storeStatusReplicaCorrupted
// The store is alive and available.
storeStatusAvailable
// The store is decommissioning.
storeStatusDecommissioning
)
// status returns the current status of the store, including whether
// any of the replicas for the specified rangeID are corrupted.
func (sd *storeDetail) status(
now time.Time, threshold time.Duration, rangeID roachpb.RangeID, nl NodeLivenessFunc,
) storeStatus {
// The store is considered dead if it hasn't been updated via gossip
// within the liveness threshold. Note that lastUpdatedTime is set
// when the store detail is created and will have a non-zero value
// even before the first gossip arrives for a store.
deadAsOf := sd.lastUpdatedTime.Add(threshold)
if now.After(deadAsOf) {
return storeStatusDead
}
// If there's no descriptor (meaning no gossip ever arrived for this
// store), return unavailable.
if sd.desc == nil {
return storeStatusUnknown
}
// Even if the store has been updated via gossip, we still rely on
// the node liveness to determine whether it is considered live.
switch nl(sd.desc.Node.NodeID, now, threshold) {
case storagepb.NodeLivenessStatus_DEAD, storagepb.NodeLivenessStatus_DECOMMISSIONED:
return storeStatusDead
case storagepb.NodeLivenessStatus_DECOMMISSIONING:
return storeStatusDecommissioning
case storagepb.NodeLivenessStatus_UNKNOWN, storagepb.NodeLivenessStatus_UNAVAILABLE:
return storeStatusUnknown
}
if sd.isThrottled(now) {
return storeStatusThrottled
}
return storeStatusAvailable
}
// localityWithString maintains a string representation of each locality along
// with its protocol buffer implementation. This is for the sake of optimizing
// memory usage by allocating a single copy of each that can be returned to
// callers of getNodeLocalityString rather than each caller (which is currently
// each replica in the local store) making its own copy.
type localityWithString struct {
locality roachpb.Locality
str string
}
// StorePool maintains a list of all known stores in the cluster and
// information on their health.
type StorePool struct {
log.AmbientContext
st *cluster.Settings
clock *hlc.Clock
gossip *gossip.Gossip
nodeCountFn NodeCountFunc
nodeLivenessFn NodeLivenessFunc
startTime time.Time
deterministic bool
// We use separate mutexes for storeDetails and nodeLocalities because the
// nodeLocalities map is used in the critical code path of Replica.Send()
// and we'd rather not block that on something less important accessing
// storeDetails.
detailsMu struct {
syncutil.RWMutex
storeDetails map[roachpb.StoreID]*storeDetail
}
localitiesMu struct {
syncutil.RWMutex
nodeLocalities map[roachpb.NodeID]localityWithString
}
}
// NewStorePool creates a StorePool and registers the store updating callback
// with gossip.
func NewStorePool(
ambient log.AmbientContext,
st *cluster.Settings,
g *gossip.Gossip,
clock *hlc.Clock,
nodeCountFn NodeCountFunc,
nodeLivenessFn NodeLivenessFunc,
deterministic bool,
) *StorePool {
sp := &StorePool{
AmbientContext: ambient,
st: st,
clock: clock,
gossip: g,
nodeCountFn: nodeCountFn,
nodeLivenessFn: nodeLivenessFn,
startTime: clock.PhysicalTime(),
deterministic: deterministic,
}
sp.detailsMu.storeDetails = make(map[roachpb.StoreID]*storeDetail)
sp.localitiesMu.nodeLocalities = make(map[roachpb.NodeID]localityWithString)
// Enable redundant callbacks for the store keys because we use these
// callbacks as a clock to determine when a store was last updated even if it
// hasn't otherwise changed.
storeRegex := gossip.MakePrefixPattern(gossip.KeyStorePrefix)
g.RegisterCallback(storeRegex, sp.storeGossipUpdate, gossip.Redundant)
return sp
}
func (sp *StorePool) String() string {
sp.detailsMu.RLock()
defer sp.detailsMu.RUnlock()
ids := make(roachpb.StoreIDSlice, 0, len(sp.detailsMu.storeDetails))
for id := range sp.detailsMu.storeDetails {
ids = append(ids, id)
}
sort.Sort(ids)
var buf bytes.Buffer
now := sp.clock.Now().GoTime()
timeUntilStoreDead := TimeUntilStoreDead.Get(&sp.st.SV)
for _, id := range ids {
detail := sp.detailsMu.storeDetails[id]
fmt.Fprintf(&buf, "%d", id)
status := detail.status(now, timeUntilStoreDead, 0, sp.nodeLivenessFn)
if status != storeStatusAvailable {
fmt.Fprintf(&buf, " (status=%d)", status)
}
if detail.desc != nil {
fmt.Fprintf(&buf, ": range-count=%d fraction-used=%.2f",
detail.desc.Capacity.RangeCount, detail.desc.Capacity.FractionUsed())
}
throttled := detail.throttledUntil.Sub(now)
if throttled > 0 {
fmt.Fprintf(&buf, " [throttled=%.1fs]", throttled.Seconds())
}
_, _ = buf.WriteString("\n")
}
return buf.String()
}
// storeGossipUpdate is the gossip callback used to keep the StorePool up to date.
func (sp *StorePool) storeGossipUpdate(_ string, content roachpb.Value) {
var storeDesc roachpb.StoreDescriptor
if err := content.GetProto(&storeDesc); err != nil {
ctx := sp.AnnotateCtx(context.TODO())
log.Error(ctx, err)
return
}
sp.detailsMu.Lock()
detail := sp.getStoreDetailLocked(storeDesc.StoreID)
detail.desc = &storeDesc
detail.lastUpdatedTime = sp.clock.PhysicalTime()
sp.detailsMu.Unlock()
sp.localitiesMu.Lock()
sp.localitiesMu.nodeLocalities[storeDesc.Node.NodeID] =
localityWithString{storeDesc.Node.Locality, storeDesc.Node.Locality.String()}
sp.localitiesMu.Unlock()
}
// updateLocalStoreAfterRebalance is used to update the local copy of the
// target store immediately after a replica addition or removal.
func (sp *StorePool) updateLocalStoreAfterRebalance(
storeID roachpb.StoreID, rangeUsageInfo RangeUsageInfo, changeType roachpb.ReplicaChangeType,
) {
sp.detailsMu.Lock()
defer sp.detailsMu.Unlock()
detail := *sp.getStoreDetailLocked(storeID)
if detail.desc == nil {
// We don't have this store yet (this is normal when we're
// starting up and don't have full information from the gossip
// network). We can't update the local store at this time.
return
}
switch changeType {
case roachpb.ADD_REPLICA:
detail.desc.Capacity.RangeCount++
detail.desc.Capacity.LogicalBytes += rangeUsageInfo.LogicalBytes
detail.desc.Capacity.WritesPerSecond += rangeUsageInfo.WritesPerSecond
case roachpb.REMOVE_REPLICA:
detail.desc.Capacity.RangeCount--
if detail.desc.Capacity.LogicalBytes <= rangeUsageInfo.LogicalBytes {
detail.desc.Capacity.LogicalBytes = 0
} else {
detail.desc.Capacity.LogicalBytes -= rangeUsageInfo.LogicalBytes
}
if detail.desc.Capacity.WritesPerSecond <= rangeUsageInfo.WritesPerSecond {
detail.desc.Capacity.WritesPerSecond = 0
} else {
detail.desc.Capacity.WritesPerSecond -= rangeUsageInfo.WritesPerSecond
}
}
sp.detailsMu.storeDetails[storeID] = &detail
}
// updateLocalStoresAfterLeaseTransfer is used to update the local copies of the
// involved store descriptors immediately after a lease transfer.
func (sp *StorePool) updateLocalStoresAfterLeaseTransfer(
from roachpb.StoreID, to roachpb.StoreID, rangeQPS float64,
) {
sp.detailsMu.Lock()
defer sp.detailsMu.Unlock()
fromDetail := *sp.getStoreDetailLocked(from)
if fromDetail.desc != nil {
fromDetail.desc.Capacity.LeaseCount--
if fromDetail.desc.Capacity.QueriesPerSecond < rangeQPS {
fromDetail.desc.Capacity.QueriesPerSecond = 0
} else {
fromDetail.desc.Capacity.QueriesPerSecond -= rangeQPS
}
sp.detailsMu.storeDetails[from] = &fromDetail
}
toDetail := *sp.getStoreDetailLocked(to)
if toDetail.desc != nil {
toDetail.desc.Capacity.LeaseCount++
toDetail.desc.Capacity.QueriesPerSecond += rangeQPS
sp.detailsMu.storeDetails[to] = &toDetail
}
}
// newStoreDetail makes a new storeDetail struct. It sets index to be -1 to
// ensure that it will be processed by a queue immediately.
func newStoreDetail() *storeDetail {
return &storeDetail{}
}
// GetStores returns information on all the stores with descriptor in the pool.
// Stores without descriptor (a node that didn't come up yet after a cluster
// restart) will not be part of the returned set.
func (sp *StorePool) GetStores() map[roachpb.StoreID]roachpb.StoreDescriptor {
sp.detailsMu.RLock()
defer sp.detailsMu.RUnlock()
stores := make(map[roachpb.StoreID]roachpb.StoreDescriptor, len(sp.detailsMu.storeDetails))
for _, s := range sp.detailsMu.storeDetails {
if s.desc != nil {
stores[s.desc.StoreID] = *s.desc
}
}
return stores
}
// getStoreDetailLocked returns the store detail for the given storeID.
// The lock must be held *in write mode* even though this looks like a
// read-only method.
func (sp *StorePool) getStoreDetailLocked(storeID roachpb.StoreID) *storeDetail {
detail, ok := sp.detailsMu.storeDetails[storeID]
if !ok {
// We don't have this store yet (this is normal when we're
// starting up and don't have full information from the gossip
// network). The first time this occurs, presume the store is
// alive, but start the clock so it will become dead if enough
// time passes without updates from gossip.
detail = newStoreDetail()
detail.lastUpdatedTime = sp.startTime
sp.detailsMu.storeDetails[storeID] = detail
}
return detail
}
// getStoreDescriptor returns the latest store descriptor for the given
// storeID.
func (sp *StorePool) getStoreDescriptor(storeID roachpb.StoreID) (roachpb.StoreDescriptor, bool) {
sp.detailsMu.RLock()
defer sp.detailsMu.RUnlock()
if detail, ok := sp.detailsMu.storeDetails[storeID]; ok && detail.desc != nil {
return *detail.desc, true
}
return roachpb.StoreDescriptor{}, false
}
// decommissioningReplicas filters out replicas on decommissioning node/store
// from the provided repls and returns them in a slice.
func (sp *StorePool) decommissioningReplicas(
rangeID roachpb.RangeID, repls []roachpb.ReplicaDescriptor,
) (decommissioningReplicas []roachpb.ReplicaDescriptor) {
sp.detailsMu.Lock()
defer sp.detailsMu.Unlock()
// NB: We use clock.Now().GoTime() instead of clock.PhysicalTime() is order to
// take clock signals from remote nodes into consideration.
now := sp.clock.Now().GoTime()
timeUntilStoreDead := TimeUntilStoreDead.Get(&sp.st.SV)
for _, repl := range repls {
detail := sp.getStoreDetailLocked(repl.StoreID)
switch detail.status(now, timeUntilStoreDead, rangeID, sp.nodeLivenessFn) {
case storeStatusDecommissioning:
decommissioningReplicas = append(decommissioningReplicas, repl)
}
}
return
}
// ClusterNodeCount returns the number of nodes that are possible allocation
// targets. This includes dead nodes, but not decommissioning or decommissioned
// nodes.
func (sp *StorePool) ClusterNodeCount() int {
return sp.nodeCountFn()
}
// liveAndDeadReplicas divides the provided repls slice into two slices: the
// first for live replicas, and the second for dead replicas.
// Replicas for which liveness or deadness cannot be ascertained are excluded
// from the returned slices. Replicas on decommissioning node/store are
// considered live.
func (sp *StorePool) liveAndDeadReplicas(
rangeID roachpb.RangeID, repls []roachpb.ReplicaDescriptor,
) (liveReplicas, deadReplicas []roachpb.ReplicaDescriptor) {
sp.detailsMu.Lock()
defer sp.detailsMu.Unlock()
now := sp.clock.Now().GoTime()
timeUntilStoreDead := TimeUntilStoreDead.Get(&sp.st.SV)
for _, repl := range repls {
detail := sp.getStoreDetailLocked(repl.StoreID)
// Mark replica as dead if store is dead.
status := detail.status(now, timeUntilStoreDead, rangeID, sp.nodeLivenessFn)
switch status {
case storeStatusDead:
deadReplicas = append(deadReplicas, repl)
case storeStatusAvailable, storeStatusThrottled, storeStatusDecommissioning:
// We count both available and throttled stores to be live for the
// purpose of computing quorum.
// We count decommissioning replicas to be alive because they are readable
// and should be used for up-replication if necessary.
liveReplicas = append(liveReplicas, repl)
case storeStatusUnknown:
// No-op.
default:
log.Fatalf(context.TODO(), "unknown store status %d", status)
}
}
return
}
// stat provides a running sample size and running stats.
type stat struct {
n, mean float64
}
// Update adds the specified value to the stat, augmenting the running stats.
func (s *stat) update(x float64) {
s.n++
s.mean += (x - s.mean) / s.n
}
// StoreList holds a list of store descriptors and associated count and used
// stats for those stores.
type StoreList struct {
stores []roachpb.StoreDescriptor
// candidateRanges tracks range count stats for stores that are eligible to
// be rebalance targets (their used capacity percentage must be lower than
// maxFractionUsedThreshold).
candidateRanges stat
// candidateLeases tracks range lease stats for stores that are eligible to
// be rebalance targets.
candidateLeases stat
// candidateLogicalBytes tracks disk usage stats for stores that are eligible
// to be rebalance targets.
candidateLogicalBytes stat
// candidateQueriesPerSecond tracks queries-per-second stats for stores that
// are eligible to be rebalance targets.
candidateQueriesPerSecond stat
// candidateWritesPerSecond tracks writes-per-second stats for stores that are
// eligible to be rebalance targets.
candidateWritesPerSecond stat
}
// Generates a new store list based on the passed in descriptors. It will
// maintain the order of those descriptors.
func makeStoreList(descriptors []roachpb.StoreDescriptor) StoreList {
sl := StoreList{stores: descriptors}
for _, desc := range descriptors {
if maxCapacityCheck(desc) {
sl.candidateRanges.update(float64(desc.Capacity.RangeCount))
}
sl.candidateLeases.update(float64(desc.Capacity.LeaseCount))
sl.candidateLogicalBytes.update(float64(desc.Capacity.LogicalBytes))
sl.candidateQueriesPerSecond.update(desc.Capacity.QueriesPerSecond)
sl.candidateWritesPerSecond.update(desc.Capacity.WritesPerSecond)
}
return sl
}
func (sl StoreList) String() string {
var buf bytes.Buffer
fmt.Fprintf(&buf,
" candidate: avg-ranges=%v avg-leases=%v avg-disk-usage=%v avg-queries-per-second=%v",
sl.candidateRanges.mean,
sl.candidateLeases.mean,
humanizeutil.IBytes(int64(sl.candidateLogicalBytes.mean)),
sl.candidateQueriesPerSecond.mean)
if len(sl.stores) > 0 {
fmt.Fprintf(&buf, "\n")
} else {
fmt.Fprintf(&buf, " <no candidates>")
}
for _, desc := range sl.stores {
fmt.Fprintf(&buf, " %d: ranges=%d leases=%d disk-usage=%s queries-per-second=%.2f\n",
desc.StoreID, desc.Capacity.RangeCount,
desc.Capacity.LeaseCount, humanizeutil.IBytes(desc.Capacity.LogicalBytes),
desc.Capacity.QueriesPerSecond)
}
return buf.String()
}
// filter takes a store list and filters it using the passed in constraints. It
// maintains the original order of the passed in store list.
func (sl StoreList) filter(constraints []zonepb.Constraints) StoreList {
if len(constraints) == 0 {
return sl
}
var filteredDescs []roachpb.StoreDescriptor
for _, store := range sl.stores {
if ok := constraintsCheck(store, constraints); ok {
filteredDescs = append(filteredDescs, store)
}
}
return makeStoreList(filteredDescs)
}
type storeFilter int
const (
_ storeFilter = iota
// storeFilterNone requests that the storeList include all live stores. Dead,
// unknown, and corrupted stores are always excluded from the storeList.
storeFilterNone
// storeFilterThrottled requests that the returned store list additionally
// exclude stores that have been throttled for declining a snapshot. (See
// storePool.throttle for details.) Throttled stores should not be considered
// for replica rebalancing, for example, but can still be considered for lease
// rebalancing.
storeFilterThrottled
)
type throttledStoreReasons []string
// getStoreList returns a storeList that contains all active stores that contain
// the required attributes and their associated stats. The storeList is filtered
// according to the provided storeFilter. It also returns the total number of
// alive and throttled stores. The passed in rangeID is used to check for
// corrupted replicas.
func (sp *StorePool) getStoreList(
rangeID roachpb.RangeID, filter storeFilter,
) (StoreList, int, throttledStoreReasons) {
sp.detailsMu.RLock()
defer sp.detailsMu.RUnlock()
var storeIDs roachpb.StoreIDSlice
for storeID := range sp.detailsMu.storeDetails {
storeIDs = append(storeIDs, storeID)
}
return sp.getStoreListFromIDsRLocked(storeIDs, rangeID, filter)
}
// getStoreListFromIDs is the same function as getStoreList but only returns stores
// from the subset of passed in store IDs.
func (sp *StorePool) getStoreListFromIDs(
storeIDs roachpb.StoreIDSlice, rangeID roachpb.RangeID, filter storeFilter,
) (StoreList, int, throttledStoreReasons) {
sp.detailsMu.RLock()
defer sp.detailsMu.RUnlock()
return sp.getStoreListFromIDsRLocked(storeIDs, rangeID, filter)
}
// getStoreListFromIDsRLocked is the same function as getStoreList but requires
// that the detailsMU read lock is held.
func (sp *StorePool) getStoreListFromIDsRLocked(
storeIDs roachpb.StoreIDSlice, rangeID roachpb.RangeID, filter storeFilter,
) (StoreList, int, throttledStoreReasons) {
if sp.deterministic {
sort.Sort(storeIDs)
} else {
shuffle.Shuffle(storeIDs)
}
var aliveStoreCount int
var throttled throttledStoreReasons
var storeDescriptors []roachpb.StoreDescriptor
now := sp.clock.Now().GoTime()
timeUntilStoreDead := TimeUntilStoreDead.Get(&sp.st.SV)
for _, storeID := range storeIDs {
detail, ok := sp.detailsMu.storeDetails[storeID]
if !ok {
// Do nothing; this store is not in the StorePool.
continue
}
switch s := detail.status(now, timeUntilStoreDead, rangeID, sp.nodeLivenessFn); s {
case storeStatusThrottled:
aliveStoreCount++
throttled = append(throttled, detail.throttledBecause)
if filter != storeFilterThrottled {
storeDescriptors = append(storeDescriptors, *detail.desc)
}
case storeStatusReplicaCorrupted:
aliveStoreCount++
case storeStatusAvailable:
aliveStoreCount++
storeDescriptors = append(storeDescriptors, *detail.desc)
case storeStatusDead, storeStatusUnknown, storeStatusDecommissioning:
// Do nothing; this store cannot be used.
default:
panic(fmt.Sprintf("unknown store status: %d", s))
}
}
return makeStoreList(storeDescriptors), aliveStoreCount, throttled
}
type throttleReason int
const (
_ throttleReason = iota
throttleDeclined
throttleFailed
)
// throttle informs the store pool that the given remote store declined a
// snapshot or failed to apply one, ensuring that it will not be considered
// for up-replication or rebalancing until after the configured timeout period
// has elapsed. Declined being true indicates that the remote store explicitly
// declined a snapshot.
func (sp *StorePool) throttle(reason throttleReason, why string, storeID roachpb.StoreID) {
sp.detailsMu.Lock()
defer sp.detailsMu.Unlock()
detail := sp.getStoreDetailLocked(storeID)
detail.throttledBecause = why
// If a snapshot is declined, be it due to an error or because it was
// rejected, we mark the store detail as having been declined so it won't
// be considered as a candidate for new replicas until after the configured
// timeout period has passed.
switch reason {
case throttleDeclined:
timeout := DeclinedReservationsTimeout.Get(&sp.st.SV)
detail.throttledUntil = sp.clock.PhysicalTime().Add(timeout)
if log.V(2) {
ctx := sp.AnnotateCtx(context.TODO())
log.Infof(ctx, "snapshot declined (%s), s%d will be throttled for %s until %s",
why, storeID, timeout, detail.throttledUntil)
}
case throttleFailed:
timeout := FailedReservationsTimeout.Get(&sp.st.SV)
detail.throttledUntil = sp.clock.PhysicalTime().Add(timeout)
if log.V(2) {
ctx := sp.AnnotateCtx(context.TODO())
log.Infof(ctx, "snapshot failed (%s), s%d will be throttled for %s until %s",
why, storeID, timeout, detail.throttledUntil)
}
}
}
// getLocalities returns the localities for the provided replicas.
// TODO(bram): consider storing a full list of all node to node diversity
// scores for faster lookups.
func (sp *StorePool) getLocalities(
replicas []roachpb.ReplicaDescriptor,
) map[roachpb.NodeID]roachpb.Locality {
sp.localitiesMu.RLock()
defer sp.localitiesMu.RUnlock()
localities := make(map[roachpb.NodeID]roachpb.Locality)
for _, replica := range replicas {
if locality, ok := sp.localitiesMu.nodeLocalities[replica.NodeID]; ok {
localities[replica.NodeID] = locality.locality
} else {
localities[replica.NodeID] = roachpb.Locality{}
}
}
return localities
}
// getNodeLocalityString returns the locality information for the given node
// in its string format.
func (sp *StorePool) getNodeLocalityString(nodeID roachpb.NodeID) string {
sp.localitiesMu.RLock()
defer sp.localitiesMu.RUnlock()
locality, ok := sp.localitiesMu.nodeLocalities[nodeID]
if !ok {
return ""
}
return locality.str
}