-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathstore.go
2514 lines (2252 loc) · 85.2 KB
/
store.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.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Spencer Kimball ([email protected])
package storage
import (
"bytes"
"fmt"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"github.com/gogo/protobuf/proto"
"github.com/google/btree"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/base"
"github.com/cockroachdb/cockroach/build"
"github.com/cockroachdb/cockroach/client"
"github.com/cockroachdb/cockroach/config"
"github.com/cockroachdb/cockroach/gossip"
"github.com/cockroachdb/cockroach/keys"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/cockroachdb/cockroach/sql/sqlutil"
"github.com/cockroachdb/cockroach/storage/engine"
"github.com/cockroachdb/cockroach/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/storage/storagebase"
"github.com/cockroachdb/cockroach/util"
"github.com/cockroachdb/cockroach/util/cache"
"github.com/cockroachdb/cockroach/util/envutil"
"github.com/cockroachdb/cockroach/util/hlc"
"github.com/cockroachdb/cockroach/util/log"
"github.com/cockroachdb/cockroach/util/metric"
"github.com/cockroachdb/cockroach/util/retry"
"github.com/cockroachdb/cockroach/util/stop"
"github.com/cockroachdb/cockroach/util/tracing"
"github.com/cockroachdb/cockroach/util/uuid"
)
const (
// rangeIDAllocCount is the number of Range IDs to allocate per allocation.
rangeIDAllocCount = 10
defaultHeartbeatIntervalTicks = 3
defaultRaftElectionTimeoutTicks = 15
defaultAsyncSnapshotMaxAge = time.Minute
// ttlStoreGossip is time-to-live for store-related info.
ttlStoreGossip = 2 * time.Minute
// TODO(bdarnell): Determine the right size for this cache. Should
// the cache be partitioned so that replica descriptors from the
// range descriptors (which are the bulk of the data and can be
// reloaded from disk as needed) don't crowd out the
// message/snapshot descriptors (whose necessity is short-lived but
// cannot be recovered through other means if evicted)?
maxReplicaDescCacheSize = 1000
raftReqBufferSize = 100
// leaderLeaseRaftElectionTimeoutMultiplier specifies what multiple the leader
// lease active duration should be of the raft election timeout.
leaderLeaseRaftElectionTimeoutMultiplier = 3
// leaderLeaseRenewalDivisor specifies what quotient the leader lease renewal
// duration should be of the leader lease active time.
leaderLeaseRenewalDivisor = 5
)
var changeTypeInternalToRaft = map[roachpb.ReplicaChangeType]raftpb.ConfChangeType{
roachpb.ADD_REPLICA: raftpb.ConfChangeAddNode,
roachpb.REMOVE_REPLICA: raftpb.ConfChangeRemoveNode,
}
var storeReplicaRaftReadyConcurrency = 2 * runtime.NumCPU()
// TestStoreContext has some fields initialized with values relevant
// in tests.
func TestStoreContext() StoreContext {
return StoreContext{
Tracer: tracing.NewTracer(),
RaftTickInterval: 100 * time.Millisecond,
RaftHeartbeatIntervalTicks: 1,
RaftElectionTimeoutTicks: 3,
ScanInterval: 10 * time.Minute,
ConsistencyCheckInterval: 10 * time.Minute,
ConsistencyCheckPanicOnFailure: true,
BlockingSnapshotDuration: 100 * time.Millisecond,
}
}
type semaphore chan struct{}
func makeSemaphore(n int) semaphore {
return make(semaphore, n)
}
func (s semaphore) acquire() {
s <- struct{}{}
}
func (s semaphore) release() {
<-s
}
// verifyKeys verifies keys. If checkEndKey is true, then the end key
// is verified to be non-nil and greater than start key. If
// checkEndKey is false, end key is verified to be nil. Additionally,
// verifies that start key is less than KeyMax and end key is less
// than or equal to KeyMax. It also verifies that a key range that
// contains range-local keys is completely range-local.
func verifyKeys(start, end roachpb.Key, checkEndKey bool) error {
if bytes.Compare(start, roachpb.KeyMax) >= 0 {
return errors.Errorf("start key %q must be less than KeyMax", start)
}
if !checkEndKey {
if len(end) != 0 {
return errors.Errorf("end key %q should not be specified for this operation", end)
}
return nil
}
if end == nil {
return errors.Errorf("end key must be specified")
}
if bytes.Compare(roachpb.KeyMax, end) < 0 {
return errors.Errorf("end key %q must be less than or equal to KeyMax", end)
}
{
sAddr, err := keys.Addr(start)
if err != nil {
return err
}
eAddr, err := keys.Addr(end)
if err != nil {
return err
}
if !sAddr.Less(eAddr) {
return errors.Errorf("end key %q must be greater than start %q", end, start)
}
if !bytes.Equal(sAddr, start) {
if bytes.Equal(eAddr, end) {
return errors.Errorf("start key is range-local, but end key is not")
}
} else if bytes.Compare(start, keys.LocalMax) < 0 {
// It's a range op, not local but somehow plows through local data -
// not cool.
return errors.Errorf("start key in [%q,%q) must be greater than LocalMax", start, end)
}
}
return nil
}
type rangeAlreadyExists struct {
rng *Replica
}
// Error implements the error interface.
func (e rangeAlreadyExists) Error() string {
return fmt.Sprintf("range for Range ID %d already exists on store", e.rng.RangeID)
}
// rangeKeyItem is a common interface for roachpb.Key and Range.
type rangeKeyItem interface {
getKey() roachpb.RKey
}
// rangeBTreeKey is a type alias of roachpb.RKey that implements the
// rangeKeyItem interface and the btree.Item interface.
type rangeBTreeKey roachpb.RKey
var _ rangeKeyItem = rangeBTreeKey{}
func (k rangeBTreeKey) getKey() roachpb.RKey {
return (roachpb.RKey)(k)
}
var _ btree.Item = rangeBTreeKey{}
func (k rangeBTreeKey) Less(i btree.Item) bool {
return k.getKey().Less(i.(rangeKeyItem).getKey())
}
var _ rangeKeyItem = &Replica{}
func (r *Replica) getKey() roachpb.RKey {
return r.Desc().EndKey
}
var _ btree.Item = &Replica{}
// Less returns true if the range's end key is less than the given item's key.
func (r *Replica) Less(i btree.Item) bool {
return r.getKey().Less(i.(rangeKeyItem).getKey())
}
// A NotBootstrappedError indicates that an engine has not yet been
// bootstrapped due to a store identifier not being present.
type NotBootstrappedError struct{}
// Error formats error.
func (e *NotBootstrappedError) Error() string {
return "store has not been bootstrapped"
}
// storeRangeSet is an implementation of rangeSet which
// cycles through a store's rangesByKey btree.
type storeRangeSet struct {
store *Store
rangeIDs []roachpb.RangeID // Range IDs of ranges to be visited.
visited int // Number of visited ranges. -1 when Visit() is not being called.
}
func newStoreRangeSet(store *Store) *storeRangeSet {
return &storeRangeSet{
store: store,
visited: 0,
}
}
// Visit calls the visitor with each Replica until false is returned.
func (rs *storeRangeSet) Visit(visitor func(*Replica) bool) {
// Copy the range IDs to a slice and iterate over the slice so
// that we can safely (e.g., no race, no range skip) iterate
// over ranges regardless of how BTree is implemented.
rs.store.mu.Lock()
rs.rangeIDs = make([]roachpb.RangeID, rs.store.mu.replicasByKey.Len())
i := 0
rs.store.mu.replicasByKey.Ascend(func(item btree.Item) bool {
rs.rangeIDs[i] = item.(*Replica).RangeID
i++
return true
})
rs.store.mu.Unlock()
rs.visited = 0
for _, rangeID := range rs.rangeIDs {
rs.visited++
rs.store.mu.Lock()
rng, ok := rs.store.mu.replicas[rangeID]
rs.store.mu.Unlock()
if ok {
if !visitor(rng) {
break
}
}
}
rs.visited = 0
}
func (rs *storeRangeSet) EstimatedCount() int {
rs.store.mu.Lock()
defer rs.store.mu.Unlock()
if rs.visited <= 0 {
return rs.store.mu.replicasByKey.Len()
}
return len(rs.rangeIDs) - rs.visited
}
type replicaDescCacheKey struct {
groupID roachpb.RangeID
replicaID roachpb.ReplicaID
}
// A Store maintains a map of ranges by start key. A Store corresponds
// to one physical device.
type Store struct {
Ident roachpb.StoreIdent
ctx StoreContext
db *client.DB
engine engine.Engine // The underlying key-value store
allocator Allocator // Makes allocation decisions
rangeIDAlloc *idAllocator // Range ID allocator
gcQueue *gcQueue // Garbage collection queue
splitQueue *splitQueue // Range splitting queue
verifyQueue *verifyQueue // Checksum verification queue
replicateQueue *replicateQueue // Replication queue
replicaGCQueue *replicaGCQueue // Replica GC queue
raftLogQueue *raftLogQueue // Raft Log Truncation queue
scanner *replicaScanner // Replica scanner
replicaConsistencyQueue *replicaConsistencyQueue // Replica consistency check queue
consistencyScanner *replicaScanner // Consistency checker scanner
metrics *storeMetrics
intentResolver *intentResolver
wakeRaftLoop chan struct{}
started int32
stopper *stop.Stopper
startedAt int64
nodeDesc *roachpb.NodeDescriptor
initComplete sync.WaitGroup // Signaled by async init tasks
raftRequestChan chan *RaftMessageRequest
bookie *bookie
// This is 1 if there is an active raft snapshot. This field must be checked
// and set atomically.
// TODO(marc): This may be better inside of `mu`, but is not currently feasible.
hasActiveRaftSnapshot int32
// drainLeadership holds a bool which indicates whether Replicas should be
// allowed to acquire or extend leader leases; see DrainLeadership().
//
// TODO(bdarnell,tschottdorf): Would look better inside of `mu`. However,
// deadlocks loom: For example, `systemGossipUpdate` holds `s.mu` while
// iterating over `s.mu.replicas` and, still under `s.mu`, calls `r.Desc()`
// but that needs the replica Mutex which may be held by a Replica while
// calling out to r.store.IsDrainingLeadership` (so it would deadlock if
// that required `s.mu` as well).
drainLeadership atomic.Value
// Locking notes: To avoid deadlocks, the following lock order
// must be obeyed: processRaftMu < Store.mu.Mutex <
// Replica.mu.Mutex < Store.pendingRaftGroups.Mutex.
//
// Methods of Store with a "Locked" suffix require that
// Store.mu.Mutex be held. Other locking requirements are indicated
// in comments.
// processRaftMu is held while doing anything raft-related.
// TODO(bdarnell): replace processRaftMu with a range-level lock.
processRaftMu sync.Mutex
mu struct {
sync.Mutex // Protects all variables in the mu struct.
replicas map[roachpb.RangeID]*Replica // Map of replicas by Range ID
replicasByKey *btree.BTree // btree keyed by ranges end keys.
uninitReplicas map[roachpb.RangeID]*Replica // Map of uninitialized replicas by Range ID
replicaDescCache *cache.UnorderedCache
}
// pendingRaftGroups contains the ranges that should be checked for
// updates. After updating this map, write to wakeRaftLoop to
// trigger the check.
pendingRaftGroups struct {
sync.Mutex
value map[roachpb.RangeID]struct{}
}
}
var _ client.Sender = &Store{}
// A StoreContext encompasses the auxiliary objects and configuration
// required to create a store.
// All fields holding a pointer or an interface are required to create
// a store; the rest will have sane defaults set if omitted.
type StoreContext struct {
Clock *hlc.Clock
DB *client.DB
Gossip *gossip.Gossip
StorePool *StorePool
Transport *RaftTransport
// SQLExecutor is used by the store to execute SQL statements in a way that
// is more direct than using a sql.Executor.
SQLExecutor sqlutil.InternalExecutor
// RangeRetryOptions are the retry options when retryable errors are
// encountered sending commands to ranges.
RangeRetryOptions retry.Options
// RaftTickInterval is the resolution of the Raft timer; other raft timeouts
// are defined in terms of multiples of this value.
RaftTickInterval time.Duration
// RaftHeartbeatIntervalTicks is the number of ticks that pass between heartbeats.
RaftHeartbeatIntervalTicks int
// RaftElectionTimeoutTicks is the number of ticks that must pass before a follower
// considers a leader to have failed and calls a new election. Should be significantly
// higher than RaftHeartbeatIntervalTicks. The raft paper recommends a value of 150ms
// for local networks.
RaftElectionTimeoutTicks int
// ScanInterval is the default value for the scan interval
ScanInterval time.Duration
// ScanMaxIdleTime is the maximum time the scanner will be idle between ranges.
// If enabled (> 0), the scanner may complete in less than ScanInterval for small
// stores.
ScanMaxIdleTime time.Duration
// ConsistencyCheckInterval is the default time period in between consecutive
// consistency checks on a range.
ConsistencyCheckInterval time.Duration
// ConsistencyCheckPanicOnFailure causes the node to panic when it detects a
// replication consistency check failure.
ConsistencyCheckPanicOnFailure bool
// AllocatorOptions configures how the store will attempt to rebalance its
// replicas to other stores.
AllocatorOptions AllocatorOptions
// Tracer is a request tracer.
Tracer opentracing.Tracer
// If LogRangeEvents is true, major changes to ranges will be logged into
// the range event log.
LogRangeEvents bool
// BlockingSnapshotDuration is the amount of time Replica.Snapshot
// will wait before switching to asynchronous mode. Zero is a good
// choice for production but non-zero values can speed up tests.
// (This only blocks on the first attempt; it will not block a
// second time if the generation is still in progress).
BlockingSnapshotDuration time.Duration
// AsyncSnapshotMaxAge is the maximum amount of time that an
// asynchronous snapshot will be held while waiting for raft to pick
// it up (counted from when the snapshot generation is completed).
AsyncSnapshotMaxAge time.Duration
TestingKnobs StoreTestingKnobs
// leaderLeaseActiveDuration is the duration of the active period of leader
// leases requested.
leaderLeaseActiveDuration time.Duration
// leaderLeaseRenewalDuration specifies a time interval at the end of the
// active lease interval (i.e. bounded to the right by the start of the stasis
// period) during which operations will trigger an asynchronous renewal of the
// lease.
leaderLeaseRenewalDuration time.Duration
}
// StoreTestingKnobs is a part of the context used to control parts of the system.
type StoreTestingKnobs struct {
// A callback to be called when executing every replica command.
// If your filter is not idempotent, consider wrapping it in a
// ReplayProtectionFilterWrapper.
TestingCommandFilter storagebase.ReplicaCommandFilter
// A callback to be called instead of panicking due to a
// checksum mismatch in VerifyChecksum()
BadChecksumPanic func([]ReplicaSnapshotDiff)
// Disables the use of one phase commits.
DisableOnePhaseCommits bool
// A hack to manipulate the clock before sending a batch request to a replica.
// TODO(kaneda): This hook is not encouraged to use. Get rid of it once
// we make TestServer take a ManualClock.
ClockBeforeSend func(*hlc.Clock, roachpb.BatchRequest)
}
var _ base.ModuleTestingKnobs = &StoreTestingKnobs{}
// ModuleTestingKnobs is part of the base.ModuleTestingKnobs interface.
func (*StoreTestingKnobs) ModuleTestingKnobs() {}
type storeMetrics struct {
registry *metric.Registry
// Range data metrics.
replicaCount *metric.Counter // Does not include reserved replicas.
reservedReplicaCount *metric.Counter
leaderRangeCount *metric.Gauge
replicatedRangeCount *metric.Gauge
availableRangeCount *metric.Gauge
// Lease data metrics.
leaseRequestSuccessCount *metric.Counter
leaseRequestErrorCount *metric.Counter
// Storage metrics.
liveBytes *metric.Gauge
keyBytes *metric.Gauge
valBytes *metric.Gauge
intentBytes *metric.Gauge
liveCount *metric.Gauge
keyCount *metric.Gauge
valCount *metric.Gauge
intentCount *metric.Gauge
intentAge *metric.Gauge
gcBytesAge *metric.Gauge
lastUpdateNanos *metric.Gauge
capacity *metric.Gauge
available *metric.Gauge
reserved *metric.Counter
sysBytes *metric.Gauge
sysCount *metric.Gauge
// RocksDB metrics.
rdbBlockCacheHits *metric.Gauge
rdbBlockCacheMisses *metric.Gauge
rdbBlockCacheUsage *metric.Gauge
rdbBlockCachePinnedUsage *metric.Gauge
rdbBloomFilterPrefixChecked *metric.Gauge
rdbBloomFilterPrefixUseful *metric.Gauge
rdbMemtableHits *metric.Gauge
rdbMemtableMisses *metric.Gauge
rdbMemtableTotalSize *metric.Gauge
rdbFlushes *metric.Gauge
rdbCompactions *metric.Gauge
rdbTableReadersMemEstimate *metric.Gauge
// Range event metrics.
rangeSplits *metric.Counter
rangeAdds *metric.Counter
rangeRemoves *metric.Counter
// Stats for efficient merges.
// TODO(mrtracy): This should be removed as part of #4465. This is only
// maintained to keep the current structure of StatusSummaries; it would be
// better to convert the Gauges above into counters which are adjusted
// accordingly.
mu sync.Mutex
stats enginepb.MVCCStats
}
func newStoreMetrics() *storeMetrics {
storeRegistry := metric.NewRegistry()
return &storeMetrics{
registry: storeRegistry,
replicaCount: storeRegistry.Counter("replicas"),
reservedReplicaCount: storeRegistry.Counter("replicas.reserved"),
leaderRangeCount: storeRegistry.Gauge("ranges.leader"),
replicatedRangeCount: storeRegistry.Gauge("ranges.replicated"),
availableRangeCount: storeRegistry.Gauge("ranges.available"),
leaseRequestSuccessCount: storeRegistry.Counter("leases.success"),
leaseRequestErrorCount: storeRegistry.Counter("leases.error"),
liveBytes: storeRegistry.Gauge("livebytes"),
keyBytes: storeRegistry.Gauge("keybytes"),
valBytes: storeRegistry.Gauge("valbytes"),
intentBytes: storeRegistry.Gauge("intentbytes"),
liveCount: storeRegistry.Gauge("livecount"),
keyCount: storeRegistry.Gauge("keycount"),
valCount: storeRegistry.Gauge("valcount"),
intentCount: storeRegistry.Gauge("intentcount"),
intentAge: storeRegistry.Gauge("intentage"),
gcBytesAge: storeRegistry.Gauge("gcbytesage"),
lastUpdateNanos: storeRegistry.Gauge("lastupdatenanos"),
capacity: storeRegistry.Gauge("capacity"),
available: storeRegistry.Gauge("capacity.available"),
reserved: storeRegistry.Counter("capacity.reserved"),
sysBytes: storeRegistry.Gauge("sysbytes"),
sysCount: storeRegistry.Gauge("syscount"),
// RocksDB metrics.
rdbBlockCacheHits: storeRegistry.Gauge("rocksdb.block.cache.hits"),
rdbBlockCacheMisses: storeRegistry.Gauge("rocksdb.block.cache.misses"),
rdbBlockCacheUsage: storeRegistry.Gauge("rocksdb.block.cache.usage"),
rdbBlockCachePinnedUsage: storeRegistry.Gauge("rocksdb.block.cache.pinned-usage"),
rdbBloomFilterPrefixChecked: storeRegistry.Gauge("rocksdb.bloom.filter.prefix.checked"),
rdbBloomFilterPrefixUseful: storeRegistry.Gauge("rocksdb.bloom.filter.prefix.useful"),
rdbMemtableHits: storeRegistry.Gauge("rocksdb.memtable.hits"),
rdbMemtableMisses: storeRegistry.Gauge("rocksdb.memtable.misses"),
rdbMemtableTotalSize: storeRegistry.Gauge("rocksdb.memtable.total-size"),
rdbFlushes: storeRegistry.Gauge("rocksdb.flushes"),
rdbCompactions: storeRegistry.Gauge("rocksdb.compactions"),
rdbTableReadersMemEstimate: storeRegistry.Gauge("rocksdb.table-readers-mem-estimate"),
// Range event metrics.
rangeSplits: storeRegistry.Counter("range.splits"),
rangeAdds: storeRegistry.Counter("range.adds"),
rangeRemoves: storeRegistry.Counter("range.removes"),
}
}
// updateGaugesLocked breaks out individual metrics from the MVCCStats object.
// This process should be locked with each stat application to ensure that all
// gauges increase/decrease in step with the application of updates. However,
// this locking is not exposed to the registry level, and therefore a single
// snapshot of these gauges in the registry might mix the values of two
// subsequent updates.
func (sm *storeMetrics) updateMVCCGaugesLocked() {
sm.liveBytes.Update(sm.stats.LiveBytes)
sm.keyBytes.Update(sm.stats.KeyBytes)
sm.valBytes.Update(sm.stats.ValBytes)
sm.intentBytes.Update(sm.stats.IntentBytes)
sm.liveCount.Update(sm.stats.LiveCount)
sm.keyCount.Update(sm.stats.KeyCount)
sm.valCount.Update(sm.stats.ValCount)
sm.intentCount.Update(sm.stats.IntentCount)
sm.intentAge.Update(sm.stats.IntentAge)
sm.gcBytesAge.Update(sm.stats.GCBytesAge)
sm.lastUpdateNanos.Update(sm.stats.LastUpdateNanos)
sm.sysBytes.Update(sm.stats.SysBytes)
sm.sysCount.Update(sm.stats.SysCount)
}
func (sm *storeMetrics) updateCapacityGauges(capacity roachpb.StoreCapacity) {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.capacity.Update(capacity.Capacity)
sm.available.Update(capacity.Available)
}
func (sm *storeMetrics) updateReplicationGauges(leaders, replicated, available int64) {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.leaderRangeCount.Update(leaders)
sm.replicatedRangeCount.Update(replicated)
sm.availableRangeCount.Update(available)
}
func (sm *storeMetrics) addMVCCStats(stats enginepb.MVCCStats) {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.stats.Add(stats)
sm.updateMVCCGaugesLocked()
}
func (sm *storeMetrics) subtractMVCCStats(stats enginepb.MVCCStats) {
sm.mu.Lock()
defer sm.mu.Unlock()
sm.stats.Subtract(stats)
sm.updateMVCCGaugesLocked()
}
func (sm *storeMetrics) updateRocksDBStats(stats engine.Stats) {
// We do not grab a lock here, because it's not possible to get a point-in-
// time snapshot of RocksDB stats. Retrieving RocksDB stats doesn't grab any
// locks, and there's no way to retrieve multiple stats in a single operation.
sm.rdbBlockCacheHits.Update(int64(stats.BlockCacheHits))
sm.rdbBlockCacheMisses.Update(int64(stats.BlockCacheMisses))
sm.rdbBlockCacheUsage.Update(int64(stats.BlockCacheUsage))
sm.rdbBlockCachePinnedUsage.Update(int64(stats.BlockCachePinnedUsage))
sm.rdbBloomFilterPrefixUseful.Update(int64(stats.BloomFilterPrefixUseful))
sm.rdbBloomFilterPrefixChecked.Update(int64(stats.BloomFilterPrefixChecked))
sm.rdbMemtableHits.Update(int64(stats.MemtableHits))
sm.rdbMemtableMisses.Update(int64(stats.MemtableMisses))
sm.rdbMemtableTotalSize.Update(int64(stats.MemtableTotalSize))
sm.rdbFlushes.Update(int64(stats.Flushes))
sm.rdbCompactions.Update(int64(stats.Compactions))
sm.rdbTableReadersMemEstimate.Update(int64(stats.TableReadersMemEstimate))
}
func (sm *storeMetrics) leaseRequestComplete(err error) {
if err == nil {
sm.leaseRequestSuccessCount.Inc(1)
} else {
sm.leaseRequestErrorCount.Inc(1)
}
}
// Valid returns true if the StoreContext is populated correctly.
// We don't check for Gossip and DB since some of our tests pass
// that as nil.
func (sc *StoreContext) Valid() bool {
return sc.Clock != nil && sc.Transport != nil &&
sc.RaftTickInterval != 0 && sc.RaftHeartbeatIntervalTicks > 0 &&
sc.RaftElectionTimeoutTicks > 0 && sc.ScanInterval > 0 &&
sc.ConsistencyCheckInterval > 0 && sc.Tracer != nil
}
// setDefaults initializes unset fields in StoreConfig to values
// suitable for use on a local network.
// TODO(tschottdorf) see if this ought to be configurable via flags.
func (sc *StoreContext) setDefaults() {
sc.RangeRetryOptions = base.DefaultRetryOptions()
if sc.RaftTickInterval == 0 {
sc.RaftTickInterval = base.DefaultRaftTickInterval
}
if sc.RaftHeartbeatIntervalTicks == 0 {
sc.RaftHeartbeatIntervalTicks = defaultHeartbeatIntervalTicks
}
if sc.RaftElectionTimeoutTicks == 0 {
sc.RaftElectionTimeoutTicks = defaultRaftElectionTimeoutTicks
}
if sc.AsyncSnapshotMaxAge == 0 {
sc.AsyncSnapshotMaxAge = defaultAsyncSnapshotMaxAge
}
raftElectionTimeout := time.Duration(sc.RaftElectionTimeoutTicks) * sc.RaftTickInterval
sc.leaderLeaseActiveDuration = leaderLeaseRaftElectionTimeoutMultiplier * raftElectionTimeout
sc.leaderLeaseRenewalDuration = sc.leaderLeaseActiveDuration / leaderLeaseRenewalDivisor
}
// NewStore returns a new instance of a store.
func NewStore(ctx StoreContext, eng engine.Engine, nodeDesc *roachpb.NodeDescriptor) *Store {
// TODO(tschottdorf) find better place to set these defaults.
ctx.setDefaults()
if !ctx.Valid() {
panic(fmt.Sprintf("invalid store configuration: %+v", &ctx))
}
s := &Store{
ctx: ctx,
db: ctx.DB, // TODO(tschottdorf) remove redundancy.
engine: eng,
allocator: MakeAllocator(ctx.StorePool, ctx.AllocatorOptions),
nodeDesc: nodeDesc,
wakeRaftLoop: make(chan struct{}, 1),
raftRequestChan: make(chan *RaftMessageRequest, raftReqBufferSize),
metrics: newStoreMetrics(),
}
s.intentResolver = newIntentResolver(s)
s.drainLeadership.Store(false)
s.mu.Lock()
s.mu.replicas = map[roachpb.RangeID]*Replica{}
s.mu.replicasByKey = btree.New(64 /* degree */)
s.mu.uninitReplicas = map[roachpb.RangeID]*Replica{}
s.mu.replicaDescCache = cache.NewUnorderedCache(cache.Config{
Policy: cache.CacheLRU,
ShouldEvict: func(size int, _, _ interface{}) bool {
return size > maxReplicaDescCacheSize
},
})
s.pendingRaftGroups.value = map[roachpb.RangeID]struct{}{}
s.mu.Unlock()
if s.ctx.Gossip != nil {
// Add range scanner and configure with queues.
s.scanner = newReplicaScanner(ctx.ScanInterval, ctx.ScanMaxIdleTime, newStoreRangeSet(s))
s.gcQueue = newGCQueue(s.ctx.Gossip)
s.splitQueue = newSplitQueue(s.db, s.ctx.Gossip)
s.verifyQueue = newVerifyQueue(s.ctx.Gossip, s.ReplicaCount)
s.replicateQueue = newReplicateQueue(s.ctx.Gossip, s.allocator, s.ctx.Clock, s.ctx.AllocatorOptions)
s.replicaGCQueue = newReplicaGCQueue(s.db, s.ctx.Gossip)
s.raftLogQueue = newRaftLogQueue(s.db, s.ctx.Gossip)
s.scanner.AddQueues(s.gcQueue, s.splitQueue, s.verifyQueue, s.replicateQueue, s.replicaGCQueue, s.raftLogQueue)
// Add consistency check scanner.
s.consistencyScanner = newReplicaScanner(ctx.ConsistencyCheckInterval, 0, newStoreRangeSet(s))
s.replicaConsistencyQueue = newReplicaConsistencyQueue(s.ctx.Gossip)
s.consistencyScanner.AddQueues(s.replicaConsistencyQueue)
}
return s
}
// String formats a store for debug output.
func (s *Store) String() string {
return fmt.Sprintf("store=%d:%d (%s)", s.Ident.NodeID, s.Ident.StoreID, s.engine)
}
// DrainLeadership (when called with 'true') prevents all of the Store's
// Replicas from acquiring or extending leader leases and waits until all of
// them have expired. If an error is returned, the draining state is still
// active, but there may be active leases held by some of the Store's Replicas.
// When called with 'false', returns to the normal mode of operation.
func (s *Store) DrainLeadership(drain bool) error {
s.drainLeadership.Store(drain)
if !drain {
return nil
}
return util.RetryForDuration(10*s.ctx.leaderLeaseActiveDuration, func() error {
var err error
now := s.Clock().Now()
newStoreRangeSet(s).Visit(func(r *Replica) bool {
lease, nextLease := r.getLeaderLease()
// If we own an active lease or we're trying to obtain a lease
// (and that request is fresh enough), wait.
if (lease.OwnedBy(s.StoreID()) && lease.Covers(now)) ||
(nextLease != nil && nextLease.Covers(now)) {
err = fmt.Errorf("replica %s still has an active lease", r)
}
return err == nil // break on error
})
return err
})
}
// context returns a base context to pass along with commands being executed,
// derived from the supplied context (which is not allowed to be nil).
func (s *Store) context(ctx context.Context) context.Context {
if ctx == nil {
panic("ctx cannot be nil")
}
return log.Add(ctx,
log.NodeID, s.Ident.NodeID,
log.StoreID, s.Ident.StoreID)
}
// IsStarted returns true if the Store has been started.
func (s *Store) IsStarted() bool {
return atomic.LoadInt32(&s.started) == 1
}
// IterateRangeDescriptors calls the provided function with each descriptor
// from the provided Engine. The return values of this method and fn have
// semantics similar to engine.MVCCIterate.
func IterateRangeDescriptors(
eng engine.Reader, fn func(desc roachpb.RangeDescriptor) (bool, error),
) error {
// Iterator over all range-local key-based data.
start := keys.RangeDescriptorKey(roachpb.RKeyMin)
end := keys.RangeDescriptorKey(roachpb.RKeyMax)
kvToDesc := func(kv roachpb.KeyValue) (bool, error) {
// Only consider range metadata entries; ignore others.
_, suffix, _, err := keys.DecodeRangeKey(kv.Key)
if err != nil {
return false, err
}
if !bytes.Equal(suffix, keys.LocalRangeDescriptorSuffix) {
return false, nil
}
var desc roachpb.RangeDescriptor
if err := kv.Value.GetProto(&desc); err != nil {
return false, err
}
return fn(desc)
}
_, err := engine.MVCCIterate(context.Background(), eng, start, end, hlc.MaxTimestamp, false /* !consistent */, nil, /* txn */
false /* !reverse */, kvToDesc)
return err
}
// MIGRATION(tschottdorf): As of #7310, we make sure that a Replica
// always has a complete Raft state on disk. Prior versions may not
// have that, which causes issues due to the fact that we used to
// synthesize a TruncatedState and do so no more. To make up for
// that, write a missing TruncatedState here. That key is in the
// replicated state, but since during a cluster upgrade, all nodes
// do it, it's fine (and we never CPut on that key, so anything in
// the Raft pipeline will simply overwrite it).
//
// TODO(tschottdorf): test this method.
func (s *Store) migrate7310(desc roachpb.RangeDescriptor) {
if !desc.IsInitialized() {
log.Fatalf("found uninitialized descriptor on range: %+v", desc)
}
batch := s.engine.NewBatch()
state, err := loadState(batch, &desc)
if err != nil {
log.Fatalf("could not migrate truncated state: %s", err)
}
if (*state.TruncatedState != roachpb.RaftTruncatedState{}) {
return
}
state.TruncatedState.Term = raftInitialLogTerm
state.TruncatedState.Index = raftInitialLogIndex
if _, err := saveState(batch, state); err != nil {
log.Fatalf("could not migrate truncated state: %s", err)
}
if err := batch.Commit(); err != nil {
log.Fatalf("could not migrate truncated state: %s", err)
}
log.Warningf("migration: synthesized truncated state for %+v", desc)
}
// Start the engine, set the GC and read the StoreIdent.
func (s *Store) Start(stopper *stop.Stopper) error {
s.stopper = stopper
// Add a closer for the various scanner queues, needed to properly clean up
// the event logs.
s.stopper.AddCloser(stop.CloserFn(func() {
if q := s.gcQueue; q != nil {
q.Close()
}
if q := s.splitQueue; q != nil {
q.Close()
}
if q := s.verifyQueue; q != nil {
q.Close()
}
if q := s.replicateQueue; q != nil {
q.Close()
}
if q := s.replicaGCQueue; q != nil {
q.Close()
}
if q := s.raftLogQueue; q != nil {
q.Close()
}
if q := s.replicaConsistencyQueue; q != nil {
q.Close()
}
}))
// Add the bookie to the store.
s.bookie = newBookie(
s.ctx.Clock,
s.stopper,
s.metrics,
envutil.EnvOrDefaultDuration("reservation_timeout", ttlStoreGossip),
)
if s.Ident.NodeID == 0 {
// Open engine (i.e. initialize RocksDB database). "NodeID != 0"
// implies the engine has already been opened.
if err := s.engine.Open(); err != nil {
return err
}
// Read store ident and return a not-bootstrapped error if necessary.
ok, err := engine.MVCCGetProto(context.Background(), s.engine, keys.StoreIdentKey(), hlc.ZeroTimestamp, true, nil, &s.Ident)
if err != nil {
return err
} else if !ok {
return &NotBootstrappedError{}
}
}
// If the nodeID is 0, it has not be assigned yet.
if s.nodeDesc.NodeID != 0 && s.Ident.NodeID != s.nodeDesc.NodeID {
return errors.Errorf("node id:%d does not equal the one in node descriptor:%d", s.Ident.NodeID, s.nodeDesc.NodeID)
}
// Always set gossip NodeID before gossiping any info.
if s.ctx.Gossip != nil {
s.ctx.Gossip.SetNodeID(s.Ident.NodeID)
}
// Create ID allocators.
idAlloc, err := newIDAllocator(keys.RangeIDGenerator, s.db, 2 /* min ID */, rangeIDAllocCount, s.stopper)
if err != nil {
return err
}
s.rangeIDAlloc = idAlloc
now := s.ctx.Clock.Now()
s.startedAt = now.WallTime
// Iterate over all range descriptors, ignoring uncommitted versions
// (consistent=false). Uncommitted intents which have been abandoned
// due to a split crashing halfway will simply be resolved on the
// next split attempt. They can otherwise be ignored.
s.mu.Lock()
err = IterateRangeDescriptors(s.engine, func(desc roachpb.RangeDescriptor) (bool, error) {
if _, repDesc := desc.FindReplica(s.StoreID()); repDesc == nil {
// We are no longer a member of the range, but we didn't GC
// the replica before shutting down. Destroy the replica now
// to avoid creating a new replica without a valid replica ID
// (which is necessary to have a non-nil raft group)
return false, s.destroyReplicaData(&desc)
}
s.migrate7310(desc)
rng, err := NewReplica(&desc, s, 0)
if err != nil {
return false, err
}
if err = s.addReplicaInternalLocked(rng); err != nil {
return false, err
}
// Add this range and its stats to our counter.
s.metrics.replicaCount.Inc(1)
s.metrics.addMVCCStats(rng.GetMVCCStats())
// TODO(bdarnell): lazily create raft groups to make the following comment true again.
// Note that we do not create raft groups at this time; they will be created
// on-demand the first time they are needed. This helps reduce the amount of
// election-related traffic in a cold start.
// Raft initialization occurs when we propose a command on this range or
// receive a raft message addressed to it.
// TODO(bdarnell): Also initialize raft groups when read leases are needed.
// TODO(bdarnell): Scan all ranges at startup for unapplied log entries
// and initialize those groups.
return false, nil
})
s.mu.Unlock()
if err != nil {
return err
}
// Start Raft processing goroutines.
s.ctx.Transport.Listen(s.StoreID(), s.enqueueRaftMessage)
s.processRaft()
doneUnfreezing := make(chan struct{})
if s.stopper.RunAsyncTask(func() {
defer close(doneUnfreezing)
sem := make(chan struct{}, 512)
var wg sync.WaitGroup // wait for unfreeze goroutines
var unfrozen int64 // updated atomically
newStoreRangeSet(s).Visit(func(r *Replica) bool {
r.mu.Lock()
frozen := r.mu.state.Frozen
r.mu.Unlock()
if !frozen {
return true
}
wg.Add(1)
if s.stopper.RunLimitedAsyncTask(sem, func() {
defer wg.Done()
desc := r.Desc()
var ba roachpb.BatchRequest
fReq := roachpb.ChangeFrozenRequest{
Span: roachpb.Span{
Key: desc.StartKey.AsRawKey(),
EndKey: desc.EndKey.AsRawKey(),
},
Frozen: false,
MustVersion: build.GetInfo().Tag,
}
ba.Add(&fReq)
if _, pErr := r.Send(context.TODO(), ba); pErr != nil {