-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
replica_raftstorage.go
874 lines (784 loc) · 28.4 KB
/
replica_raftstorage.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
// Copyright 2015 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: Ben Darnell
package storage
import (
"fmt"
"time"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"github.com/pkg/errors"
"golang.org/x/net/context"
"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/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
// replicaRaftStorage implements the raft.Storage interface.
type replicaRaftStorage Replica
var _ raft.Storage = (*replicaRaftStorage)(nil)
// All calls to raft.RawNode require that both Replica.raftMu and
// Replica.mu are held. All of the functions exposed via the
// raft.Storage interface will in turn be called from RawNode, so none
// of these methods may acquire either lock, but they may require
// their caller to hold one or both locks (even though they do not
// follow our "Locked" naming convention). Specific locking
// requirements are noted in each method's comments.
//
// Many of the methods defined in this file are wrappers around static
// functions. This is done to facilitate their use from
// Replica.Snapshot(), where it is important that all the data that
// goes into the snapshot comes from a consistent view of the
// database, and not the replica's in-memory state or via a reference
// to Replica.store.Engine().
// InitialState implements the raft.Storage interface.
// InitialState requires that r.mu is held.
func (r *replicaRaftStorage) InitialState() (raftpb.HardState, raftpb.ConfState, error) {
ctx := r.AnnotateCtx(context.TODO())
// For uninitialized ranges, membership is unknown at this point.
hs, err := r.mu.stateLoader.loadHardState(ctx, r.store.RaftEngine())
if raft.IsEmptyHardState(hs) || err != nil {
return raftpb.HardState{}, raftpb.ConfState{}, err
}
var cs raftpb.ConfState
for _, rep := range r.mu.state.Desc.Replicas {
cs.Nodes = append(cs.Nodes, uint64(rep.ReplicaID))
}
return hs, cs, nil
}
// Entries implements the raft.Storage interface. Note that maxBytes is advisory
// and this method will always return at least one entry even if it exceeds
// maxBytes. Passing maxBytes equal to zero disables size checking.
func (r *replicaRaftStorage) Entries(lo, hi, maxBytes uint64) ([]raftpb.Entry, error) {
snap := r.store.NewSnapshot()
defer snap.Close()
raftEngSnap := snap
if TransitioningRaftStorage || EnabledRaftStorage {
raftEngSnap = r.store.NewRaftEngineSnapshot()
defer raftEngSnap.Close()
}
ctx := r.AnnotateCtx(context.TODO())
return entries(ctx, snap, raftEngSnap, r.RangeID, r.store.raftEntryCache, lo, hi, maxBytes)
}
// raftEntriesLocked requires that r.mu is held.
func (r *Replica) raftEntriesLocked(lo, hi, maxBytes uint64) ([]raftpb.Entry, error) {
return (*replicaRaftStorage)(r).Entries(lo, hi, maxBytes)
}
func entries(
ctx context.Context,
e engine.Reader,
re engine.Reader,
rangeID roachpb.RangeID,
eCache *raftEntryCache,
lo, hi, maxBytes uint64,
) ([]raftpb.Entry, error) {
if lo > hi {
return nil, errors.Errorf("lo:%d is greater than hi:%d", lo, hi)
}
n := hi - lo
if n > 100 {
n = 100
}
ents := make([]raftpb.Entry, 0, n)
ents, size, hitIndex := eCache.getEntries(ents, rangeID, lo, hi, maxBytes)
// Return results if the correct number of results came back or if
// we ran into the max bytes limit.
if uint64(len(ents)) == hi-lo || (maxBytes > 0 && size > maxBytes) {
return ents, nil
}
// Scan over the log to find the requested entries in the range [lo, hi),
// stopping once we have enough.
expectedIndex := hitIndex
var ent raftpb.Entry
exceededMaxBytes := false
scanFunc := func(kv roachpb.KeyValue) (bool, error) {
if err := kv.Value.GetProto(&ent); err != nil {
return false, err
}
// Exit early if we have any gaps or it has been compacted.
if ent.Index != expectedIndex {
return true, nil
}
expectedIndex++
size += uint64(ent.Size())
ents = append(ents, ent)
exceededMaxBytes = maxBytes > 0 && size > maxBytes
return exceededMaxBytes, nil
}
if err := iterateEntries(ctx, re, rangeID, expectedIndex, hi, scanFunc); err != nil {
return nil, err
}
// Cache the fetched entries.
eCache.addEntries(rangeID, ents)
// Did the correct number of results come back? If so, we're all good.
if uint64(len(ents)) == hi-lo {
return ents, nil
}
// Did we hit the size limit? If so, return what we have.
if exceededMaxBytes {
return ents, nil
}
// Did we get any results at all? Because something went wrong.
if len(ents) > 0 {
// Was the lo already truncated?
if ents[0].Index > lo {
return nil, raft.ErrCompacted
}
// Was the missing index after the last index?
// TODO(irfansharif): Explore writing last index to raft engine.
lastIndex, err := loadLastIndex(ctx, e, rangeID)
if err != nil {
return nil, err
}
if lastIndex <= expectedIndex {
return nil, raft.ErrUnavailable
}
// We have a gap in the record, if so, return a nasty error.
return nil, errors.Errorf("there is a gap in the index record between lo:%d and hi:%d at index:%d", lo, hi, expectedIndex)
}
// No results, was it due to unavailability or truncation?
// TODO(irfansharif): Explore writing truncated state to raft engine.
// Possibly separating out TruncatedState from ReplicaState.
ts, err := loadTruncatedState(ctx, e, rangeID)
if err != nil {
return nil, err
}
if ts.Index >= lo {
// The requested lo index has already been truncated.
return nil, raft.ErrCompacted
}
// The requested lo index does not yet exist.
return nil, raft.ErrUnavailable
}
func iterateEntries(
ctx context.Context,
e engine.Reader,
rangeID roachpb.RangeID,
lo,
hi uint64,
scanFunc func(roachpb.KeyValue) (bool, error),
) error {
_, err := engine.MVCCIterate(
ctx, e,
keys.RaftLogKey(rangeID, lo),
keys.RaftLogKey(rangeID, hi),
hlc.Timestamp{},
true, /* consistent */
nil, /* txn */
false, /* !reverse */
scanFunc,
)
return err
}
// Term implements the raft.Storage interface.
func (r *replicaRaftStorage) Term(i uint64) (uint64, error) {
snap := r.store.NewSnapshot()
defer snap.Close()
raftEngSnap := snap
if TransitioningRaftStorage || EnabledRaftStorage {
raftEngSnap = r.store.NewRaftEngineSnapshot()
defer raftEngSnap.Close()
}
ctx := r.AnnotateCtx(context.TODO())
return term(ctx, snap, raftEngSnap, r.RangeID, r.store.raftEntryCache, i)
}
// raftTermLocked requires that r.mu is held.
func (r *Replica) raftTermLocked(i uint64) (uint64, error) {
return (*replicaRaftStorage)(r).Term(i)
}
func term(
ctx context.Context,
eng, raftEng engine.Reader,
rangeID roachpb.RangeID,
eCache *raftEntryCache,
i uint64,
) (uint64, error) {
ents, err := entries(ctx, eng, raftEng, rangeID, eCache, i, i+1, 0)
if err == raft.ErrCompacted {
ts, err := loadTruncatedState(ctx, eng, rangeID)
if err != nil {
return 0, err
}
if i == ts.Index {
return ts.Term, nil
}
return 0, raft.ErrCompacted
} else if err != nil {
return 0, err
}
if len(ents) == 0 {
return 0, nil
}
return ents[0].Term, nil
}
// LastIndex implements the raft.Storage interface.
func (r *replicaRaftStorage) LastIndex() (uint64, error) {
return r.mu.lastIndex, nil
}
// raftLastIndexLocked requires that r.mu is held.
func (r *Replica) raftLastIndexLocked() (uint64, error) {
return (*replicaRaftStorage)(r).LastIndex()
}
// raftTruncatedStateLocked returns metadata about the log that preceded the
// first current entry. This includes both entries that have been compacted away
// and the dummy entries that make up the starting point of an empty log.
// raftTruncatedStateLocked requires that r.mu is held.
func (r *Replica) raftTruncatedStateLocked(
ctx context.Context,
) (roachpb.RaftTruncatedState, error) {
if r.mu.state.TruncatedState != nil {
return *r.mu.state.TruncatedState, nil
}
ts, err := r.mu.stateLoader.loadTruncatedState(ctx, r.store.Engine())
if err != nil {
return ts, err
}
if ts.Index != 0 {
r.mu.state.TruncatedState = &ts
}
return ts, nil
}
// FirstIndex implements the raft.Storage interface.
func (r *replicaRaftStorage) FirstIndex() (uint64, error) {
ctx := r.AnnotateCtx(context.TODO())
ts, err := (*Replica)(r).raftTruncatedStateLocked(ctx)
if err != nil {
return 0, err
}
return ts.Index + 1, nil
}
// raftFirstIndexLocked requires that r.mu is held.
func (r *Replica) raftFirstIndexLocked() (uint64, error) {
return (*replicaRaftStorage)(r).FirstIndex()
}
// GetFirstIndex is the same function as raftFirstIndexLocked but it requires
// that r.mu is not held.
func (r *Replica) GetFirstIndex() (uint64, error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.raftFirstIndexLocked()
}
// Snapshot implements the raft.Storage interface. Snapshot requires that
// r.mu is held. Note that the returned snapshot is a placeholder and
// does not contain any of the replica data. The snapshot is actually generated
// (and sent) by the Raft snapshot queue.
func (r *replicaRaftStorage) Snapshot() (raftpb.Snapshot, error) {
r.mu.AssertHeld()
appliedIndex := r.mu.state.RaftAppliedIndex
term, err := r.Term(appliedIndex)
if err != nil {
return raftpb.Snapshot{}, err
}
return raftpb.Snapshot{
Metadata: raftpb.SnapshotMetadata{
Index: appliedIndex,
Term: term,
},
}, nil
}
// raftSnapshotLocked requires that r.mu is held.
func (r *Replica) raftSnapshotLocked() (raftpb.Snapshot, error) {
return (*replicaRaftStorage)(r).Snapshot()
}
// GetSnapshot returns a snapshot of the replica appropriate for sending to a
// replica. If this method returns without error, callers must eventually call
// OutgoingSnapshot.Close.
func (r *Replica) GetSnapshot(ctx context.Context, snapType string) (*OutgoingSnapshot, error) {
r.mu.RLock()
defer r.mu.RUnlock()
rangeID := r.RangeID
if r.exceedsDoubleSplitSizeRLocked() {
maxBytes := r.mu.maxBytes
size := r.mu.state.Stats.Total()
err := errors.Errorf(
"%s: not generating %s snapshot because replica is too large: %d > 2 * %d",
r, snapType, size, maxBytes)
return &OutgoingSnapshot{}, err
}
startKey := r.mu.state.Desc.StartKey
ctx, sp := r.AnnotateCtxWithSpan(ctx, "snapshot")
defer sp.Finish()
snap := r.store.NewSnapshot()
log.Eventf(ctx, "new engine snapshot for replica %s", r)
raftEngSnap := snap
if TransitioningRaftStorage || EnabledRaftStorage {
raftEngSnap = r.store.NewRaftEngineSnapshot()
}
// Delegate to a static function to make sure that we do not depend
// on any indirect calls to r.store.Engine() (or other in-memory
// state of the Replica). Everything must come from the snapshot.
snapData, err := snapshot(ctx, snapType, snap, raftEngSnap, rangeID, r.store.raftEntryCache, startKey)
if err != nil {
log.Errorf(ctx, "error generating snapshot: %s", err)
return nil, err
}
return &snapData, nil
}
// OutgoingSnapshot contains the data required to stream a snapshot to a
// recipient. Once one is created, it needs to be closed via Close() to prevent
// resource leakage.
type OutgoingSnapshot struct {
SnapUUID uuid.UUID
// The Raft snapshot message to send. Contains SnapUUID as its data.
RaftSnap raftpb.Snapshot
// The RocksDB snapshots that will be streamed from.
EngineSnap engine.Reader
RaftEngineSnap engine.Reader
// The complete range iterator for the snapshot to stream.
Iter *ReplicaDataIterator
// The replica state within the snapshot.
State storagebase.ReplicaState
}
// Close releases the resources associated with the snapshot.
func (s *OutgoingSnapshot) Close() {
s.Iter.Close()
s.EngineSnap.Close()
if TransitioningRaftStorage || EnabledRaftStorage {
s.RaftEngineSnap.Close()
}
}
// IncomingSnapshot contains the data for an incoming streaming snapshot message.
type IncomingSnapshot struct {
SnapUUID uuid.UUID
// The RocksDB BatchReprs that make up this snapshot.
Batches [][]byte
// The Raft log entries for this snapshot.
LogEntries [][]byte
// The replica state at the time the snapshot was generated (never nil).
State *storagebase.ReplicaState
snapType string
}
// snapshot creates an OutgoingSnapshot containing a rocksdb snapshot for the
// given range. Note that snapshot() is called without Replica.raftMu held.
func snapshot(
ctx context.Context,
snapType string,
snap, raftEngSnap engine.Reader,
rangeID roachpb.RangeID,
eCache *raftEntryCache,
startKey roachpb.RKey,
) (OutgoingSnapshot, error) {
var desc roachpb.RangeDescriptor
// We ignore intents on the range descriptor (consistent=false) because we
// know they cannot be committed yet; operations that modify range
// descriptors resolve their own intents when they commit.
ok, err := engine.MVCCGetProto(ctx, snap, keys.RangeDescriptorKey(startKey),
hlc.MaxTimestamp, false /* !consistent */, nil, &desc)
if err != nil {
return OutgoingSnapshot{}, errors.Errorf("failed to get desc: %s", err)
}
if !ok {
return OutgoingSnapshot{}, errors.Errorf("couldn't find range descriptor")
}
var snapData roachpb.RaftSnapshotData
// Store RangeDescriptor as metadata, it will be retrieved by ApplySnapshot()
snapData.RangeDescriptor = desc
// Read the range metadata from the snapshot instead of the members
// of the Range struct because they might be changed concurrently.
appliedIndex, _, err := loadAppliedIndex(ctx, snap, rangeID)
if err != nil {
return OutgoingSnapshot{}, err
}
// Synthesize our raftpb.ConfState from desc.
var cs raftpb.ConfState
for _, rep := range desc.Replicas {
cs.Nodes = append(cs.Nodes, uint64(rep.ReplicaID))
}
term, err := term(ctx, snap, raftEngSnap, rangeID, eCache, appliedIndex)
if err != nil {
return OutgoingSnapshot{}, errors.Errorf("failed to fetch term of %d: %s", appliedIndex, err)
}
rsl := makeReplicaStateLoader(rangeID)
state, err := rsl.load(ctx, snap, &desc)
if err != nil {
return OutgoingSnapshot{}, err
}
// Intentionally let this iterator and the snapshot escape so that the
// streamer can send chunks from it bit by bit.
iter := NewReplicaDataIterator(&desc, snap, true /* replicatedOnly */)
snapUUID := uuid.MakeV4()
log.Infof(ctx, "generated %s snapshot %s at index %d",
snapType, snapUUID.Short(), appliedIndex)
return OutgoingSnapshot{
EngineSnap: snap,
RaftEngineSnap: raftEngSnap,
Iter: iter,
State: state,
SnapUUID: snapUUID,
RaftSnap: raftpb.Snapshot{
Data: snapUUID.GetBytes(),
Metadata: raftpb.SnapshotMetadata{
Index: appliedIndex,
Term: term,
ConfState: cs,
},
},
}, nil
}
// append the given entries to the raft log. Takes the previous values of
// r.mu.lastIndex and r.mu.raftLogSize, and returns new values. We do this
// rather than modifying them directly because these modifications need to be
// atomic with the commit of the batch. This method requires that r.raftMu is held.
func (r *Replica) append(
ctx context.Context,
batch, raftBatch engine.ReadWriter,
prevLastIndex uint64,
prevRaftLogSize int64,
entries []raftpb.Entry,
) (uint64, int64, error) {
if len(entries) == 0 {
return prevLastIndex, prevRaftLogSize, nil
}
var diff enginepb.MVCCStats
var value roachpb.Value
for i := range entries {
ent := &entries[i]
key := r.raftMu.stateLoader.RaftLogKey(ent.Index)
if err := value.SetProto(ent); err != nil {
return 0, 0, err
}
value.InitChecksum(key)
var err error
if ent.Index > prevLastIndex {
err = engine.MVCCBlindPut(ctx, raftBatch, &diff, key, hlc.Timestamp{}, value, nil /* txn */)
} else {
err = engine.MVCCPut(ctx, raftBatch, &diff, key, hlc.Timestamp{}, value, nil /* txn */)
}
if err != nil {
return 0, 0, err
}
if TransitioningRaftStorage {
var err error
if ent.Index > prevLastIndex {
// We pass in a nil MVCCStats so to not account for this delta
// in raftLogSize. In TransitioningRaftStorage mode log truncations
// are based entirely on the size of the raft log stored in the
// raft specific RocksDB instance.
err = engine.MVCCBlindPut(ctx, batch, nil, key, hlc.Timestamp{}, value, nil /* txn */)
} else {
err = engine.MVCCPut(ctx, batch, nil, key, hlc.Timestamp{}, value, nil /* txn */)
}
if err != nil {
return 0, 0, err
}
}
}
// Delete any previously appended log entries which never committed.
lastIndex := entries[len(entries)-1].Index
for i := lastIndex + 1; i <= prevLastIndex; i++ {
err := engine.MVCCDelete(ctx, raftBatch, &diff, r.raftMu.stateLoader.RaftLogKey(i),
hlc.Timestamp{}, nil /* txn */)
if err != nil {
return 0, 0, err
}
if TransitioningRaftStorage {
err := engine.MVCCDelete(ctx, batch, nil, r.raftMu.stateLoader.RaftLogKey(i),
hlc.Timestamp{}, nil /* txn */)
if err != nil {
return 0, 0, err
}
}
}
if err := r.raftMu.stateLoader.setLastIndex(ctx, batch, lastIndex); err != nil {
return 0, 0, err
}
raftLogSize := prevRaftLogSize + diff.SysBytes
return lastIndex, raftLogSize, nil
}
// updateRangeInfo is called whenever a range is updated by ApplySnapshot
// or is created by range splitting to setup the fields which are
// uninitialized or need updating.
func (r *Replica) updateRangeInfo(desc *roachpb.RangeDescriptor) error {
// RangeMaxBytes should be updated by looking up Zone Config in two cases:
// 1. After applying a snapshot, if the zone config was not updated for
// this key range, then maxBytes of this range will not be updated either.
// 2. After a new range is created by a split, only copying maxBytes from
// the original range wont work as the original and new ranges might belong
// to different zones.
// Load the system config.
cfg, ok := r.store.Gossip().GetSystemConfig()
if !ok {
// This could be before the system config was ever gossiped,
// or it expired. Let the gossip callback set the info.
ctx := r.AnnotateCtx(context.TODO())
log.Warningf(ctx, "no system config available, cannot determine range MaxBytes")
return nil
}
// Find zone config for this range.
zone, err := cfg.GetZoneConfigForKey(desc.StartKey)
if err != nil {
return errors.Errorf("%s: failed to lookup zone config: %s", r, err)
}
r.SetMaxBytes(zone.RangeMaxBytes)
return nil
}
const (
snapTypeRaft = "Raft"
snapTypePreemptive = "preemptive"
)
var disableSnapshotClearRange = false
// TestingSetDisableSnapshotClearRange allows tests to control whether RocksDB
// range tombstones (the ClearRange operation on Engine) may be used in
// snapshots.
//
// TODO(dan): This is exposed while RocksDB doesn't support using range
// tombstones with IngestExternalFile: https://github.com/facebook/rocksdb/issues/2344
func TestingSetDisableSnapshotClearRange(x bool) func() {
saved := disableSnapshotClearRange
disableSnapshotClearRange = x
return func() {
disableSnapshotClearRange = saved
}
}
func clearRangeData(
desc *roachpb.RangeDescriptor, eng, raftEng engine.Engine, batch, raftBatch engine.Batch,
) error {
iter := eng.NewIterator(false)
defer iter.Close()
const metadataRanges = 2
for i, keyRange := range makeAllKeyRanges(desc) {
// The metadata ranges have a relatively small number of keys making usage
// of range tombstones (as created by ClearRange) a pessimization.
var err error
if disableSnapshotClearRange || i < metadataRanges {
err = batch.ClearIterRange(iter, keyRange.start, keyRange.end)
} else {
err = batch.ClearRange(keyRange.start, keyRange.end)
}
if err != nil {
return err
}
}
if TransitioningRaftStorage || EnabledRaftStorage {
raftIter := raftEng.NewIterator(false)
defer raftIter.Close()
for _, keyRange := range makeRaftEngineKeyRanges(desc) {
// The metadata ranges have a relatively small number of keys making usage
// of range tombstones (as created by ClearRange) a pessimization.
if err := raftBatch.ClearIterRange(raftIter, keyRange.start, keyRange.end); err != nil {
return err
}
}
}
return nil
}
// applySnapshot updates the replica based on the given snapshot and associated
// HardState (which may be empty, as Raft may apply some snapshots which don't
// require an update to the HardState). All snapshots must pass through Raft
// for correctness, i.e. the parameters to this method must be taken from
// a raft.Ready. It is the caller's responsibility to call
// r.store.processRangeDescriptorUpdate(r) after a successful applySnapshot.
// This method requires that r.raftMu is held.
func (r *Replica) applySnapshot(
ctx context.Context, inSnap IncomingSnapshot, snap raftpb.Snapshot, hs raftpb.HardState,
) (err error) {
s := *inSnap.State
if s.Desc.RangeID != r.RangeID {
log.Fatalf(ctx, "unexpected range ID %d", s.Desc.RangeID)
}
r.mu.RLock()
raftLogSize := r.mu.raftLogSize
r.mu.RUnlock()
snapType := inSnap.snapType
defer func() {
if err == nil {
if snapType == snapTypeRaft {
r.store.metrics.RangeSnapshotsNormalApplied.Inc(1)
} else {
r.store.metrics.RangeSnapshotsPreemptiveApplied.Inc(1)
}
}
}()
if raft.IsEmptySnap(snap) {
// Raft discarded the snapshot, indicating that our local state is
// already ahead of what the snapshot provides. But we count it for
// stats (see the defer above).
return nil
}
var stats struct {
clear time.Time
batch time.Time
entries time.Time
commit time.Time
}
var size int
for _, b := range inSnap.Batches {
size += len(b)
}
for _, e := range inSnap.LogEntries {
size += len(e)
}
log.Infof(ctx, "applying %s snapshot at index %d "+
"(id=%s, encoded size=%d, %d rocksdb batches, %d log entries)",
snapType, snap.Metadata.Index, inSnap.SnapUUID.Short(),
size, len(inSnap.Batches), len(inSnap.LogEntries))
defer func(start time.Time) {
now := timeutil.Now()
log.Infof(ctx, "applied %s snapshot in %0.0fms [clear=%0.0fms batch=%0.0fms entries=%0.0fms commit=%0.0fms]",
snapType, now.Sub(start).Seconds()*1000,
stats.clear.Sub(start).Seconds()*1000,
stats.batch.Sub(stats.clear).Seconds()*1000,
stats.entries.Sub(stats.batch).Seconds()*1000,
stats.commit.Sub(stats.entries).Seconds()*1000)
}(timeutil.Now())
// Use a more efficient write-only batch because we don't need to do any
// reads from the batch.
batch := r.store.Engine().NewWriteOnlyBatch()
defer batch.Close()
raftBatch := batch
if TransitioningRaftStorage || EnabledRaftStorage {
raftBatch = r.store.RaftEngine().NewWriteOnlyBatch()
defer raftBatch.Close()
}
// Delete everything in the range and recreate it from the snapshot.
// We need to delete any old Raft log entries here because any log entries
// that predate the snapshot will be orphaned and never truncated or GC'd.
if err := clearRangeData(s.Desc, r.store.Engine(), r.store.RaftEngine(), batch, raftBatch); err != nil {
return err
}
stats.clear = timeutil.Now()
// Write the snapshot into the range.
for _, batchRepr := range inSnap.Batches {
if err := batch.ApplyBatchRepr(batchRepr, false); err != nil {
return err
}
}
// The log entries are all written to distinct keys so we can use a
// distinct batch.
distinctBatch := batch.Distinct()
distinctBatchRaft := distinctBatch
if TransitioningRaftStorage || EnabledRaftStorage {
distinctBatchRaft = raftBatch.Distinct()
}
stats.batch = timeutil.Now()
logEntries := make([]raftpb.Entry, len(inSnap.LogEntries))
for i, bytes := range inSnap.LogEntries {
if err := logEntries[i].Unmarshal(bytes); err != nil {
return err
}
}
// Write the snapshot's Raft log into the range.
_, raftLogSize, err = r.append(ctx, distinctBatch, distinctBatchRaft, 0, raftLogSize, logEntries)
if err != nil {
return err
}
stats.entries = timeutil.Now()
// Note that we don't require that Raft supply us with a nonempty HardState
// on a snapshot. We don't want to make that assumption because it's not
// guaranteed by the contract. Raft *must* send us a HardState when it
// increases the committed index as a result of the snapshot, but who is to
// say it isn't going to accept a snapshot which is identical to the current
// state?
if !raft.IsEmptyHardState(hs) {
if TransitioningRaftStorage {
if err := r.raftMu.stateLoader.setHardState(ctx, distinctBatch, hs); err != nil {
return errors.Wrapf(err, "unable to persist HardState %+v", &hs)
}
}
if err := r.raftMu.stateLoader.setHardState(ctx, distinctBatchRaft, hs); err != nil {
return errors.Wrapf(err, "unable to persist HardState %+v", &hs)
}
}
// We need to close the distinct batch and start using the normal batch for
// the read below.
distinctBatch.Close()
if TransitioningRaftStorage || EnabledRaftStorage {
distinctBatchRaft.Close()
}
// As outlined above, last and applied index are the same after applying
// the snapshot (i.e. the snapshot has no uncommitted tail).
if s.RaftAppliedIndex != snap.Metadata.Index {
log.Fatalf(ctx, "snapshot RaftAppliedIndex %d doesn't match its metadata index %d",
s.RaftAppliedIndex, snap.Metadata.Index)
}
// We've written Raft log entries, so we need to sync the WAL.
if err := batch.Commit(syncRaftLog.Get()); err != nil {
return err
}
if TransitioningRaftStorage || EnabledRaftStorage {
if err := raftBatch.Commit(syncRaftLog.Get()); err != nil {
return err
}
}
stats.commit = timeutil.Now()
r.mu.Lock()
// We set the persisted last index to the last applied index. This is
// not a correctness issue, but means that we may have just transferred
// some entries we're about to re-request from the leader and overwrite.
// However, raft.MultiNode currently expects this behaviour, and the
// performance implications are not likely to be drastic. If our
// feelings about this ever change, we can add a LastIndex field to
// raftpb.SnapshotMetadata.
r.mu.lastIndex = s.RaftAppliedIndex
r.mu.raftLogSize = raftLogSize
// Update the range and store stats.
r.store.metrics.subtractMVCCStats(r.mu.state.Stats)
r.store.metrics.addMVCCStats(s.Stats)
r.mu.state = s
r.assertStateLocked(ctx, r.store.Engine())
r.mu.Unlock()
// As the last deferred action after committing the batch, update other
// fields which are uninitialized or need updating. This may not happen
// if the system config has not yet been loaded. While config update
// will correctly set the fields, there is no order guarantee in
// ApplySnapshot.
// TODO: should go through the standard store lock when adding a replica.
if err := r.updateRangeInfo(s.Desc); err != nil {
panic(err)
}
r.setDescWithoutProcessUpdate(s.Desc)
return nil
}
// Raft commands are encoded with a 1-byte version (currently 0), an 8-byte ID,
// followed by the payload. This inflexible encoding is used so we can efficiently
// parse the command id while processing the logs.
// TODO(bdarnell): Is this commandID still appropriate for our needs?
const (
// The prescribed length for each command ID.
raftCommandIDLen = 8
raftCommandEncodingVersion byte = 0
// The no-split bit is now unused, but we still apply the mask to the first
// byte of the command for backward compatibility.
raftCommandNoSplitBit = 1 << 7
raftCommandNoSplitMask = raftCommandNoSplitBit - 1
)
// encode a command ID, an encoded storagebase.RaftCommand, and
// whether the command contains a split.
func encodeRaftCommand(commandID storagebase.CmdIDKey, command []byte) []byte {
if len(commandID) != raftCommandIDLen {
panic(fmt.Sprintf("invalid command ID length; %d != %d", len(commandID), raftCommandIDLen))
}
x := make([]byte, 1, 1+raftCommandIDLen+len(command))
x[0] = raftCommandEncodingVersion
x = append(x, []byte(commandID)...)
x = append(x, command...)
return x
}
// DecodeRaftCommand splits a raftpb.Entry.Data into its commandID and
// command portions. The caller is responsible for checking that the data
// is not empty (which indicates a dummy entry generated by raft rather
// than a real command). Usage is mostly internal to the storage package
// but is exported for use by debugging tools.
func DecodeRaftCommand(data []byte) (storagebase.CmdIDKey, []byte) {
if data[0]&raftCommandNoSplitMask != raftCommandEncodingVersion {
panic(fmt.Sprintf("unknown command encoding version %v", data[0]))
}
return storagebase.CmdIDKey(data[1 : 1+raftCommandIDLen]), data[1+raftCommandIDLen:]
}