forked from ngaut/unistore
/
applier.go
1603 lines (1477 loc) · 46.2 KB
/
applier.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 2019-present PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package raftstore
import (
"bytes"
"fmt"
"time"
"github.com/ngaut/unistore/tikv/dbreader"
"github.com/ngaut/unistore/tikv/mvcc"
"github.com/ngaut/unistore/tikv/raftstore/raftlog"
"github.com/pingcap/badger"
"github.com/pingcap/badger/y"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/eraftpb"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/raft_cmdpb"
rspb "github.com/pingcap/kvproto/pkg/raft_serverpb"
"github.com/pingcap/log"
"github.com/pingcap/tidb/util/codec"
"github.com/uber-go/atomic"
)
const (
DefaultApplyWBSize = 4 * 1024
WriteTypeFlagPut = 'P'
WriteTypeFlagDelete = 'D'
WriteTypeFlagLock = 'L'
WriteTypeFlagRollback = 'R'
)
type pendingCmd struct {
index uint64
term uint64
cb *Callback
}
type pendingCmdQueue struct {
normals []pendingCmd
confChange *pendingCmd
}
func (q *pendingCmdQueue) popNormal(term uint64) *pendingCmd {
if len(q.normals) == 0 {
return nil
}
cmd := &q.normals[0]
if cmd.term > term {
return nil
}
q.normals = q.normals[1:]
return cmd
}
func (q *pendingCmdQueue) appendNormal(cmd pendingCmd) {
q.normals = append(q.normals, cmd)
}
func (q *pendingCmdQueue) takeConfChange() *pendingCmd {
// conf change will not be affected when changing between follower and leader,
// so there is no need to check term.
cmd := q.confChange
q.confChange = nil
return cmd
}
// TODO: seems we don't need to separate conf change from normal entries.
func (q *pendingCmdQueue) setConfChange(cmd *pendingCmd) {
q.confChange = cmd
}
type changePeer struct {
confChange *eraftpb.ConfChange
peer *metapb.Peer
region *metapb.Region
}
type keyRange struct {
startKey []byte
endKey []byte
}
type apply struct {
regionId uint64
term uint64
entries []eraftpb.Entry
}
type applyMetrics struct {
sizeDiffHint uint64
deleteKeysHint uint64
writtenBytes uint64
writtenKeys uint64
}
type applyTaskRes struct {
regionID uint64
applyState applyState
appliedIndexTerm uint64
execResults []execResult
metrics applyMetrics
merged bool
destroyPeerID uint64
}
type execResultChangePeer struct {
cp changePeer
}
type execResultCompactLog struct {
truncatedIndex uint64
firstIndex uint64
}
type execResultSplitRegion struct {
regions []*metapb.Region
derived *metapb.Region
}
type execResultPrepareMerge struct {
region *metapb.Region
state *rspb.MergeState
}
type execResultCommitMerge struct {
region *metapb.Region
source *metapb.Region
}
type execResultRollbackMerge struct {
region *metapb.Region
commit uint64
}
type execResultComputeHash struct {
region *metapb.Region
index uint64
snap *mvcc.DBSnapshot
}
type execResultVerifyHash struct {
index uint64
hash []byte
}
type execResultDeleteRange struct {
ranges []keyRange
}
type execResult = interface{}
type applyResultType int
const (
applyResultTypeNone applyResultType = 0
applyResultTypeExecResult applyResultType = 1
applyResultTypeWaitMergeResource applyResultType = 2
)
type applyResult struct {
tp applyResultType
data interface{}
}
type applyExecContext struct {
index uint64
term uint64
applyState applyState
}
type applyCallback struct {
region *metapb.Region
cbs []*Callback
}
func (c *applyCallback) invokeAll(doneApplyTime time.Time) {
for _, cb := range c.cbs {
if cb != nil {
cb.applyDoneTime = doneApplyTime
cb.wg.Done()
}
}
}
func (c *applyCallback) push(cb *Callback, resp *raft_cmdpb.RaftCmdResponse) {
if cb != nil {
cb.resp = resp
}
c.cbs = append(c.cbs, cb)
}
type proposal struct {
isConfChange bool
index uint64
term uint64
cb *Callback
}
type regionProposal struct {
Id uint64
RegionId uint64
Props []*proposal
}
func newRegionProposal(id uint64, regionId uint64, props []*proposal) *regionProposal {
return ®ionProposal{
Id: id,
RegionId: regionId,
Props: props,
}
}
type registration struct {
id uint64
term uint64
applyState applyState
appliedIndexTerm uint64
region *metapb.Region
}
func newRegistration(peer *Peer) *registration {
return ®istration{
id: peer.PeerId(),
term: peer.Term(),
applyState: peer.Store().applyState,
appliedIndexTerm: peer.Store().appliedIndexTerm,
region: peer.Region(),
}
}
type GenSnapTask struct {
regionID uint64
snapNotifier chan *eraftpb.Snapshot
}
func newGenSnapTask(regionID uint64, notifier chan *eraftpb.Snapshot) *GenSnapTask {
return &GenSnapTask{
regionID: regionID,
snapNotifier: notifier,
}
}
func (t *GenSnapTask) generateAndScheduleSnapshot(regionSched chan<- task, redoIdx uint64) {
regionSched <- task{
tp: taskTypeRegionGen,
data: ®ionTask{
regionId: t.regionID,
notifier: t.snapNotifier,
redoIdx: redoIdx,
},
}
}
type applyMsgs struct {
msgs []Msg
}
func (r *applyMsgs) appendMsg(regionID uint64, msg Msg) {
msg.RegionID = regionID
r.msgs = append(r.msgs, msg)
return
}
type applyContext struct {
tag string
timer *time.Time
regionScheduler chan<- task
applyResCh chan<- Msg
engines *Engines
txn *badger.Txn
cbs []applyCallback
applyTaskResList []*applyTaskRes
execCtx *applyExecContext
wb *WriteBatch
wbLastBytes uint64
wbLastKeys uint64
lastAppliedIndex uint64
committedCount int
// Indicates that WAL can be synchronized when data is written to KV engine.
enableSyncLog bool
// Whether to use the delete range API instead of deleting one by one.
useDeleteRange bool
}
func newApplyContext(tag string, regionScheduler chan<- task, engines *Engines,
applyResCh chan<- Msg, cfg *Config) *applyContext {
return &applyContext{
tag: tag,
regionScheduler: regionScheduler,
engines: engines,
applyResCh: applyResCh,
enableSyncLog: cfg.SyncLog,
useDeleteRange: cfg.UseDeleteRange,
wb: new(WriteBatch),
}
}
/// Prepares for applying entries for `applier`.
///
/// A general apply progress for an applier is:
/// `prepare_for` -> `commit` [-> `commit` ...] -> `finish_for`.
/// After all appliers are handled, `write_to_db` method should be called.
func (ac *applyContext) prepareFor(d *applier) {
if ac.wb == nil {
ac.wb = new(WriteBatch)
ac.wbLastBytes = 0
ac.wbLastKeys = 0
}
ac.cbs = append(ac.cbs, applyCallback{region: d.region})
ac.lastAppliedIndex = d.applyState.appliedIndex
}
/// Commits all changes have done for applier. `persistent` indicates whether
/// write the changes into rocksdb.
///
/// This call is valid only when it's between a `prepare_for` and `finish_for`.
func (ac *applyContext) commit(d *applier) {
if ac.lastAppliedIndex < d.applyState.appliedIndex {
d.writeApplyState(ac.wb)
}
// last_applied_index doesn't need to be updated, set persistent to true will
// force it call `prepare_for` automatically.
ac.commitOpt(d, true)
}
func (ac *applyContext) commitOpt(d *applier, persistent bool) {
d.updateMetrics(ac)
if persistent {
ac.writeToDB()
ac.prepareFor(d)
}
ac.wbLastBytes = uint64(ac.wb.size)
ac.wbLastKeys = uint64(len(ac.wb.entries))
}
/// Writes all the changes into badger.
func (ac *applyContext) writeToDB() {
if ac.wb.size != 0 {
if err := ac.wb.WriteToKV(ac.engines.kv); err != nil {
panic(err)
}
ac.wb.Reset()
ac.wbLastBytes = 0
ac.wbLastKeys = 0
}
doneApply := time.Now()
for _, cb := range ac.cbs {
cb.invokeAll(doneApply)
}
ac.cbs = make([]applyCallback, 0, cap(ac.cbs))
}
/// Finishes `Apply`s for the applier.
func (ac *applyContext) finishFor(d *applier, results []execResult) {
if !d.pendingRemove {
d.writeApplyState(ac.wb)
}
ac.commitOpt(d, false)
res := &applyTaskRes{
regionID: d.region.Id,
applyState: d.applyState,
execResults: results,
metrics: d.metrics,
appliedIndexTerm: d.appliedIndexTerm,
}
ac.applyTaskResList = append(ac.applyTaskResList, res)
}
func (ac *applyContext) deltaBytes() uint64 {
return uint64(ac.wb.size) - ac.wbLastBytes
}
func (ac *applyContext) deltaKeys() uint64 {
return uint64(len(ac.wb.entries)) - ac.wbLastKeys
}
func (ac *applyContext) getTxn() *badger.Txn {
if ac.txn == nil {
ac.txn = ac.engines.kv.DB.NewTransaction(false)
}
return ac.txn
}
func (ac *applyContext) flush() {
// TODO: this check is too hacky, need to be more verbose and less buggy.
t := ac.timer
ac.timer = nil
if t == nil {
return
}
if ac.txn != nil {
ac.txn.Discard()
ac.txn = nil
}
// Write to engine
// raftsotre.sync-log = true means we need prevent data loss when power failure.
// take raft log gc for example, we write kv WAL first, then write raft WAL,
// if power failure happen, raft WAL may synced to disk, but kv WAL may not.
// so we use sync-log flag here.
ac.writeToDB()
if len(ac.applyTaskResList) > 0 {
for i, res := range ac.applyTaskResList {
ac.applyResCh <- NewPeerMsg(MsgTypeApplyRes, res.regionID, res)
ac.applyTaskResList[i] = nil
}
ac.applyTaskResList = ac.applyTaskResList[:0]
}
ac.committedCount = 0
}
/// Calls the callback of `cmd` when the Region is removed.
func notifyRegionRemoved(regionID, peerID uint64, cmd pendingCmd) {
log.S().Debugf("region %d is removed, peerID %d, index %d, term %d", regionID, peerID, cmd.index, cmd.term)
notifyReqRegionRemoved(regionID, cmd.cb)
}
func notifyReqRegionRemoved(regionID uint64, cb *Callback) {
cb.Done(ErrRespRegionNotFound(regionID))
}
/// Calls the callback of `cmd` when it can not be processed further.
func notifyStaleCommand(regionID, peerID, term uint64, cmd pendingCmd) {
log.S().Infof("command is stale, skip. regionID %d, peerID %d, index %d, term %d",
regionID, peerID, cmd.index, cmd.term)
notifyStaleReq(term, cmd.cb)
}
func notifyStaleReq(term uint64, cb *Callback) {
cb.Done(ErrRespStaleCommand(term))
}
/// Checks if a write is needed to be issued before handling the command.
func shouldWriteToEngine(rlog raftlog.RaftLog, wbKeys int) bool {
cmd := rlog.GetRaftCmdRequest()
if cmd == nil {
return false
}
if cmd.AdminRequest != nil {
switch cmd.AdminRequest.CmdType {
case raft_cmdpb.AdminCmdType_ComputeHash, // ComputeHash require an up to date snapshot.
raft_cmdpb.AdminCmdType_CommitMerge, // Merge needs to get the latest apply index.
raft_cmdpb.AdminCmdType_RollbackMerge:
return true
}
}
// Some commands may modify keys covered by the current write batch, so we
// must write the current write batch to the engine first.
for _, req := range cmd.Requests {
if req.DeleteRange != nil {
return true
}
if req.IngestSst != nil {
return true
}
}
return false
}
/// A struct that stores the state related to Merge.
///
/// When executing a `CommitMerge`, the source peer may have not applied
/// to the required index, so the target peer has to abort current execution
/// and wait for it asynchronously.
///
/// When rolling the stack, all states required to recover are stored in
/// this struct.
/// TODO: check whether generator/coroutine is a good choice in this case.
type waitSourceMergeState struct {
/// All of the entries that need to continue to be applied after
/// the source peer has applied its logs.
pendingEntries []eraftpb.Entry
/// All of messages that need to continue to be handled after
/// the source peer has applied its logs and pending entries
/// are all handled.
pendingMsgs []Msg
/// A flag that indicates whether the source peer has applied to the required
/// index. If the source peer is ready, this flag should be set to the region id
/// of source peer.
readyToMerge *atomic.Uint64
/// When handling `CatchUpLogs` message, maybe there is a merge cascade, namely,
/// a source peer to catch up logs whereas the logs contain a `CommitMerge`.
/// In this case, the source peer needs to merge another source peer first, so storing the
/// `CatchUpLogs` message in this field, and once the cascaded merge and all other pending
/// msgs are handled, the source peer will check this field and then send `LogsUpToDate`
/// message to its target peer.
catchUpLogs *catchUpLogs
}
func (s *waitSourceMergeState) String() string {
return fmt.Sprintf("waitSourceMergeState{pending_entries:%d, pending_msgs:%d, ready_to_merge:%d, catch_up_logs:%v}",
len(s.pendingEntries), len(s.pendingMsgs), s.readyToMerge.Load(), s.catchUpLogs != nil)
}
/// The applier of a Region which is responsible for handling committed
/// raft log entries of a Region.
///
/// `Apply` is a term of Raft, which means executing the actual commands.
/// In Raft, once some log entries are committed, for every peer of the Raft
/// group will apply the logs one by one. For write commands, it does write or
/// delete to local engine; for admin commands, it does some meta change of the
/// Raft group.
///
/// The raft worker receives all the apply tasks of different Regions
/// located at this store, and it will get the corresponding applier to
/// handle the apply task to make the code logic more clear.
type applier struct {
id uint64
term uint64
region *metapb.Region
tag string
/// If the applier should be stopped from polling.
/// A applier can be stopped in conf change, merge or requested by destroy message.
stopped bool
/// Set to true when removing itself because of `ConfChangeType::RemoveNode`, and then
/// any following committed logs in same Ready should be applied failed.
pendingRemove bool
/// The commands waiting to be committed and applied
pendingCmds pendingCmdQueue
/// Marks the applier as merged by CommitMerge.
merged bool
/// Indicates the peer is in merging, if that compact log won't be performed.
isMerging bool
/// Records the epoch version after the last merge.
lastMergeVersion uint64
/// A temporary state that keeps track of the progress of the source peer state when
/// CommitMerge is unable to be executed.
waitMergeState *waitSourceMergeState
// ID of last region that reports ready.
readySourceRegion uint64
/// We writes apply_state to KV DB, in one write batch together with kv data.
///
/// If we write it to Raft DB, apply_state and kv data (Put, Delete) are in
/// separate WAL file. When power failure, for current raft log, apply_index may synced
/// to file, but KV data may not synced to file, so we will lose data.
applyState applyState
/// The term of the raft log at applied index.
appliedIndexTerm uint64
// redoIdx is the raft log index starts redo for lockStore.
redoIndex uint64
/// The local metrics, and it will be flushed periodically.
metrics applyMetrics
}
func newApplier(reg *registration) *applier {
return &applier{
id: reg.id,
tag: fmt.Sprintf("[region %d] %d", reg.region.Id, reg.id),
region: reg.region,
applyState: reg.applyState,
appliedIndexTerm: reg.appliedIndexTerm,
term: reg.term,
}
}
/// Handles all the committed_entries, namely, applies the committed entries.
func (a *applier) handleRaftCommittedEntries(aCtx *applyContext, committedEntries []eraftpb.Entry) {
if len(committedEntries) == 0 {
return
}
aCtx.prepareFor(a)
aCtx.committedCount += len(committedEntries)
// If we send multiple ConfChange commands, only first one will be proposed correctly,
// others will be saved as a normal entry with no data, so we must re-propose these
// commands again.
aCtx.committedCount += len(committedEntries)
var results []execResult
for i := range committedEntries {
entry := &committedEntries[i]
if a.pendingRemove {
// This peer is about to be destroyed, skip everything.
break
}
expectedIndex := a.applyState.appliedIndex + 1
if expectedIndex != entry.Index {
// Msg::CatchUpLogs may have arrived before Msg::Apply.
if expectedIndex > entry.GetIndex() && a.isMerging {
log.S().Infof("skip log as it's already applied. region_id %d, peer_id %d, index %d",
a.region.Id, a.id, entry.Index)
continue
}
panic(fmt.Sprintf("%s expect index %d, but got %d", a.tag, expectedIndex, entry.Index))
}
var res applyResult
switch entry.EntryType {
case eraftpb.EntryType_EntryNormal:
res = a.handleRaftEntryNormal(aCtx, entry)
case eraftpb.EntryType_EntryConfChange:
res = a.handleRaftEntryConfChange(aCtx, entry)
}
switch res.tp {
case applyResultTypeNone:
case applyResultTypeExecResult:
results = append(results, res.data)
case applyResultTypeWaitMergeResource:
readyToMerge := res.data.(*atomic.Uint64)
aCtx.committedCount -= len(committedEntries) - i
pendingEntries := make([]eraftpb.Entry, 0, len(committedEntries)-i)
// Note that CommitMerge is skipped when `WaitMergeSource` is returned.
// So we need to enqueue it again and execute it again when resuming.
pendingEntries = append(pendingEntries, committedEntries[i:]...)
aCtx.finishFor(a, results)
a.waitMergeState = &waitSourceMergeState{
pendingEntries: pendingEntries,
readyToMerge: readyToMerge,
}
return
}
}
aCtx.finishFor(a, results)
}
func (a *applier) updateMetrics(aCtx *applyContext) {
a.metrics.writtenBytes += aCtx.deltaBytes()
a.metrics.writtenKeys += aCtx.deltaKeys()
}
func (a *applier) writeApplyState(wb *WriteBatch) {
applyStateKey := y.KeyWithTs(ApplyStateKey(a.region.Id), KvTS)
wb.Set(applyStateKey, a.applyState.Marshal())
}
func (a *applier) handleRaftEntryNormal(aCtx *applyContext, entry *eraftpb.Entry) applyResult {
index := entry.Index
term := entry.Term
if len(entry.Data) > 0 {
var rlog raftlog.RaftLog
if entry.Data[0] == raftlog.CustomRaftLogFlag {
rlog = raftlog.NewCustom(entry.Data)
} else {
cmd := new(raft_cmdpb.RaftCmdRequest)
err := cmd.Unmarshal(entry.Data)
if err != nil {
panic(err)
}
rlog = raftlog.NewRequest(cmd)
}
if shouldWriteToEngine(rlog, len(aCtx.wb.entries)) {
aCtx.commit(a)
}
return a.processRaftCmd(aCtx, index, term, rlog)
}
// when a peer become leader, it will send an empty entry.
a.applyState.appliedIndex = index
a.appliedIndexTerm = term
y.Assert(term > 0)
for {
cmd := a.pendingCmds.popNormal(term - 1)
if cmd == nil {
break
}
// apparently, all the callbacks whose term is less than entry's term are stale.
cb := &aCtx.cbs[len(aCtx.cbs)-1]
cmd.cb.resp = ErrRespStaleCommand(term)
cb.cbs = append(cb.cbs, cmd.cb)
}
return applyResult{}
}
func (a *applier) handleRaftEntryConfChange(aCtx *applyContext, entry *eraftpb.Entry) applyResult {
index := entry.Index
term := entry.Term
confChange := new(eraftpb.ConfChange)
if err := confChange.Unmarshal(entry.Data); err != nil {
panic(err)
}
cmd := new(raft_cmdpb.RaftCmdRequest)
if err := cmd.Unmarshal(confChange.Context); err != nil {
panic(err)
}
result := a.processRaftCmd(aCtx, index, term, raftlog.NewRequest(cmd))
switch result.tp {
case applyResultTypeNone:
// If failed, tell Raft that the `ConfChange` was aborted.
return applyResult{tp: applyResultTypeExecResult, data: &execResultChangePeer{}}
case applyResultTypeExecResult:
cp := result.data.(*execResultChangePeer)
cp.cp.confChange = confChange
return applyResult{tp: applyResultTypeExecResult, data: result.data}
default:
panic("unreachable")
}
}
func (a *applier) findCallback(index, term uint64, isConfChange bool) *Callback {
regionID := a.region.Id
peerID := a.id
if isConfChange {
cmd := a.pendingCmds.takeConfChange()
if cmd == nil {
return nil
}
if cmd.index == index && cmd.term == term {
return cmd.cb
}
notifyStaleCommand(regionID, peerID, term, *cmd)
return nil
}
for {
head := a.pendingCmds.popNormal(term)
if head == nil {
break
}
if head.index == index && head.term == term {
return head.cb
}
// Because of the lack of original RaftCmdRequest, we skip calling
// coprocessor here.
notifyStaleCommand(regionID, peerID, term, *head)
}
return nil
}
func (a *applier) processRaftCmd(aCtx *applyContext, index, term uint64, rlog raftlog.RaftLog) applyResult {
if index == 0 {
panic(fmt.Sprintf("%s process raft cmd need a none zero index", a.tag))
}
isConfChange := GetChangePeerCmd(rlog.GetRaftCmdRequest()) != nil
resp, result := a.applyRaftCmd(aCtx, index, term, rlog)
if result.tp == applyResultTypeWaitMergeResource {
return result
}
log.S().Debugf("applied command. region_id %d, peer_id %d, index %d", a.region.Id, a.id, index)
// TODO: if we have exec_result, maybe we should return this callback too. Outer
// store will call it after handing exec result.
BindRespTerm(resp, term)
cmdCB := a.findCallback(index, term, isConfChange)
aCtx.cbs[len(aCtx.cbs)-1].push(cmdCB, resp)
return result
}
/// Applies raft command.
///
/// An apply operation can fail in the following situations:
/// 1. it encounters an error that will occur on all stores, it can continue
/// applying next entry safely, like epoch not match for example;
/// 2. it encounters an error that may not occur on all stores, in this case
/// we should try to apply the entry again or panic. Considering that this
/// usually due to disk operation fail, which is rare, so just panic is ok.
func (a *applier) applyRaftCmd(aCtx *applyContext, index, term uint64,
rlog raftlog.RaftLog) (*raft_cmdpb.RaftCmdResponse, applyResult) {
// if pending remove, apply should be aborted already.
y.Assert(!a.pendingRemove)
aCtx.execCtx = a.newCtx(index, term)
aCtx.wb.SetSafePoint()
resp, applyResult, err := a.execRaftCmd(aCtx, rlog)
if err != nil {
// clear dirty values.
aCtx.wb.RollbackToSafePoint()
if _, ok := err.(*ErrEpochNotMatch); ok {
log.S().Debugf("epoch not match region_id %d, peer_id %d, err %v", a.region.Id, a.id, err)
} else {
log.S().Errorf("execute raft command region_id %d, peer_id %d, err %v", a.region.Id, a.id, err)
}
resp = ErrResp(err)
}
if applyResult.tp == applyResultTypeWaitMergeResource {
return resp, applyResult
}
a.applyState = aCtx.execCtx.applyState
aCtx.execCtx = nil
a.applyState.appliedIndex = index
a.appliedIndexTerm = term
if applyResult.tp == applyResultTypeExecResult {
switch x := applyResult.data.(type) {
case *execResultChangePeer:
a.region = x.cp.region
case *execResultSplitRegion:
a.region = x.derived
a.metrics.sizeDiffHint = 0
a.metrics.deleteKeysHint = 0
case *execResultPrepareMerge:
a.region = x.region
a.isMerging = true
case *execResultCommitMerge:
a.region = x.region
a.lastMergeVersion = x.region.RegionEpoch.Version
case *execResultRollbackMerge:
a.region = x.region
a.isMerging = false
default:
}
}
return resp, applyResult
}
func (a *applier) clearAllCommandsAsStale() {
for i, cmd := range a.pendingCmds.normals {
notifyStaleCommand(a.region.Id, a.id, a.term, cmd)
a.pendingCmds.normals[i] = pendingCmd{}
}
a.pendingCmds.normals = a.pendingCmds.normals[:0]
if cmd := a.pendingCmds.takeConfChange(); cmd != nil {
notifyStaleCommand(a.region.Id, a.id, a.term, *cmd)
}
}
func (a *applier) newCtx(index, term uint64) *applyExecContext {
return &applyExecContext{
index: index,
term: term,
applyState: a.applyState,
}
}
// Only errors that will also occur on all other stores should be returned.
func (a *applier) execRaftCmd(aCtx *applyContext, rlog raftlog.RaftLog) (
resp *raft_cmdpb.RaftCmdResponse, result applyResult, err error) {
// Include region for epoch not match after merge may cause key not in range.
includeRegion := rlog.Epoch().Ver() >= a.lastMergeVersion
err = checkRegionEpoch(rlog, a.region, includeRegion)
if err != nil {
return
}
req := rlog.GetRaftCmdRequest()
if req.GetAdminRequest() != nil {
return a.execAdminCmd(aCtx, req)
}
resp, result = a.execWriteCmd(aCtx, rlog)
return
}
func (a *applier) execAdminCmd(aCtx *applyContext, req *raft_cmdpb.RaftCmdRequest) (
resp *raft_cmdpb.RaftCmdResponse, result applyResult, err error) {
adminReq := req.AdminRequest
cmdType := adminReq.CmdType
if cmdType != raft_cmdpb.AdminCmdType_CompactLog && cmdType != raft_cmdpb.AdminCmdType_CommitMerge {
log.S().Infof("%s execute admin command. term %d, index %d, command %s",
a.tag, aCtx.execCtx.term, aCtx.execCtx.index, adminReq)
}
var adminResp *raft_cmdpb.AdminResponse
switch cmdType {
case raft_cmdpb.AdminCmdType_ChangePeer:
adminResp, result, err = a.execChangePeer(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_Split:
adminResp, result, err = a.execSplit(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_BatchSplit:
adminResp, result, err = a.execBatchSplit(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_CompactLog:
adminResp, result, err = a.execCompactLog(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_TransferLeader:
err = errors.New("transfer leader won't execute")
case raft_cmdpb.AdminCmdType_ComputeHash:
adminResp, result, err = a.execComputeHash(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_VerifyHash:
adminResp, result, err = a.execVerifyHash(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_PrepareMerge:
adminResp, result, err = a.execPrepareMerge(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_CommitMerge:
adminResp, result, err = a.execCommitMerge(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_RollbackMerge:
adminResp, result, err = a.execRollbackMerge(aCtx, adminReq)
case raft_cmdpb.AdminCmdType_InvalidAdmin:
err = errors.New("unsupported command type")
}
if err != nil {
return
}
adminResp.CmdType = cmdType
resp = newCmdRespForReq(req)
resp.AdminResponse = adminResp
return
}
func (a *applier) execWriteCmd(aCtx *applyContext, rlog raftlog.RaftLog) (
resp *raft_cmdpb.RaftCmdResponse, result applyResult) {
if cl, ok := rlog.(*raftlog.CustomRaftLog); ok {
resp = a.execCustomLog(aCtx, cl)
return
}
req := rlog.GetRaftCmdRequest()
requests := req.GetRequests()
writeCmdOps := createWriteCmdOps(requests)
rangeDeleted := false
for _, op := range writeCmdOps {
switch x := op.(type) {
case *prewriteOp:
a.execPrewrite(aCtx, *x)
case *commitOp:
a.execCommit(aCtx, *x)
case *rollbackOp:
a.execRollback(aCtx, *x)
case *raft_cmdpb.DeleteRangeRequest:
a.execDeleteRange(aCtx, x)
rangeDeleted = true
default:
log.S().Fatalf("invalid input op=%v", x)
}
}
resps := make([]raft_cmdpb.Response, len(requests))
respPtrs := make([]*raft_cmdpb.Response, len(requests))
for i := 0; i < len(resps); i++ {
resp := &resps[i]
resp.CmdType = requests[i].CmdType
respPtrs[i] = resp
}
resp = newCmdRespForReq(req)
resp.Responses = respPtrs
if rangeDeleted {
result = applyResult{
tp: applyResultTypeExecResult,
data: &execResultDeleteRange{},
}
}
return
}
func (a *applier) execCustomLog(actx *applyContext, cl *raftlog.CustomRaftLog) (
resp *raft_cmdpb.RaftCmdResponse) {
var cnt int
switch cl.Type() {
case raftlog.TypePrewrite, raftlog.TypePessimisticLock:
cl.IterateLock(func(key, val []byte) {
actx.wb.SetLock(key, val)
cnt++
})
case raftlog.TypeCommit:
cl.IterateCommit(func(key, val []byte, commitTS uint64) {
a.commitLock(actx, key, val, commitTS)
cnt++
})
case raftlog.TypeRolback:
cl.IterateRollback(func(key []byte, startTS uint64, deleteLock bool) {
actx.wb.Rollback(y.KeyWithTs(key, startTS))
if deleteLock {
actx.wb.DeleteLock(key)
}
cnt++
})
case raftlog.TypePessimisticRollback:
cl.IteratePessimisticRollback(func(key []byte) {
actx.wb.DeleteLock(key)
cnt++
})
}
resp = &raft_cmdpb.RaftCmdResponse{Header: &raft_cmdpb.RaftResponseHeader{}}
resp.Responses = make([]*raft_cmdpb.Response, cnt)
return
}
// every commit must followed with a delete lock.
type commitOp struct {
putWrite *raft_cmdpb.PutRequest
delLock *raft_cmdpb.DeleteRequest
}
// a prewrite may optionally has a put Default.
// a put default must follows a put lock.
type prewriteOp struct {
putDefault *raft_cmdpb.PutRequest // optional
putLock *raft_cmdpb.PutRequest
}
// a Rollback optionally has a delete Default.
type rollbackOp struct {
delDefault *raft_cmdpb.DeleteRequest
putWrite *raft_cmdpb.PutRequest
delLock *raft_cmdpb.DeleteRequest
}
// createWriteCmdOps regroups requests into operations.
func createWriteCmdOps(requests []*raft_cmdpb.Request) (ops []interface{}) {
// If first request is delete write, then this is a GC command, we can ignore it.
if len(requests) > 0 {
if del := requests[0].Delete; del != nil {
if del.Cf == CFWrite {
return
}
}
}
for i := 0; i < len(requests); i++ {
req := requests[i]
switch req.CmdType {