-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
replica.go
4051 lines (3710 loc) · 142 KB
/
replica.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])
// Author: Jiang-Ming Yang ([email protected])
// Author: Tobias Schottdorf ([email protected])
// Author: Bram Gruneir ([email protected])
package storage
import (
"bytes"
"fmt"
"math"
"math/rand"
"reflect"
"sort"
"sync/atomic"
"time"
"unsafe"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"github.com/google/btree"
"github.com/kr/pretty"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/storagebase"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
const (
// sentinelGossipTTL is time-to-live for the gossip sentinel. The
// sentinel informs a node whether or not it's connected to the
// primary gossip network and not just a partition. As such it must
// expire on a reasonable basis and be continually re-gossiped. The
// replica which is the lease holder of the first range gossips it.
sentinelGossipTTL = 2 * time.Minute
// sentinelGossipInterval is the approximate interval at which the
// sentinel info is gossiped.
sentinelGossipInterval = sentinelGossipTTL / 2
// configGossipTTL is the time-to-live for configuration maps.
configGossipTTL = 0 // does not expire
// configGossipInterval is the interval at which range lease holders gossip
// their config maps. Even if config maps do not expire, we still
// need a periodic gossip to safeguard against failure of a lease holder
// to gossip after performing an update to the map.
configGossipInterval = 1 * time.Minute
// optimizePutThreshold is the minimum length of a contiguous run
// of batched puts or conditional puts, after which the constituent
// put operations will possibly be optimized by determining whether
// the key space being written is starting out empty.
optimizePutThreshold = 10
replicaChangeTxnName = "change-replica"
defaultReplicaRaftMuWarnThreshold = 500 * time.Millisecond
defaultReplicaMuWarnThreshold = 500 * time.Millisecond
)
// This flag controls whether Transaction entries are automatically gc'ed
// upon EndTransaction if they only have local intents (which can be
// resolved synchronously with EndTransaction). Certain tests become
// simpler with this being turned off.
var txnAutoGC = true
var tickQuiesced = envutil.EnvOrDefaultBool("COCKROACH_TICK_QUIESCED", true)
// Whether to enable experimental support for proposer-evaluated KV.
var propEvalKV = envutil.EnvOrDefaultBool("COCKROACH_PROPOSER_EVALUATED_KV", false)
// raftInitialLog{Index,Term} are the starting points for the raft log. We
// bootstrap the raft membership by synthesizing a snapshot as if there were
// some discarded prefix to the log, so we must begin the log at an arbitrary
// index greater than 1.
const (
raftInitialLogIndex = 10
raftInitialLogTerm = 5
)
// consultsTimestampCacheMethods specifies the set of methods which
// consult the timestamp cache. This syntax creates a sparse array
// with maximum index equal to the value of the final Method. Unused
// indexes default to false.
var consultsTimestampCacheMethods = [...]bool{
roachpb.Put: true,
roachpb.ConditionalPut: true,
roachpb.Increment: true,
roachpb.Delete: true,
roachpb.DeleteRange: true,
roachpb.BeginTransaction: true,
}
func consultsTimestampCache(r roachpb.Request) bool {
m := r.Method()
if m < 0 || m >= roachpb.Method(len(consultsTimestampCacheMethods)) {
return false
}
return consultsTimestampCacheMethods[m]
}
// updatesTimestampCacheMethods specifies the set of methods which if
// successful will update the timestamp cache.
var updatesTimestampCacheMethods = [...]bool{
roachpb.Get: true,
// ConditionalPut effectively reads and may not write, so must
// update the timestamp cache.
roachpb.ConditionalPut: true,
// DeleteRange updates the write timestamp cache as it doesn't leave
// intents or tombstones for keys which don't yet exist. By updating
// the write timestamp cache, it forces subsequent writes to get a
// write-too-old error and avoids the phantom delete anomaly.
roachpb.DeleteRange: true,
roachpb.Scan: true,
roachpb.ReverseScan: true,
// EndTransaction updates the write timestamp cache to prevent
// replays. Replays for the same transaction key and timestamp will
// have Txn.WriteTooOld=true and must retry on EndTransaction.
roachpb.EndTransaction: true,
}
func updatesTimestampCache(r roachpb.Request) bool {
m := r.Method()
if m < 0 || m >= roachpb.Method(len(updatesTimestampCacheMethods)) {
return false
}
return updatesTimestampCacheMethods[m]
}
// proposalResult indicates the result of a proposal with the following semantics:
// - If ShouldRetry is set, the proposal applied at a Lease index it was not
// legal for. The command should be retried.
// - Otherwise, exactly one of the BatchResponse or the Error are set and
// represent the result of the proposal.
type proposalResult struct {
Reply *roachpb.BatchResponse
Err *roachpb.Error
ShouldRetry bool
}
type replicaChecksum struct {
// started is true if the checksum computation has started.
started bool
// Computed checksum. This is set to nil on error.
checksum []byte
// If gcTimestamp is nonzero, GC this checksum after gcTimestamp. gcTimestamp
// is zero if and only if the checksum computation is in progress.
gcTimestamp time.Time
// This channel is closed after the checksum is computed, and is used
// as a notification.
notify chan struct{}
// Some debug output that can be added to the CollectChecksumResponse.
snapshot *roachpb.RaftSnapshotData
}
type atomicDescString struct {
strPtr unsafe.Pointer
}
// store atomically updates d.strPtr with the string representation of desc.
func (d *atomicDescString) store(replicaID roachpb.ReplicaID, desc *roachpb.RangeDescriptor) {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%d/", desc.RangeID)
if replicaID == 0 {
fmt.Fprintf(&buf, "?:")
} else {
fmt.Fprintf(&buf, "%d:", replicaID)
}
if !desc.IsInitialized() {
buf.WriteString("{-}")
} else {
const maxRangeChars = 30
keys.PrettyPrintRange(&buf, roachpb.Key(desc.StartKey), roachpb.Key(desc.EndKey), maxRangeChars)
}
str := buf.String()
atomic.StorePointer(&d.strPtr, unsafe.Pointer(&str))
}
// String returns the string representation of the range; since we are not
// using a lock, the copy might be inconsistent.
func (d *atomicDescString) String() string {
return *(*string)(atomic.LoadPointer(&d.strPtr))
}
// A Replica is a contiguous keyspace with writes managed via an
// instance of the Raft consensus algorithm. Many ranges may exist
// in a store and they are unlikely to be contiguous. Ranges are
// independent units and are responsible for maintaining their own
// integrity by replacing failed replicas, splitting and merging
// as appropriate.
type Replica struct {
log.AmbientContext
// TODO(tschottdorf): Duplicates r.mu.state.desc.RangeID; revisit that.
RangeID roachpb.RangeID // Should only be set by the constructor.
store *Store
// sha1 hash of the system config @ last gossip. No synchronized access;
// must only be accessed from maybeGossipSystemConfig (which in turn is
// only called from the Raft-processing goroutine).
systemDBHash []byte
abortCache *AbortCache // Avoids anomalous reads after abort
// creatingReplica is set when a replica is created as uninitialized
// via a raft message.
creatingReplica *roachpb.ReplicaDescriptor
// Held in read mode during read-only commands. Held in exclusive mode to
// prevent read-only commands from executing. Acquired before the embedded
// RWMutex.
readOnlyCmdMu syncutil.RWMutex
// rangeStr is a string representation of a RangeDescriptor that cam be
// atomically read and updated without needing to acquire the replica.mu lock.
// All updates to state.Desc should be duplicated here.
rangeStr atomicDescString
// raftMu protects Raft processing the replica.
//
// Locking notes: Replica.raftMu < Replica.mu
//
// TODO(peter): evaluate runtime overhead the timed mutex.
raftMu syncutil.TimedMutex
cmdQMu struct {
// Protects all fields in the cmdQMu struct.
//
// Locking notes: Replica.mu < Replica.cmdQMu
syncutil.TimedMutex
// Enforces at most one command is running per key(s). The global
// component tracks user writes (i.e. all keys for which keys.Addr is
// the identity), the local component the rest (e.g. RangeDescriptor,
// transaction record, Lease, ...).
global, local *CommandQueue
}
mu struct {
// Protects all fields in the mu struct.
//
// TODO(peter): evaluate runtime overhead the timed mutex.
syncutil.TimedMutex
// Has the replica been destroyed.
destroyed error
// Corrupted persistently (across process restarts) indicates whether the
// replica has been corrupted.
//
// TODO(tschottdorf): remove/refactor this field.
corrupted bool
// Is the range quiescent? Quiescent ranges are not Tick()'d and unquiesce
// whenever a Raft operation is performed.
quiescent bool
// The state of the Raft state machine.
state storagebase.ReplicaState
// Counter used for assigning lease indexes for proposals.
lastAssignedLeaseIndex uint64
// Last index persisted to the raft log (not necessarily committed).
lastIndex uint64
// The raft log index of a pending preemptive snapshot. Used to prohibit
// raft log truncation while a preemptive snapshot is in flight. A value of
// 0 indicates that there is no pending snapshot.
pendingSnapshotIndex uint64
// raftLogSize is the approximate size in bytes of the persisted raft log.
// On server restart, this value is assumed to be zero to avoid costly scans
// of the raft log. This will be correct when all log entries predating this
// process have been truncated.
raftLogSize int64
// pendingLeaseRequest is used to coalesce RequestLease requests.
pendingLeaseRequest pendingLeaseRequest
// Max bytes before split.
maxBytes int64
// proposals stores the Raft in-flight commands which
// originated at this Replica, i.e. all commands for which
// propose has been called, but which have not yet
// applied.
//
// The *ProposalData in the map are "owned" by it. Elements from the
// map must only be referenced while Replica.mu is held, except if the
// element is removed from the map first.
proposals map[storagebase.CmdIDKey]*ProposalData
internalRaftGroup *raft.RawNode
// The ID of the replica within the Raft group. May be 0 if the replica has
// been created from a preemptive snapshot (i.e. before being added to the
// Raft group). The replica ID will be non-zero whenever the replica is
// part of a Raft group.
replicaID roachpb.ReplicaID
// The ID of the leader replica within the Raft group. Used to determine
// when the leadership changes.
leaderID roachpb.ReplicaID
// The last seen replica descriptors from incoming Raft messages. These are
// stored so that the replica still knows the replica descriptors for itself
// and for its message recipients in the circumstances when its RangeDescriptor
// is out of date.
//
// Normally, a replica knows about the other replica descriptors for a
// range via the RangeDescriptor stored in Replica.mu.state.Desc. But that
// descriptor is only updated during a Split or ChangeReplicas operation.
// There are periods during a Replica's lifetime when that information is
// out of date:
//
// 1. When a replica is being newly created as the result of an incoming
// Raft message for it. This is the common case for ChangeReplicas and an
// uncommon case for Splits. The leader will be sending the replica
// messages and the replica needs to be able to respond before it can
// receive an updated range descriptor (via a snapshot,
// changeReplicasTrigger, or splitTrigger).
//
// 2. If the node containing a replica is partitioned or down while the
// replicas for the range are updated. When the node comes back up, other
// replicas may begin communicating with it and it needs to be able to
// respond. Unlike 1 where there is no range descriptor, in this situation
// the replica has a range descriptor but it is out of date. Note that a
// replica being removed from a node and then quickly re-added before the
// replica has been GC'd will also use the last seen descriptors. In
// effect, this is another path for which the replica's local range
// descriptor is out of date.
//
// The last seen replica descriptors are updated on receipt of every raft
// message via Replica.setLastReplicaDescriptors (see
// Store.HandleRaftRequest). These last seen descriptors are used when
// the replica's RangeDescriptor contains missing or out of date descriptors
// for a replica (see Replica.sendRaftMessage).
//
// Removing a replica from Store.mu.replicas is not a problem because
// when a replica is completely removed, it won't be recreated until
// there is another event that will repopulate the replicas map in the
// range descriptor. When it is temporarily dropped and recreated, the
// newly recreated replica will have a complete range descriptor.
lastToReplica, lastFromReplica roachpb.ReplicaDescriptor
// Most recent timestamps for keys / key ranges.
tsCache *timestampCache
// submitProposalFn can be set to mock out the propose operation.
submitProposalFn func(*ProposalData) error
// Computed checksum at a snapshot UUID.
checksums map[uuid.UUID]replicaChecksum
// Counts calls to Replica.tick()
ticks int
// Counts Raft messages refused due to queue congestion.
droppedMessages int
// When closed, indicates that this replica has finished sending
// an outgoing snapshot. Nothing is sent on this channel.
outSnapDone chan struct{}
// The pending outgoing snapshot if there is one.
outSnap OutgoingSnapshot
}
unreachablesMu struct {
syncutil.Mutex
remotes map[roachpb.ReplicaID]struct{}
}
}
// KeyRange is an interface type for the replicasByKey BTree, to compare
// Replica and ReplicaPlaceholder.
type KeyRange interface {
Desc() *roachpb.RangeDescriptor
rangeKeyItem
btree.Item
fmt.Stringer
}
var _ KeyRange = &Replica{}
// withRaftGroupLocked calls the supplied function with the (lazily
// initialized) Raft group. The supplied function should return true for the
// unquiesceAndWakeLeader argument if the replica should be unquiesced (and the
// leader awoken). See handleRaftReady for an instance of where this value
// varies. The shouldCampaign argument indicates whether a new raft group
// should be campaigned upon creation and is used to eagerly campaign idle
// replicas.
//
// Requires that both Replica.mu and Replica.raftMu are held.
func (r *Replica) withRaftGroupLocked(
shouldCampaign bool, f func(r *raft.RawNode) (unquiesceAndWakeLeader bool, _ error),
) error {
if r.mu.destroyed != nil {
// Silently ignore all operations on destroyed replicas. We can't return an
// error here as all errors returned from this method are considered fatal.
return nil
}
if r.mu.replicaID == 0 {
// The replica's raft group has not yet been configured (i.e. the replica
// was created from a preemptive snapshot).
return nil
}
if shouldCampaign {
// Special handling of idle replicas: we campaign their Raft group upon
// creation if we gossiped our store descriptor more than the election
// timeout in the past.
shouldCampaign = (r.mu.internalRaftGroup == nil) && r.store.canCampaignIdleReplica()
}
ctx := r.AnnotateCtx(context.TODO())
if r.mu.internalRaftGroup == nil {
raftGroup, err := raft.NewRawNode(newRaftConfig(
raft.Storage(r),
uint64(r.mu.replicaID),
r.mu.state.RaftAppliedIndex,
r.store.cfg,
&raftLogger{ctx: ctx},
), nil)
if err != nil {
return err
}
r.mu.internalRaftGroup = raftGroup
if !shouldCampaign {
// Automatically campaign and elect a leader for this group if there's
// exactly one known node for this group.
//
// A grey area for this being correct happens in the case when we're
// currently in the process of adding a second node to the group, with
// the change committed but not applied.
//
// Upon restarting, the first node would immediately elect itself and
// only then apply the config change, where really it should be applying
// first and then waiting for the majority (which would now require two
// votes, not only its own).
//
// However, in that special case, the second node has no chance to be
// elected leader while the first node restarts (as it's aware of the
// configuration and knows it needs two votes), so the worst that could
// happen is both nodes ending up in candidate state, timing out and then
// voting again. This is expected to be an extremely rare event.
//
// TODO(peter): It would be more natural for this campaigning to only be
// done when proposing a command (see defaultProposeRaftCommandLocked).
// Unfortunately, we enqueue the right hand side of a split for Raft
// ready processing if the range only has a single replica (see
// splitPostApply). Doing so implies we need to be campaigning
// that right hand side range when raft ready processing is
// performed. Perhaps we should move the logic for campaigning single
// replica ranges there so that normally we only eagerly campaign when
// proposing.
shouldCampaign = r.isSoloReplicaLocked()
}
if shouldCampaign {
if log.V(3) {
log.Infof(ctx, "campaigning")
}
if err := raftGroup.Campaign(); err != nil {
return err
}
}
}
unquiesce, err := f(r.mu.internalRaftGroup)
if unquiesce {
r.unquiesceAndWakeLeaderLocked()
}
return err
}
// withRaftGroup calls the supplied function with the (lazily initialized)
// Raft group. It acquires and releases the Replica lock, so r.mu must not be
// held (or acquired by the supplied function).
//
// Requires that Replica.raftMu is held.
func (r *Replica) withRaftGroup(
f func(r *raft.RawNode) (unquiesceAndWakeLeader bool, _ error),
) error {
r.mu.Lock()
defer r.mu.Unlock()
return r.withRaftGroupLocked(false, f)
}
var _ client.Sender = &Replica{}
var initialOutSnapDone = func() chan struct{} {
ch := make(chan struct{})
close(ch)
return ch
}()
func newReplica(rangeID roachpb.RangeID, store *Store) *Replica {
r := &Replica{
AmbientContext: store.cfg.AmbientCtx,
RangeID: rangeID,
store: store,
abortCache: NewAbortCache(rangeID),
}
// Init rangeStr with the range ID.
r.rangeStr.store(0, &roachpb.RangeDescriptor{RangeID: rangeID})
// Add replica log tag - the value is rangeStr.String().
r.AmbientContext.AddLogTag("r", &r.rangeStr)
raftMuLogger := syncutil.ThresholdLogger(
r.AnnotateCtx(context.Background()),
defaultReplicaRaftMuWarnThreshold,
func(ctx context.Context, msg string, args ...interface{}) {
log.Warningf(ctx, "raftMu: "+msg, args...)
},
func(t time.Duration) {
r.store.metrics.MuRaftNanos.RecordValue(t.Nanoseconds())
},
)
r.raftMu = syncutil.MakeTimedMutex(raftMuLogger)
replicaMuLogger := syncutil.ThresholdLogger(
r.AnnotateCtx(context.Background()),
defaultReplicaMuWarnThreshold,
func(ctx context.Context, msg string, args ...interface{}) {
log.Warningf(ctx, "replicaMu: "+msg, args...)
},
func(t time.Duration) {
r.store.metrics.MuReplicaNanos.RecordValue(t.Nanoseconds())
},
)
r.mu.TimedMutex = syncutil.MakeTimedMutex(replicaMuLogger)
r.mu.outSnapDone = initialOutSnapDone
cmdQMuLogger := syncutil.ThresholdLogger(
r.AnnotateCtx(context.Background()),
defaultReplicaMuWarnThreshold,
func(ctx context.Context, msg string, args ...interface{}) {
log.Warningf(ctx, "cmdQMu: "+msg, args...)
},
func(t time.Duration) {
r.store.metrics.MuCommandQueueNanos.RecordValue(t.Nanoseconds())
},
)
r.cmdQMu.TimedMutex = syncutil.MakeTimedMutex(cmdQMuLogger)
return r
}
// NewReplica initializes the replica using the given metadata. If the
// replica is initialized (i.e. desc contains more than a RangeID),
// replicaID should be 0 and the replicaID will be discovered from the
// descriptor.
func NewReplica(
desc *roachpb.RangeDescriptor, store *Store, replicaID roachpb.ReplicaID,
) (*Replica, error) {
r := newReplica(desc.RangeID, store)
if err := r.init(desc, store.Clock(), replicaID); err != nil {
return nil, err
}
r.maybeGossipSystemConfig()
r.maybeGossipNodeLiveness(keys.NodeLivenessSpan)
return r, nil
}
func (r *Replica) init(
desc *roachpb.RangeDescriptor, clock *hlc.Clock, replicaID roachpb.ReplicaID,
) error {
r.mu.Lock()
defer r.mu.Unlock()
return r.initLocked(desc, clock, replicaID)
}
func (r *Replica) initLocked(
desc *roachpb.RangeDescriptor, clock *hlc.Clock, replicaID roachpb.ReplicaID,
) error {
ctx := r.AnnotateCtx(context.TODO())
if r.mu.state.Desc != nil && r.isInitializedLocked() {
log.Fatalf(ctx, "r%d: cannot reinitialize an initialized replica", desc.RangeID)
}
if desc.IsInitialized() && replicaID != 0 {
return errors.Errorf("replicaID must be 0 when creating an initialized replica")
}
r.cmdQMu.Lock()
r.cmdQMu.global = NewCommandQueue(true /* optimizeOverlap */)
r.cmdQMu.local = NewCommandQueue(false /* !optimizeOverlap */)
r.cmdQMu.Unlock()
r.mu.tsCache = newTimestampCache(clock)
r.mu.proposals = map[storagebase.CmdIDKey]*ProposalData{}
r.mu.checksums = map[uuid.UUID]replicaChecksum{}
// Clear the internal raft group in case we're being reset. Since we're
// reloading the raft state below, it isn't safe to use the existing raft
// group.
r.mu.internalRaftGroup = nil
var err error
if r.mu.state, err = loadState(ctx, r.store.Engine(), desc); err != nil {
return err
}
r.rangeStr.store(0, r.mu.state.Desc)
r.mu.lastIndex, err = loadLastIndex(ctx, r.store.Engine(), r.RangeID)
if err != nil {
return err
}
pErr, err := loadReplicaDestroyedError(ctx, r.store.Engine(), r.RangeID)
if err != nil {
return err
}
r.mu.destroyed = pErr.GetDetail()
r.mu.corrupted = r.mu.destroyed != nil
if replicaID == 0 {
repDesc, ok := desc.GetReplicaDescriptor(r.store.StoreID())
if !ok {
// This is intentionally not an error and is the code path exercised
// during preemptive snapshots. The replica ID will be sent when the
// actual raft replica change occurs.
return nil
}
replicaID = repDesc.ReplicaID
}
r.rangeStr.store(replicaID, r.mu.state.Desc)
if err := r.setReplicaIDLocked(replicaID); err != nil {
return err
}
r.assertStateLocked(r.store.Engine())
return nil
}
// String returns the string representation of the replica using an
// inconsistent copy of the range descriptor. Therefore, String does not
// require a lock and its output may not be atomic with other ongoing work in
// the replica. This is done to prevent deadlocks in logging sites.
func (r *Replica) String() string {
return fmt.Sprintf("[n%d,s%d,r%s]", r.store.Ident.NodeID, r.store.Ident.StoreID, &r.rangeStr)
}
// destroyData deletes all data associated with a replica, leaving a
// tombstone. Requires that Replica.raftMu is held.
func (r *Replica) destroyDataRaftMuLocked() error {
desc := r.Desc()
iter := NewReplicaDataIterator(desc, r.store.Engine(), false /* !replicatedOnly */)
defer iter.Close()
batch := r.store.Engine().NewBatch()
defer batch.Close()
for ; iter.Valid(); iter.Next() {
_ = batch.Clear(iter.Key())
}
// Save a tombstone. The range cannot be re-replicated onto this
// node without having a replica ID of at least desc.NextReplicaID.
tombstoneKey := keys.RaftTombstoneKey(desc.RangeID)
tombstone := &roachpb.RaftTombstone{
NextReplicaID: desc.NextReplicaID,
}
ctx := r.AnnotateCtx(context.TODO())
if err := engine.MVCCPutProto(ctx, batch, nil, tombstoneKey, hlc.ZeroTimestamp, nil, tombstone); err != nil {
return err
}
return batch.Commit()
}
func (r *Replica) setReplicaID(replicaID roachpb.ReplicaID) error {
r.mu.Lock()
defer r.mu.Unlock()
return r.setReplicaIDLocked(replicaID)
}
// setReplicaIDLocked requires that the replica lock is held.
func (r *Replica) setReplicaIDLocked(replicaID roachpb.ReplicaID) error {
if replicaID == 0 {
// If the incoming message didn't give us a new replica ID,
// there's nothing to do (this is only expected for preemptive snapshots).
return nil
}
if r.mu.replicaID == replicaID {
return nil
} else if r.mu.replicaID > replicaID {
return errors.Errorf("replicaID cannot move backwards from %d to %d", r.mu.replicaID, replicaID)
} else if r.mu.replicaID != 0 {
// TODO(bdarnell): clean up previous raftGroup (update peers)
}
previousReplicaID := r.mu.replicaID
r.mu.replicaID = replicaID
// Reset the raft group to force its recreation on next usage.
r.mu.internalRaftGroup = nil
// If there was a previous replica, repropose its pending commands under
// this new incarnation.
if previousReplicaID != 0 {
// repropose all pending commands under new replicaID.
r.refreshProposalsLocked(0, reasonReplicaIDChanged)
}
return nil
}
// GetMaxBytes atomically gets the range maximum byte limit.
func (r *Replica) GetMaxBytes() int64 {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.maxBytes
}
// SetMaxBytes atomically sets the maximum byte limit before
// split. This value is cached by the range for efficiency.
func (r *Replica) SetMaxBytes(maxBytes int64) {
r.mu.Lock()
defer r.mu.Unlock()
r.mu.maxBytes = maxBytes
}
// IsFirstRange returns true if this is the first range.
func (r *Replica) IsFirstRange() bool {
return r.RangeID == 1
}
// getLease returns the current lease, and the tentative next one, if a lease
// request initiated by this replica is in progress.
func (r *Replica) getLease() (*roachpb.Lease, *roachpb.Lease) {
r.mu.Lock()
defer r.mu.Unlock()
if nextLease, ok := r.mu.pendingLeaseRequest.RequestPending(); ok {
return r.mu.state.Lease, &nextLease
}
return r.mu.state.Lease, nil
}
// newNotLeaseHolderError returns a NotLeaseHolderError initialized with the
// replica for the holder (if any) of the given lease.
//
// Note that this error can be generated on the Raft processing goroutine, so
// its output should be completely determined by its parameters.
func newNotLeaseHolderError(
l *roachpb.Lease, originStoreID roachpb.StoreID, rangeDesc *roachpb.RangeDescriptor,
) error {
err := &roachpb.NotLeaseHolderError{
RangeID: rangeDesc.RangeID,
}
err.Replica, _ = rangeDesc.GetReplicaDescriptor(originStoreID)
if l != nil {
// Morally, we return the lease-holding Replica here. However, in the
// case in which a leader removes itself, we want the followers to
// avoid handing out a misleading clue (which in itself shouldn't be
// overly disruptive as the lease would expire and then this method
// shouldn't be called for it any more, but at the very least it
// could catch tests in a loop, presumably due to manual clocks).
_, stillMember := rangeDesc.GetReplicaDescriptor(l.Replica.StoreID)
if stillMember {
err.LeaseHolder = &l.Replica
err.Lease = l
}
}
return err
}
// redirectOnOrAcquireLease checks whether this replica has the lease at the
// current timestamp. If it does, returns success. If another replica currently
// holds the lease, redirects by returning NotLeaseHolderError. If the lease is
// expired, a renewal is synchronously requested. This method uses the
// pendingLeaseRequest structure to guarantee only one request to grant the
// lease is pending. Leases are eagerly renewed when a request with a timestamp
// close to the beginning of the stasis period is served.
//
// TODO(spencer): for write commands, don't wait while requesting
// the range lease. If the lease acquisition fails, the write cmd
// will fail as well. If it succeeds, as is likely, then the write
// will not incur latency waiting for the command to complete.
// Reads, however, must wait.
func (r *Replica) redirectOnOrAcquireLease(ctx context.Context) *roachpb.Error {
// Loop until the lease is held or the replica ascertains the actual
// lease holder. Returns also on context.Done() (timeout or cancellation).
for attempt := 1; ; attempt++ {
timestamp := r.store.Clock().Now()
llChan, pErr := func() (<-chan *roachpb.Error, *roachpb.Error) {
r.mu.Lock()
defer r.mu.Unlock()
lease := r.mu.state.Lease
if lease.Covers(timestamp) {
if !lease.OwnedBy(r.store.StoreID()) {
// If lease is currently held by another, redirect to holder.
return nil, roachpb.NewError(
newNotLeaseHolderError(lease, r.store.StoreID(), r.mu.state.Desc))
}
// Check that we're not in the process of transferring the lease away.
// If we are transferring the lease away, we can't serve reads or
// propose Raft commands - see comments on TransferLease.
// TODO(andrei): If the lease is being transferred, consider returning a
// new error type so the client backs off until the transfer is
// completed.
repDesc, err := r.getReplicaDescriptorLocked()
if err != nil {
return nil, roachpb.NewError(err)
}
if transferLease, ok := r.mu.pendingLeaseRequest.TransferInProgress(
repDesc.ReplicaID); ok {
return nil, roachpb.NewError(
newNotLeaseHolderError(&transferLease, r.store.StoreID(), r.mu.state.Desc))
}
// Should we extend the lease?
if _, ok := r.mu.pendingLeaseRequest.RequestPending(); !ok &&
!timestamp.Less(lease.StartStasis.Add(-int64(r.store.cfg.RangeLeaseRenewalDuration), 0)) {
if log.V(2) {
log.Warningf(ctx, "extending lease %s at %s", lease, timestamp)
}
// We had an active lease to begin with, but we want to trigger
// a lease extension. We don't need to wait for that extension
// to go through and simply ignore the returned channel (which
// is buffered).
_ = r.requestLeaseLocked(timestamp)
}
// Return a nil chan to signal that we have a valid lease.
return nil, nil
}
log.Eventf(ctx, "request range lease (attempt #%d)", attempt)
// No active lease: Request renewal if a renewal is not already pending.
return r.requestLeaseLocked(timestamp), nil
}()
if pErr != nil {
return pErr
}
if llChan == nil {
// We own a covering lease.
return nil
}
// Wait for the range lease to finish, or the context to expire.
select {
case pErr := <-llChan:
if pErr != nil {
// Getting a LeaseRejectedError back means someone else got there
// first, or the lease request was somehow invalid due to a
// concurrent change. Convert the error to a NotLeaseHolderError.
if _, ok := pErr.GetDetail().(*roachpb.LeaseRejectedError); ok {
lease, _ := r.getLease()
if !lease.Covers(r.store.Clock().Now()) {
lease = nil
}
return roachpb.NewError(newNotLeaseHolderError(lease, r.store.StoreID(), r.Desc()))
}
return pErr
}
log.Event(ctx, "lease acquisition succeeded")
continue
case <-ctx.Done():
log.ErrEventf(ctx, "lease acquisition failed: %s", ctx.Err())
case <-r.store.Stopper().ShouldStop():
}
return roachpb.NewError(newNotLeaseHolderError(nil, r.store.StoreID(), r.Desc()))
}
}
// IsInitialized is true if we know the metadata of this range, either
// because we created it or we have received an initial snapshot from
// another node. It is false when a range has been created in response
// to an incoming message but we are waiting for our initial snapshot.
func (r *Replica) IsInitialized() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.isInitializedLocked()
}
// isInitializedLocked is true if we know the metadata of this range, either
// because we created it or we have received an initial snapshot from
// another node. It is false when a range has been created in response
// to an incoming message but we are waiting for our initial snapshot.
// isInitializedLocked requires that the replica lock is held.
func (r *Replica) isInitializedLocked() bool {
return r.mu.state.Desc.IsInitialized()
}
// Desc returns the authoritative range descriptor, acquiring a replica lock in
// the process.
func (r *Replica) Desc() *roachpb.RangeDescriptor {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.state.Desc
}
// setDesc atomically sets the range's descriptor. This method calls
// processRangeDescriptorUpdate() to make the Store handle the descriptor
// update. Requires raftMu to be locked.
func (r *Replica) setDesc(desc *roachpb.RangeDescriptor) error {
r.setDescWithoutProcessUpdate(desc)
if r.store == nil {
// r.rm is null in some tests.
return nil
}
return r.store.processRangeDescriptorUpdate(r)
}
// setDescWithoutProcessUpdate updates the range descriptor without calling
// processRangeDescriptorUpdate. Requires raftMu to be locked.
func (r *Replica) setDescWithoutProcessUpdate(desc *roachpb.RangeDescriptor) {
r.mu.Lock()
defer r.mu.Unlock()
if desc.RangeID != r.RangeID {
ctx := r.AnnotateCtx(context.TODO())
log.Fatalf(ctx, "range descriptor ID (%d) does not match replica's range ID (%d)",
desc.RangeID, r.RangeID)
}
if r.mu.state.Desc != nil && r.mu.state.Desc.IsInitialized() &&
(desc == nil || !desc.IsInitialized()) {
ctx := r.AnnotateCtx(context.TODO())
log.Fatalf(ctx, "cannot replace initialized descriptor with uninitialized one: %+v -> %+v",
r.mu.state.Desc, desc)
}
r.rangeStr.store(r.mu.replicaID, desc)
r.mu.state.Desc = desc
}
// GetReplicaDescriptor returns the replica for this range from the range
// descriptor. Returns a *RangeNotFoundError if the replica is not found.
// No other errors are returned.
func (r *Replica) GetReplicaDescriptor() (roachpb.ReplicaDescriptor, error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.getReplicaDescriptorLocked()
}
// getReplicaDescriptorLocked is like getReplicaDescriptor, but assumes that r.mu is held.
func (r *Replica) getReplicaDescriptorLocked() (roachpb.ReplicaDescriptor, error) {
repDesc, ok := r.mu.state.Desc.GetReplicaDescriptor(r.store.StoreID())
if ok {
return repDesc, nil
}
return roachpb.ReplicaDescriptor{}, roachpb.NewRangeNotFoundError(r.RangeID)
}
// setLastReplicaDescriptors sets the the most recently seen replica
// descriptors to those contained in the *RaftMessageRequest, acquiring r.mu
// to do so.
func (r *Replica) setLastReplicaDescriptors(req *RaftMessageRequest) {
r.mu.Lock()
r.mu.lastFromReplica = req.FromReplica
r.mu.lastToReplica = req.ToReplica
r.mu.Unlock()
}
// GetMVCCStats returns a copy of the MVCC stats object for this range.
func (r *Replica) GetMVCCStats() enginepb.MVCCStats {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.state.Stats
}
// ContainsKey returns whether this range contains the specified key.
func (r *Replica) ContainsKey(key roachpb.Key) bool {
return containsKey(*r.Desc(), key)
}
func containsKey(desc roachpb.RangeDescriptor, key roachpb.Key) bool {
if bytes.HasPrefix(key, keys.LocalRangeIDPrefix) {
return bytes.HasPrefix(key, keys.MakeRangeIDPrefix(desc.RangeID))
}
keyAddr, err := keys.Addr(key)
if err != nil {
return false
}
return desc.ContainsKey(keyAddr)
}
// ContainsKeyRange returns whether this range contains the specified
// key range from start to end.
func (r *Replica) ContainsKeyRange(start, end roachpb.Key) bool {
return containsKeyRange(*r.Desc(), start, end)
}
func containsKeyRange(desc roachpb.RangeDescriptor, start, end roachpb.Key) bool {
startKeyAddr, err := keys.Addr(start)
if err != nil {