-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathreplica.go
1908 lines (1714 loc) · 68.2 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 (spencer.kimball@gmail.com)
// Author: Jiang-Ming Yang (jiangming.yang@gmail.com)
// Author: Tobias Schottdorf (tobias.schottdorf@gmail.com)
// Author: Bram Gruneir (bram+code@cockroachlabs.com)
package storage
import (
"bytes"
"errors"
"fmt"
"math"
"math/rand"
"reflect"
"sync"
"time"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"github.com/gogo/protobuf/proto"
opentracing "github.com/opentracing/opentracing-go"
"golang.org/x/net/context"
"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/storage/engine"
"github.com/cockroachdb/cockroach/util"
"github.com/cockroachdb/cockroach/util/encoding"
"github.com/cockroachdb/cockroach/util/hlc"
"github.com/cockroachdb/cockroach/util/log"
"github.com/cockroachdb/cockroach/util/tracing"
"github.com/cockroachdb/cockroach/util/uuid"
)
const (
// DefaultHeartbeatInterval is how often heartbeats are sent from the
// transaction coordinator to a live transaction. These keep it from
// being preempted by other transactions writing the same keys. If a
// transaction fails to be heartbeat within 2x the heartbeat interval,
// it may be aborted by conflicting txns.
DefaultHeartbeatInterval = 5 * time.Second
// 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 raft leader of the first range gossips it.
sentinelGossipTTL = 2 * time.Minute
// sentinalGossipInterval 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 leaders gossip
// their config maps. Even if config maps do not expire, we still
// need a periodic gossip to safeguard against failure of a leader
// to gossip after performing an update to the map.
configGossipInterval = 1 * time.Minute
opReplica = "replica"
)
// CommandFilter may be used in tests through the StorageTestingMocker to
// intercept the handling of commands and artificially generate errors. Return
// nil to continue with regular processing or non-nil to terminate processing
// with the returned error. Note that in a multi-replica test this filter will
// be run once for each replica and must produce consistent results each time.
type CommandFilter func(roachpb.StoreID, roachpb.Request, roachpb.Header) error
// 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
// raftInitialLogIndex is the starting point 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
// DefaultLeaderLeaseDuration is the default duration of the leader lease.
DefaultLeaderLeaseDuration = time.Second
)
// tsCacheMethods specifies the set of methods which affect 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 tsCacheMethods = [...]bool{
roachpb.Get: true,
roachpb.Put: true,
roachpb.ConditionalPut: true,
roachpb.Increment: true,
roachpb.Scan: true,
roachpb.ReverseScan: true,
roachpb.Delete: true,
roachpb.DeleteRange: true,
roachpb.ResolveIntent: true,
roachpb.ResolveIntentRange: true,
}
// usesTimestampCache returns true if the request affects or is
// affected by the timestamp cache.
func usesTimestampCache(r roachpb.Request) bool {
m := r.Method()
if m < 0 || m >= roachpb.Method(len(tsCacheMethods)) {
return false
}
return tsCacheMethods[m]
}
// A pendingCmd holds a done channel for a command sent to Raft. Once
// committed to the Raft log, the command is executed and the result returned
// via the done channel.
type pendingCmd struct {
ctx context.Context
idKey cmdIDKey
raftCmd roachpb.RaftCommand
done chan roachpb.ResponseWithError // Used to signal waiting RPC handler
}
type cmdIDKey string
type replicaChecksum struct {
// Set to true when the checksum computation is ready. The checksum
// can be nil indicating an error.
ok bool
// Computed checksum. This is set to nil on error.
checksum []byte
// GC this checksum after this timestamp. The timestamp is set when
// ok is set to true.
gcTimestamp time.Time
}
// 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 {
RangeID roachpb.RangeID // Should only be set by the constructor.
store *Store
stats *rangeStats // Range statistics
systemDBHash []byte // sha1 hash of the system config @ last gossip
sequence *SequenceCache // Provides txn replay protection
// 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 sync.RWMutex
mu struct {
sync.Mutex // Protects all fields in the mu struct.
appliedIndex uint64 // Last index applied to the state machine.
cmdQ *CommandQueue // Enforce at most one command is running per key(s).
desc *roachpb.RangeDescriptor
lastIndex uint64 // Last index persisted to the raft log (not necessarily committed).
leaderLease *roachpb.Lease
maxBytes int64 // Max bytes before split.
pendingCmds map[cmdIDKey]*pendingCmd
pendingSeq uint64 // atomic sequence counter for cmdIDKey generation.
raftGroup *raft.RawNode
replicaID roachpb.ReplicaID
truncatedState *roachpb.RaftTruncatedState
tsCache *TimestampCache // Most recent timestamps for keys / key ranges
llChans []chan *roachpb.Error // Slice of channels to send on after leader lease acquisition
// proposeRaftCommandFn can be set to mock out the propose operation.
proposeRaftCommandFn func(cmdIDKey, *pendingCmd) error
checksums map[uuid.UUID]replicaChecksum // computed checksum at a snapshot UUID.
checksumNotify map[uuid.UUID]chan []byte // notify of computed checksum.
}
}
var _ client.Sender = &Replica{}
// 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 := &Replica{
store: store,
sequence: NewSequenceCache(desc.RangeID),
RangeID: desc.RangeID,
}
if err := r.newReplicaInner(desc, store.Clock(), replicaID); err != nil {
return nil, err
}
r.maybeGossipSystemConfig()
var err error
if r.stats, err = newRangeStats(desc.RangeID, store.Engine()); err != nil {
return nil, err
}
return r, nil
}
func (r *Replica) newReplicaInner(desc *roachpb.RangeDescriptor, clock *hlc.Clock, replicaID roachpb.ReplicaID) error {
r.mu.Lock()
defer r.mu.Unlock()
r.mu.cmdQ = NewCommandQueue()
r.mu.tsCache = NewTimestampCache(clock)
r.mu.pendingCmds = map[cmdIDKey]*pendingCmd{}
r.mu.checksums = map[uuid.UUID]replicaChecksum{}
r.mu.checksumNotify = map[uuid.UUID]chan []byte{}
r.setDescWithoutProcessUpdateLocked(desc)
var err error
r.mu.lastIndex, err = r.loadLastIndexLocked()
if err != nil {
return err
}
r.mu.appliedIndex, err = r.loadAppliedIndexLocked(r.store.Engine())
if err != nil {
return err
}
r.mu.leaderLease, err = loadLeaderLease(r.store.Engine(), desc.RangeID)
if err != nil {
return err
}
if r.isInitializedLocked() && replicaID != 0 {
return util.Errorf("replicaID must be 0 when creating an initialized replica")
}
if replicaID == 0 {
_, repDesc := desc.FindReplica(r.store.StoreID())
if repDesc == nil {
return util.Errorf("cannot recreate replica that is not a member of its range (StoreID %s not found in %s)",
r.store.StoreID(), desc)
}
replicaID = repDesc.ReplicaID
}
return r.setReplicaIDLocked(replicaID)
}
// String returns a string representation of the range. It acquires mu.Lock in the call to Desc().
func (r *Replica) String() string {
desc := r.Desc()
return fmt.Sprintf("range=%d [%s-%s)", desc.RangeID, desc.StartKey, desc.EndKey)
}
// Destroy clears pending command queue by sending each pending
// command an error and cleans up all data associated with this range.
func (r *Replica) Destroy(origDesc roachpb.RangeDescriptor) error {
desc := r.Desc()
if _, rd := desc.FindReplica(r.store.StoreID()); rd != nil && rd.ReplicaID >= origDesc.NextReplicaID {
return util.Errorf("cannot destroy replica %s; replica ID has changed (%s >= %s)",
r, rd.ReplicaID, origDesc.NextReplicaID)
}
// Clear the pending command queue.
r.mu.Lock()
for _, p := range r.mu.pendingCmds {
p.done <- roachpb.ResponseWithError{
Reply: &roachpb.BatchResponse{},
Err: roachpb.NewError(roachpb.NewRangeNotFoundError(r.RangeID)),
}
}
// Clear the map.
r.mu.pendingCmds = map[cmdIDKey]*pendingCmd{}
r.mu.Unlock()
return r.store.destroyReplicaData(desc)
}
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 r.mu.replicaID == replicaID {
return nil
} else if r.mu.replicaID > replicaID {
return util.Errorf("replicaID cannot move backwards")
} else if r.mu.replicaID != 0 {
// TODO(bdarnell): clean up previous raftGroup (cancel pending commands,
// update peers)
}
raftCfg := &raft.Config{
ID: uint64(replicaID),
Applied: r.mu.appliedIndex,
ElectionTick: r.store.ctx.RaftElectionTimeoutTicks,
HeartbeatTick: r.store.ctx.RaftHeartbeatIntervalTicks,
Storage: r,
// TODO(bdarnell): make these configurable; evaluate defaults.
MaxSizePerMsg: 1024 * 1024,
MaxInflightMsgs: 256,
Logger: &raftLogger{group: uint64(r.RangeID)},
}
raftGroup, err := raft.NewRawNode(raftCfg, nil)
if err != nil {
return err
}
r.mu.replicaID = replicaID
r.mu.raftGroup = raftGroup
// 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 progress of adding a second node to the group,
// with the change committed but not applied.
// Upon restarting, the 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 this 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.
if len(r.mu.desc.Replicas) == 1 && r.mu.desc.Replicas[0].StoreID == r.store.StoreID() {
if err := raftGroup.Campaign(); err != nil {
return err
}
}
return nil
}
// context returns a context which is initialized with information about
// this range. It is only relevant when commands need to be executed
// on this range in the absence of a pre-existing context, such as
// during range scanner operations.
func (r *Replica) context() context.Context {
return context.WithValue(r.store.Context(nil), log.RangeID, r.RangeID)
}
// 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 bytes.Equal(r.Desc().StartKey, roachpb.RKeyMin)
}
func loadLeaderLease(eng engine.Engine, rangeID roachpb.RangeID) (*roachpb.Lease, error) {
lease := &roachpb.Lease{}
if _, err := engine.MVCCGetProto(eng, keys.RangeLeaderLeaseKey(rangeID), roachpb.ZeroTimestamp, true, nil, lease); err != nil {
return nil, err
}
return lease, nil
}
// getLeaderLease returns the current leader lease.
func (r *Replica) getLeaderLease() *roachpb.Lease {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.leaderLease
}
// newNotLeaderError returns a NotLeaderError initialized with the
// replica for the holder (if any) of the given lease.
func (r *Replica) newNotLeaderError(l *roachpb.Lease, originStoreID roachpb.StoreID) error {
err := &roachpb.NotLeaderError{}
if l != nil && l.Replica.ReplicaID != 0 {
desc := r.Desc()
err.RangeID = r.RangeID
_, err.Replica = desc.FindReplica(originStoreID)
_, err.Leader = desc.FindReplica(l.Replica.StoreID)
}
return err
}
// requestLeaderLease sends a request to obtain or extend a leader
// lease for this replica. Unless an error is returned, the obtained
// lease will be valid for a time interval containing the requested
// timestamp. Only a single lease request may be pending at a time.
func (r *Replica) requestLeaderLease(timestamp roachpb.Timestamp) <-chan *roachpb.Error {
r.mu.Lock()
defer r.mu.Unlock()
llChan := make(chan *roachpb.Error, 1)
if len(r.mu.llChans) > 0 {
r.mu.llChans = append(r.mu.llChans, llChan)
return llChan
}
r.store.Stopper().RunWorker(func() {
pErr := func() *roachpb.Error {
// TODO(Tobias): get duration from configuration, either as a config flag
// or, later, dynamically adjusted.
duration := DefaultLeaderLeaseDuration
// Prepare a Raft command to get a leader lease for this replica.
expiration := timestamp.Add(int64(duration), 0)
desc := r.Desc()
_, replica := desc.FindReplica(r.store.StoreID())
if replica == nil {
return roachpb.NewError(roachpb.NewRangeNotFoundError(r.RangeID))
}
args := &roachpb.LeaderLeaseRequest{
Span: roachpb.Span{
Key: desc.StartKey.AsRawKey(),
},
Lease: roachpb.Lease{
Start: timestamp,
Expiration: expiration,
Replica: *replica,
},
}
ba := roachpb.BatchRequest{}
ba.Timestamp = r.store.Clock().Now()
ba.RangeID = r.RangeID
ba.Add(args)
// Send lease request directly to raft in order to skip unnecessary
// checks from normal request machinery, (e.g. the command queue).
// Note that the command itself isn't traced, but usually the caller
// waiting for the result has an active Trace.
cmd, err := r.proposeRaftCommand(r.context(), ba)
if err != nil {
return roachpb.NewError(err)
}
// If the command was committed, wait for the range to apply it.
select {
case c := <-cmd.done:
if c.Err != nil {
if log.V(1) {
log.Infof("failed to acquire leader lease for replica %s: %s", r.store, c.Err)
}
}
return c.Err
case <-r.store.Stopper().ShouldStop():
return roachpb.NewError(r.newNotLeaderError(nil, r.store.StoreID()))
}
}()
// Send result of leader lease to all waiter channels.
r.mu.Lock()
defer r.mu.Unlock()
for _, llChan := range r.mu.llChans {
llChan <- pErr
}
r.mu.llChans = r.mu.llChans[:0]
})
r.mu.llChans = append(r.mu.llChans, llChan)
return llChan
}
// redirectOnOrAcquireLeaderLease checks whether this replica has the
// leader lease at the specified timestamp. If it does, returns
// success. If another replica currently holds the lease, redirects by
// returning NotLeaderError. If the lease is expired, a renewal is
// synchronously requested. This method uses the leader lease mutex
// to guarantee only one request to grant the lease is pending.
//
// TODO(spencer): implement threshold regrants to avoid latency in
// the presence of read or write pressure sufficiently close to the
// current lease's expiration.
//
// TODO(spencer): for write commands, don't wait while requesting
// the leader 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) redirectOnOrAcquireLeaderLease(trace opentracing.Span, 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()
if lease := r.getLeaderLease(); lease.Covers(timestamp) {
if lease.OwnedBy(r.store.StoreID()) {
// Happy path: We have an active lease, nothing to do.
return nil
}
// If lease is currently held by another, redirect to holder.
return roachpb.NewError(r.newNotLeaderError(lease, r.store.StoreID()))
}
// Otherwise, no active lease: Request renewal if a renewal is not already pending.
trace.LogEvent(fmt.Sprintf("request leader lease (attempt #%d)", attempt))
llChan := r.requestLeaderLease(timestamp)
// Wait for the leader 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 NotLeaderError.
if _, ok := pErr.GetDetail().(*roachpb.LeaseRejectedError); ok {
lease := r.getLeaderLease()
if !lease.Covers(r.store.Clock().Now()) {
lease = nil
}
return roachpb.NewError(r.newNotLeaderError(lease, r.store.StoreID()))
}
return pErr
}
continue
case <-ctx.Done():
case <-r.store.Stopper().ShouldStop():
}
return roachpb.NewError(r.newNotLeaderError(nil, r.store.StoreID()))
}
}
// 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 len(r.mu.desc.EndKey) > 0
}
// Desc returns the range's descriptor.
func (r *Replica) Desc() *roachpb.RangeDescriptor {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.desc
}
// setDesc atomically sets the range's descriptor. This method calls
// processRangeDescriptorUpdate() to make the range manager handle the
// descriptor update.
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.
func (r *Replica) setDescWithoutProcessUpdate(desc *roachpb.RangeDescriptor) {
r.mu.Lock()
defer r.mu.Unlock()
r.setDescWithoutProcessUpdateLocked(desc)
}
// setDescWithoutProcessUpdateLocked updates the range descriptor without
// calling processRangeDescriptorUpdate.
// setDescWithoutProcessUpdateLocked requires that the replica lock is held.
func (r *Replica) setDescWithoutProcessUpdateLocked(desc *roachpb.RangeDescriptor) {
if desc.RangeID != r.RangeID {
panic(fmt.Sprintf("range descriptor ID (%d) does not match replica's range ID (%d)",
desc.RangeID, r.RangeID))
}
r.mu.desc = desc
}
// GetReplica returns the replica for this range from the range descriptor.
// Returns nil if the replica is not found.
func (r *Replica) GetReplica() *roachpb.ReplicaDescriptor {
_, replica := r.Desc().FindReplica(r.store.StoreID())
return replica
}
// ReplicaDescriptor returns information about the given member of
// this replica's range.
func (r *Replica) ReplicaDescriptor(replicaID roachpb.ReplicaID) (roachpb.ReplicaDescriptor, error) {
r.mu.Lock()
defer r.mu.Unlock()
desc := r.mu.desc
for _, repAddress := range desc.Replicas {
if repAddress.ReplicaID == replicaID {
return repAddress, nil
}
}
return roachpb.ReplicaDescriptor{}, util.Errorf("replica %d not found in range %d",
replicaID, desc.RangeID)
}
// GetMVCCStats returns a copy of the MVCC stats object for this range.
func (r *Replica) GetMVCCStats() engine.MVCCStats {
return r.stats.GetMVCC()
}
// 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))
}
return desc.ContainsKey(keys.Addr(key))
}
// 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 {
return desc.ContainsKeyRange(keys.Addr(start), keys.Addr(end))
}
// getLastReplicaGCTimestamp reads the timestamp at which the replica was
// last checked for garbage collection.
func (r *Replica) getLastReplicaGCTimestamp() (roachpb.Timestamp, error) {
key := keys.RangeLastReplicaGCTimestampKey(r.RangeID)
timestamp := roachpb.Timestamp{}
_, err := engine.MVCCGetProto(r.store.Engine(), key, roachpb.ZeroTimestamp, true, nil, ×tamp)
if err != nil {
return roachpb.ZeroTimestamp, err
}
return timestamp, nil
}
func (r *Replica) setLastReplicaGCTimestamp(timestamp roachpb.Timestamp) error {
key := keys.RangeLastReplicaGCTimestampKey(r.RangeID)
return engine.MVCCPutProto(r.store.Engine(), nil, key, roachpb.ZeroTimestamp, nil, ×tamp)
}
// getLastVerificationTimestamp reads the timestamp at which the replica's
// data was last verified.
func (r *Replica) getLastVerificationTimestamp() (roachpb.Timestamp, error) {
key := keys.RangeLastVerificationTimestampKey(r.RangeID)
timestamp := roachpb.Timestamp{}
_, err := engine.MVCCGetProto(r.store.Engine(), key, roachpb.ZeroTimestamp, true, nil, ×tamp)
if err != nil {
return roachpb.ZeroTimestamp, err
}
return timestamp, nil
}
func (r *Replica) setLastVerificationTimestamp(timestamp roachpb.Timestamp) error {
key := keys.RangeLastVerificationTimestampKey(r.RangeID)
return engine.MVCCPutProto(r.store.Engine(), nil, key, roachpb.ZeroTimestamp, nil, ×tamp)
}
// RaftStatus returns the current raft status of the replica.
func (r *Replica) RaftStatus() *raft.Status {
r.mu.Lock()
defer r.mu.Unlock()
return r.mu.raftGroup.Status()
}
// Send adds a command for execution on this range. The command's
// affected keys are verified to be contained within the range and the
// range's leadership is confirmed. The command is then dispatched
// either along the read-only execution path or the read-write Raft
// command queue.
func (r *Replica) Send(ctx context.Context, ba roachpb.BatchRequest) (*roachpb.BatchResponse, *roachpb.Error) {
var br *roachpb.BatchResponse
if err := r.checkBatchRequest(ba); err != nil {
return nil, roachpb.NewError(err)
}
sp, cleanupSp := tracing.SpanFromContext(opReplica, r.store.Tracer(), ctx)
defer cleanupSp()
// Differentiate between admin, read-only and write.
var pErr *roachpb.Error
if ba.IsAdmin() {
sp.LogEvent("admin path")
br, pErr = r.addAdminCmd(ctx, ba)
} else if ba.IsReadOnly() {
sp.LogEvent("read-only path")
br, pErr = r.addReadOnlyCmd(ctx, ba)
} else if ba.IsWrite() {
sp.LogEvent("read-write path")
br, pErr = r.addWriteCmd(ctx, ba, nil)
} else if len(ba.Requests) == 0 {
// empty batch; shouldn't happen (we could handle it, but it hints
// at someone doing weird things, and once we drop the key range
// from the header it won't be clear how to route those requests).
panic("empty batch")
} else {
panic(fmt.Sprintf("don't know how to handle command %s", ba))
}
if _, ok := pErr.GetDetail().(*roachpb.RaftGroupDeletedError); ok {
// This error needs to be converted appropriately so that
// clients will retry.
pErr = roachpb.NewError(roachpb.NewRangeNotFoundError(r.RangeID))
}
// TODO(tschottdorf): assert nil reply on error.
if pErr != nil {
sp.LogEvent(fmt.Sprintf("error: %s", pErr))
return nil, pErr
}
return br, nil
}
// TODO(tschottdorf): almost obsolete.
func (r *Replica) checkCmdHeader(header *roachpb.Span) error {
if !r.ContainsKeyRange(header.Key, header.EndKey) {
return roachpb.NewRangeKeyMismatchError(header.Key, header.EndKey, r.Desc())
}
return nil
}
// checkBatchRequest verifies BatchRequest validity requirements. In
// particular, timestamp, user, user priority and transactions must
// all be set to identical values between the batch request header and
// all constituent batch requests. Also, either all requests must be
// read-only, or none.
// TODO(tschottdorf): should check that request is contained in range
// and that EndTransaction only occurs at the very end.
func (r *Replica) checkBatchRequest(ba roachpb.BatchRequest) error {
if ba.IsReadOnly() {
if ba.ReadConsistency == roachpb.INCONSISTENT && ba.Txn != nil {
// Disallow any inconsistent reads within txns.
return util.Errorf("cannot allow inconsistent reads within a transaction")
}
if ba.ReadConsistency == roachpb.CONSENSUS {
return util.Errorf("consensus reads not implemented")
}
} else if ba.ReadConsistency == roachpb.INCONSISTENT {
return util.Errorf("inconsistent mode is only available to reads")
}
return nil
}
// beginCmds waits for any overlapping, already-executing commands via
// the command queue and adds itself to queues based on keys affected by the
// batched commands. This gates subsequent commands with overlapping keys or
// key ranges. This method will block if there are any overlapping commands
// already in the queue. Returns a cleanup function to be called when the
// commands are done and can be removed from the queue.
func (r *Replica) beginCmds(ba *roachpb.BatchRequest) func(*roachpb.Error) {
var cmdKeys []interface{}
// Don't use the command queue for inconsistent reads.
if ba.ReadConsistency != roachpb.INCONSISTENT {
var spans []roachpb.Span
readOnly := ba.IsReadOnly()
for _, union := range ba.Requests {
h := union.GetInner().Header()
spans = append(spans, roachpb.Span{Key: h.Key, EndKey: h.EndKey})
}
var wg sync.WaitGroup
r.mu.Lock()
r.mu.cmdQ.GetWait(readOnly, &wg, spans...)
cmdKeys = append(cmdKeys, r.mu.cmdQ.Add(readOnly, spans...)...)
r.mu.Unlock()
wg.Wait()
}
// Update the incoming timestamp if unset. Wait until after any
// preceding command(s) for key range are complete so that the node
// clock has been updated to the high water mark of any commands
// which might overlap this one in effect.
if ba.Timestamp.Equal(roachpb.ZeroTimestamp) {
if ba.Txn != nil {
// TODO(tschottdorf): see if this is already done somewhere else.
ba.Timestamp = ba.Txn.Timestamp
} else {
ba.Timestamp = r.store.Clock().Now()
}
}
return func(pErr *roachpb.Error) {
r.endCmds(cmdKeys, ba, pErr)
}
}
// endCmds removes pending commands from the command queue and updates
// the timestamp cache using the final timestamp of each command.
func (r *Replica) endCmds(cmdKeys []interface{}, ba *roachpb.BatchRequest, pErr *roachpb.Error) {
r.mu.Lock()
defer r.mu.Unlock()
// Only update the timestamp cache if the command succeeded and we're not
// doing inconsistent ops (in which case the ops are always read-only).
if pErr == nil && ba.ReadConsistency != roachpb.INCONSISTENT {
for _, union := range ba.Requests {
args := union.GetInner()
if usesTimestampCache(args) {
header := args.Header()
var txnID *uuid.UUID
if ba.Txn != nil {
txnID = ba.Txn.ID
}
r.mu.tsCache.Add(header.Key, header.EndKey, ba.Timestamp, txnID, roachpb.IsReadOnly(args))
}
}
}
r.mu.cmdQ.Remove(cmdKeys)
}
// addAdminCmd executes the command directly. There is no interaction
// with the command queue or the timestamp cache, as admin commands
// are not meant to consistently access or modify the underlying data.
// Admin commands must run on the leader replica. Batch support here is
// limited to single-element batches; everything else catches an error.
func (r *Replica) addAdminCmd(ctx context.Context, ba roachpb.BatchRequest) (*roachpb.BatchResponse, *roachpb.Error) {
if len(ba.Requests) != 1 {
return nil, roachpb.NewErrorf("only single-element admin batches allowed")
}
args := ba.Requests[0].GetInner()
if err := r.checkCmdHeader(args.Header()); err != nil {
return nil, roachpb.NewErrorWithTxn(err, ba.Txn)
}
sp, cleanupSp := tracing.SpanFromContext(opReplica, r.store.Tracer(), ctx)
defer cleanupSp()
sp.SetOperationName(reflect.TypeOf(args).String())
// Admin commands always require the leader lease.
if pErr := r.redirectOnOrAcquireLeaderLease(sp, ctx); pErr != nil {
return nil, pErr
}
var resp roachpb.Response
var pErr *roachpb.Error
switch tArgs := args.(type) {
case *roachpb.AdminSplitRequest:
var reply roachpb.AdminSplitResponse
reply, pErr = r.AdminSplit(ctx, *tArgs, r.Desc())
resp = &reply
case *roachpb.AdminMergeRequest:
var reply roachpb.AdminMergeResponse
reply, pErr = r.AdminMerge(ctx, *tArgs, r.Desc())
resp = &reply
case *roachpb.CheckConsistencyRequest:
var reply roachpb.CheckConsistencyResponse
reply, pErr = r.CheckConsistency(*tArgs, r.Desc())
resp = &reply
default:
return nil, roachpb.NewErrorf("unrecognized admin command: %T", args)
}
if pErr != nil {
return nil, pErr
}
br := &roachpb.BatchResponse{}
br.Add(resp)
br.Txn = resp.Header().Txn
return br, nil
}
// addReadOnlyCmd updates the read timestamp cache and waits for any
// overlapping writes currently processing through Raft ahead of us to
// clear via the read queue.
func (r *Replica) addReadOnlyCmd(ctx context.Context, ba roachpb.BatchRequest) (br *roachpb.BatchResponse, pErr *roachpb.Error) {
sp, cleanupSp := tracing.SpanFromContext(opReplica, r.store.Tracer(), ctx)
defer cleanupSp()
// If the read is consistent, the read requires the leader lease.
if ba.ReadConsistency != roachpb.INCONSISTENT {
if pErr = r.redirectOnOrAcquireLeaderLease(sp, ctx); pErr != nil {
return nil, pErr
}
}
// Add the read to the command queue to gate subsequent
// overlapping commands until this command completes.
sp.LogEvent("command queue")
endCmdsFunc := r.beginCmds(&ba)
r.readOnlyCmdMu.RLock()
defer r.readOnlyCmdMu.RUnlock()
// Guarantee we remove the commands from the command queue. It is
// important that this is inside the readOnlyCmdMu lock so that the
// timestamp cache update is synchronized. This is wrapped to delay
// pErr evaluation to its value when returning.
defer func() {
endCmdsFunc(pErr)
}()
// Execute read-only batch command. It checks for matching key range; note
// that holding readMu throughout is important to avoid reads from the
// "wrong" key range being served after the range has been split.
var intents []intentsWithArg
br, intents, pErr = r.executeBatch(r.store.Engine(), nil, ba)
if pErr == nil && ba.Txn != nil {
// Checking the sequence cache on reads makes sure that when our
// transaction has already been aborted, we don't experience anomalous
// conditions as described in #2231.
pErr = r.checkSequenceCache(r.store.Engine(), *ba.Txn)
}
r.store.intentResolver.processIntentsAsync(r, intents)
return br, pErr
}
// addWriteCmd first adds the keys affected by this command as pending writes
// to the command queue. Next, the timestamp cache is checked to determine if
// any newer accesses to this command's affected keys have been made. If so,
// the command's timestamp is moved forward. Finally, the command is submitted
// to Raft. Upon completion, the write is removed from the read queue and any
// error returned. If a WaitGroup is supplied, it is signaled when the command
// enters Raft or the function returns with a preprocessing error, whichever
// happens earlier.
func (r *Replica) addWriteCmd(ctx context.Context, ba roachpb.BatchRequest, wg *sync.WaitGroup) (br *roachpb.BatchResponse, pErr *roachpb.Error) {
signal := func() {
if wg != nil {
wg.Done()
wg = nil
}
}
// This happens more eagerly below, but it's important to guarantee that
// early returns do not skip this.
defer signal()
sp, cleanupSp := tracing.SpanFromContext(opReplica, r.store.Tracer(), ctx)
defer cleanupSp()
// Add the write to the command queue to gate subsequent overlapping
// commands until this command completes. Note that this must be
// done before getting the max timestamp for the key(s), as
// timestamp cache is only updated after preceding commands have
// been run to successful completion.
sp.LogEvent("command queue")
endCmdsFunc := r.beginCmds(&ba)
// Guarantee we remove the commands from the command queue. This is
// wrapped to delay pErr evaluation to its value when returning.
defer func() {
endCmdsFunc(pErr)
}()
// This replica must have leader lease to process a write.
if pErr = r.redirectOnOrAcquireLeaderLease(sp, ctx); pErr != nil {
return nil, pErr
}
// Two important invariants of Cockroach: 1) encountering a more
// recently written value means transaction restart. 2) values must
// be written with a greater timestamp than the most recent read to
// the same key. Check the timestamp cache for reads/writes which
// are at least as recent as the timestamp of this write. For
// writes, send WriteTooOldError; for reads, update the write's
// timestamp. When the write returns, the updated timestamp will
// inform the final commit timestamp.
//
// Find the maximum timestamp required to satisfy all requests in
// the batch and then apply that to all requests.
func() {
r.mu.Lock()
defer r.mu.Unlock()
for _, union := range ba.Requests {
args := union.GetInner()
if usesTimestampCache(args) {
header := args.Header()
var txnID *uuid.UUID
if ba.Txn != nil {
txnID = ba.Txn.ID
}