forked from ngaut/unistore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvcc.go
1607 lines (1498 loc) · 46.5 KB
/
mvcc.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 tikv
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"fmt"
"math"
"os"
"sort"
"sync/atomic"
"time"
"unsafe"
"github.com/dgryski/go-farm"
"github.com/ngaut/unistore/config"
"github.com/ngaut/unistore/lockstore"
"github.com/ngaut/unistore/pd"
"github.com/ngaut/unistore/tikv/dbreader"
"github.com/ngaut/unistore/tikv/mvcc"
"github.com/ngaut/unistore/util/lockwaiter"
"github.com/pingcap/badger"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/log"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/store/tikv/oracle"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/codec"
"github.com/pingcap/tidb/util/rowcodec"
"go.uber.org/zap"
)
// MVCCStore is a wrapper of badger.DB to provide MVCC functions.
type MVCCStore struct {
dir string
db *badger.DB
lockStore *lockstore.MemStore
dbWriter mvcc.DBWriter
safePoint *SafePoint
pdClient pd.Client
closeCh chan bool
conf *config.Config
latestTS uint64
lockWaiterManager *lockwaiter.Manager
DeadlockDetectCli *DetectorClient
DeadlockDetectSvr *DetectorServer
}
// NewMVCCStore creates a new MVCCStore
func NewMVCCStore(conf *config.Config, bundle *mvcc.DBBundle, dataDir string, safePoint *SafePoint,
writer mvcc.DBWriter, pdClient pd.Client) *MVCCStore {
store := &MVCCStore{
db: bundle.DB,
dir: dataDir,
lockStore: bundle.LockStore,
safePoint: safePoint,
pdClient: pdClient,
closeCh: make(chan bool),
dbWriter: writer,
conf: conf,
lockWaiterManager: lockwaiter.NewManager(conf),
}
store.DeadlockDetectSvr = NewDetectorServer()
store.DeadlockDetectCli = NewDetectorClient(store.lockWaiterManager, pdClient)
writer.Open()
if pdClient != nil {
// pdClient is nil in unit test.
go store.runUpdateSafePointLoop()
}
return store
}
func (store *MVCCStore) updateLatestTS(ts uint64) {
for {
old := atomic.LoadUint64(&store.latestTS)
if old < ts {
if !atomic.CompareAndSwapUint64(&store.latestTS, old, ts) {
continue
}
}
return
}
}
func (store *MVCCStore) getLatestTS() uint64 {
return atomic.LoadUint64(&store.latestTS)
}
func (store *MVCCStore) Close() error {
store.dbWriter.Close()
close(store.closeCh)
err := store.dumpMemLocks()
if err != nil {
log.Fatal("dump mem locks failed", zap.Error(err))
}
return nil
}
type lockEntryHdr struct {
keyLen uint32
valLen uint32
}
func (store *MVCCStore) dumpMemLocks() error {
tmpFileName := store.dir + "/lock_store.tmp"
f, err := os.OpenFile(tmpFileName, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666)
if err != nil {
return errors.Trace(err)
}
writer := bufio.NewWriter(f)
cnt := 0
it := store.lockStore.NewIterator()
hdrBuf := make([]byte, 8)
hdr := (*lockEntryHdr)(unsafe.Pointer(&hdrBuf[0]))
for it.SeekToFirst(); it.Valid(); it.Next() {
hdr.keyLen = uint32(len(it.Key()))
hdr.valLen = uint32(len(it.Value()))
writer.Write(hdrBuf)
writer.Write(it.Key())
writer.Write(it.Value())
cnt++
}
err = writer.Flush()
if err != nil {
return errors.Trace(err)
}
err = f.Sync()
if err != nil {
return errors.Trace(err)
}
f.Close()
return os.Rename(tmpFileName, store.dir+"/lock_store")
}
func (store *MVCCStore) getDBItems(reqCtx *requestCtx, mutations []*kvrpcpb.Mutation) (items []*badger.Item, err error) {
txn := reqCtx.getDBReader().GetTxn()
keys := make([][]byte, len(mutations))
for i, m := range mutations {
keys[i] = m.Key
}
return txn.MultiGet(keys)
}
func sortMutations(mutations []*kvrpcpb.Mutation) []*kvrpcpb.Mutation {
fn := func(i, j int) bool {
return bytes.Compare(mutations[i].Key, mutations[j].Key) < 0
}
if sort.SliceIsSorted(mutations, fn) {
return mutations
}
sort.Slice(mutations, fn)
return mutations
}
func sortPrewrite(req *kvrpcpb.PrewriteRequest) []*kvrpcpb.Mutation {
if len(req.IsPessimisticLock) == 0 {
return sortMutations(req.Mutations)
}
sorter := pessimisticPrewriteSorter{PrewriteRequest: req}
if sort.IsSorted(sorter) {
return req.Mutations
}
sort.Sort(sorter)
return req.Mutations
}
type pessimisticPrewriteSorter struct {
*kvrpcpb.PrewriteRequest
}
func (sorter pessimisticPrewriteSorter) Less(i, j int) bool {
return bytes.Compare(sorter.Mutations[i].Key, sorter.Mutations[j].Key) < 0
}
func (sorter pessimisticPrewriteSorter) Len() int {
return len(sorter.Mutations)
}
func (sorter pessimisticPrewriteSorter) Swap(i, j int) {
sorter.Mutations[i], sorter.Mutations[j] = sorter.Mutations[j], sorter.Mutations[i]
sorter.IsPessimisticLock[i], sorter.IsPessimisticLock[j] = sorter.IsPessimisticLock[j], sorter.IsPessimisticLock[i]
}
func sortKeys(keys [][]byte) [][]byte {
less := func(i, j int) bool {
return bytes.Compare(keys[i], keys[j]) < 0
}
if sort.SliceIsSorted(keys, less) {
return keys
}
sort.Slice(keys, less)
return keys
}
func (store *MVCCStore) PessimisticLock(reqCtx *requestCtx, req *kvrpcpb.PessimisticLockRequest, resp *kvrpcpb.PessimisticLockResponse) (*lockwaiter.Waiter, error) {
mutations := req.Mutations
if !req.ReturnValues {
mutations = sortMutations(req.Mutations)
}
startTS := req.StartVersion
regCtx := reqCtx.regCtx
hashVals := mutationsToHashVals(mutations)
regCtx.AcquireLatches(hashVals)
defer regCtx.ReleaseLatches(hashVals)
batch := store.dbWriter.NewWriteBatch(startTS, 0, reqCtx.rpcCtx)
var dup bool
for _, m := range mutations {
lock, err := store.checkConflictInLockStore(reqCtx, m, startTS)
if err != nil {
return store.handleCheckPessimisticErr(startTS, err, req.IsFirstLock, req.WaitTimeout)
}
if lock != nil {
if lock.Op != uint8(kvrpcpb.Op_PessimisticLock) {
return nil, errors.New("lock type not match")
}
if lock.ForUpdateTS >= req.ForUpdateTs {
// It's a duplicate command, we can simply return values.
dup = true
break
}
// Single statement rollback key, we can overwrite it.
}
if bytes.Equal(m.Key, req.PrimaryLock) {
txnStatus := store.checkExtraTxnStatus(reqCtx, m.Key, startTS)
if txnStatus.isRollback {
return nil, ErrAlreadyRollback
} else if txnStatus.isOpLockCommitted() {
dup = true
break
}
}
}
items, err := store.getDBItems(reqCtx, mutations)
if err != nil {
return nil, err
}
if !dup {
for i, m := range mutations {
lock, err1 := store.buildPessimisticLock(m, items[i], req)
if err1 != nil {
return nil, err1
}
batch.PessimisticLock(m.Key, lock)
}
err = store.dbWriter.Write(batch)
if err != nil {
return nil, err
}
}
if req.Force {
dbMeta := mvcc.DBUserMeta(items[0].UserMeta())
val, err1 := items[0].ValueCopy(nil)
if err1 != nil {
return nil, err1
}
resp.Value = val
resp.CommitTs = dbMeta.CommitTS()
}
if req.ReturnValues {
for _, item := range items {
if item == nil {
resp.Values = append(resp.Values, nil)
continue
}
val, err1 := item.ValueCopy(nil)
if err1 != nil {
return nil, err1
}
resp.Values = append(resp.Values, val)
}
}
return nil, err
}
// extraTxnStatus can be rollback or Op_Lock that only contains transaction status info, no values.
type extraTxnStatus struct {
commitTS uint64
isRollback bool
}
func (s extraTxnStatus) isOpLockCommitted() bool {
return s.commitTS > 0
}
func (store *MVCCStore) checkExtraTxnStatus(reqCtx *requestCtx, key []byte, startTS uint64) extraTxnStatus {
txn := reqCtx.getDBReader().GetTxn()
txnStatusKey := mvcc.EncodeExtraTxnStatusKey(key, startTS)
item, err := txn.Get(txnStatusKey)
if err != nil {
return extraTxnStatus{}
}
userMeta := mvcc.DBUserMeta(item.UserMeta())
if userMeta.CommitTS() == 0 {
return extraTxnStatus{isRollback: true}
}
return extraTxnStatus{commitTS: userMeta.CommitTS()}
}
func (store *MVCCStore) PessimisticRollback(reqCtx *requestCtx, req *kvrpcpb.PessimisticRollbackRequest) error {
keys := sortKeys(req.Keys)
hashVals := keysToHashVals(keys...)
regCtx := reqCtx.regCtx
regCtx.AcquireLatches(hashVals)
defer regCtx.ReleaseLatches(hashVals)
startTS := req.StartVersion
var batch mvcc.WriteBatch
for _, k := range keys {
lock := store.getLock(reqCtx, k)
if lock != nil &&
lock.Op == uint8(kvrpcpb.Op_PessimisticLock) &&
lock.StartTS == startTS &&
lock.ForUpdateTS <= req.ForUpdateTs {
if batch == nil {
batch = store.dbWriter.NewWriteBatch(startTS, 0, reqCtx.rpcCtx)
}
batch.PessimisticRollback(k)
}
}
var err error
if batch != nil {
err = store.dbWriter.Write(batch)
}
store.lockWaiterManager.WakeUp(startTS, 0, hashVals)
store.DeadlockDetectCli.CleanUp(startTS)
return err
}
func (store *MVCCStore) TxnHeartBeat(reqCtx *requestCtx, req *kvrpcpb.TxnHeartBeatRequest) (lockTTL uint64, err error) {
hashVals := keysToHashVals(req.PrimaryLock)
regCtx := reqCtx.regCtx
regCtx.AcquireLatches(hashVals)
defer regCtx.ReleaseLatches(hashVals)
lock := store.getLock(reqCtx, req.PrimaryLock)
if lock != nil && lock.StartTS == req.StartVersion {
if !bytes.Equal(lock.Primary, req.PrimaryLock) {
return 0, errors.New("heartbeat on non-primary key")
}
if lock.TTL < uint32(req.AdviseLockTtl) {
lock.TTL = uint32(req.AdviseLockTtl)
batch := store.dbWriter.NewWriteBatch(req.StartVersion, 0, reqCtx.rpcCtx)
batch.PessimisticLock(req.PrimaryLock, lock)
err = store.dbWriter.Write(batch)
if err != nil {
return 0, err
}
}
return uint64(lock.TTL), nil
}
return 0, errors.New("lock doesn't exists")
}
// TxnStatus is the result of `CheckTxnStatus` API.
type TxnStatus struct {
commitTS uint64
action kvrpcpb.Action
lockInfo *kvrpcpb.LockInfo
}
func (store *MVCCStore) CheckTxnStatus(reqCtx *requestCtx,
req *kvrpcpb.CheckTxnStatusRequest) (txnStatusRes TxnStatus, err error) {
hashVals := keysToHashVals(req.PrimaryKey)
regCtx := reqCtx.regCtx
regCtx.AcquireLatches(hashVals)
defer regCtx.ReleaseLatches(hashVals)
lock := store.getLock(reqCtx, req.PrimaryKey)
batch := store.dbWriter.NewWriteBatch(req.LockTs, 0, reqCtx.rpcCtx)
if lock != nil && lock.StartTS == req.LockTs {
// For an async-commit lock, never roll it back or push forward it MinCommitTS.
if lock.UseAsyncCommit && !req.ForceSyncCommit {
log.S().Debugf("async commit startTS=%v secondaries=%v minCommitTS=%v", lock.StartTS, lock.Secondaries, lock.MinCommitTS)
return TxnStatus{0, kvrpcpb.Action_NoAction, lock.ToLockInfo(req.PrimaryKey)}, nil
}
// If the lock has already outdated, clean up it.
if uint64(oracle.ExtractPhysical(lock.StartTS))+uint64(lock.TTL) < uint64(oracle.ExtractPhysical(req.CurrentTs)) {
// If the resolving lock and primary lock are both pessimistic type, just pessimistic rollback locks.
if req.ResolvingPessimisticLock && lock.Op == uint8(kvrpcpb.Op_PessimisticLock) {
batch.PessimisticRollback(req.PrimaryKey)
return TxnStatus{0, kvrpcpb.Action_TTLExpirePessimisticRollback, nil}, store.dbWriter.Write(batch)
}
batch.Rollback(req.PrimaryKey, true)
return TxnStatus{0, kvrpcpb.Action_TTLExpireRollback, nil}, store.dbWriter.Write(batch)
}
// If this is a large transaction and the lock is active, push forward the minCommitTS.
// lock.minCommitTS == 0 may be a secondary lock, or not a large transaction.
// For async commit protocol, the minCommitTS is always greater than zero, but async commit will not be a large transaction.
action := kvrpcpb.Action_NoAction
if req.CallerStartTs == maxSystemTS {
action = kvrpcpb.Action_MinCommitTSPushed
} else if lock.MinCommitTS > 0 && !lock.UseAsyncCommit {
action = kvrpcpb.Action_MinCommitTSPushed
// We *must* guarantee the invariance lock.minCommitTS >= callerStartTS + 1
if lock.MinCommitTS < req.CallerStartTs+1 {
lock.MinCommitTS = req.CallerStartTs + 1
// Remove this condition should not affect correctness.
// We do it because pushing forward minCommitTS as far as possible could avoid
// the lock been pushed again several times, and thus reduce write operations.
if lock.MinCommitTS < req.CurrentTs {
lock.MinCommitTS = req.CurrentTs
}
batch.PessimisticLock(req.PrimaryKey, lock)
if err = store.dbWriter.Write(batch); err != nil {
return TxnStatus{0, action, nil}, err
}
}
}
return TxnStatus{0, action, lock.ToLockInfo(req.PrimaryKey)}, nil
}
// The current transaction lock not exists, check the transaction commit info
commitTS, err := store.checkCommitted(reqCtx.getDBReader(), req.PrimaryKey, req.LockTs)
if commitTS > 0 {
return TxnStatus{commitTS, kvrpcpb.Action_NoAction, nil}, nil
}
// Check if the transaction already rollbacked
status := store.checkExtraTxnStatus(reqCtx, req.PrimaryKey, req.LockTs)
if status.isRollback {
return TxnStatus{0, kvrpcpb.Action_NoAction, nil}, nil
}
if status.isOpLockCommitted() {
commitTS = status.commitTS
return TxnStatus{commitTS, kvrpcpb.Action_NoAction, nil}, nil
}
// If current transaction is not prewritted before, it may be pessimistic lock.
// When pessimistic txn rollback statement, it may not leave a 'rollbacked' tombstone.
// Or maybe caused by concurrent prewrite operation.
// Especially in the non-block reading case, the secondary lock is likely to be
// written before the primary lock.
// Currently client will always set this flag to true when resolving locks
if req.RollbackIfNotExist {
if req.ResolvingPessimisticLock {
return TxnStatus{0, kvrpcpb.Action_LockNotExistDoNothing, nil}, nil
}
batch.Rollback(req.PrimaryKey, false)
err = store.dbWriter.Write(batch)
return TxnStatus{0, kvrpcpb.Action_LockNotExistRollback, nil}, nil
}
return TxnStatus{0, kvrpcpb.Action_NoAction, nil}, &ErrTxnNotFound{
PrimaryKey: req.PrimaryKey,
StartTS: req.LockTs,
}
}
// SecondaryLocksStatus is the result of `CheckSecondaryLocksStatus` API.
type SecondaryLocksStatus struct {
locks []*kvrpcpb.LockInfo
commitTS uint64
}
func (store *MVCCStore) CheckSecondaryLocks(reqCtx *requestCtx, keys [][]byte, startTS uint64) (SecondaryLocksStatus, error) {
sortKeys(keys)
hashVals := keysToHashVals(keys...)
log.S().Debugf("%d check secondary %v", startTS, hashVals)
regCtx := reqCtx.regCtx
regCtx.AcquireLatches(hashVals)
defer regCtx.ReleaseLatches(hashVals)
batch := store.dbWriter.NewWriteBatch(startTS, 0, reqCtx.rpcCtx)
locks := make([]*kvrpcpb.LockInfo, 0, len(keys))
for i, key := range keys {
lock := store.getLock(reqCtx, key)
if lock != nil && lock.StartTS == startTS {
if lock.Op == uint8(kvrpcpb.Op_PessimisticLock) {
batch.Rollback(key, true)
err := store.dbWriter.Write(batch)
if err != nil {
return SecondaryLocksStatus{}, err
}
store.lockWaiterManager.WakeUp(startTS, 0, []uint64{hashVals[i]})
store.DeadlockDetectCli.CleanUp(startTS)
return SecondaryLocksStatus{commitTS: 0}, nil
} else {
locks = append(locks, lock.ToLockInfo(key))
}
} else {
commitTS, err := store.checkCommitted(reqCtx.getDBReader(), key, startTS)
if err != nil {
return SecondaryLocksStatus{}, err
}
if commitTS > 0 {
return SecondaryLocksStatus{commitTS: commitTS}, nil
}
status := store.checkExtraTxnStatus(reqCtx, key, startTS)
if status.isOpLockCommitted() {
return SecondaryLocksStatus{commitTS: status.commitTS}, nil
}
if !status.isRollback {
batch.Rollback(key, false)
err = store.dbWriter.Write(batch)
}
return SecondaryLocksStatus{commitTS: 0}, err
}
}
return SecondaryLocksStatus{locks: locks}, nil
}
func (store *MVCCStore) normalizeWaitTime(lockWaitTime int64) time.Duration {
if lockWaitTime > store.conf.PessimisticTxn.WaitForLockTimeout {
lockWaitTime = store.conf.PessimisticTxn.WaitForLockTimeout
}
return time.Duration(lockWaitTime) * time.Millisecond
}
func (store *MVCCStore) handleCheckPessimisticErr(startTS uint64, err error, isFirstLock bool, lockWaitTime int64) (*lockwaiter.Waiter, error) {
if locked, ok := err.(*ErrLocked); ok {
if lockWaitTime != lockwaiter.LockNoWait {
keyHash := farm.Fingerprint64(locked.Key)
waitTimeDuration := store.normalizeWaitTime(lockWaitTime)
lock := locked.Lock
log.S().Debugf("%d blocked by %d on key %d", startTS, lock.StartTS, keyHash)
waiter := store.lockWaiterManager.NewWaiter(startTS, lock.StartTS, keyHash, waitTimeDuration)
if !isFirstLock {
store.DeadlockDetectCli.Detect(startTS, lock.StartTS, keyHash)
}
return waiter, err
}
}
return nil, err
}
func (store *MVCCStore) buildPessimisticLock(m *kvrpcpb.Mutation, item *badger.Item,
req *kvrpcpb.PessimisticLockRequest) (*mvcc.MvccLock, error) {
if item != nil {
userMeta := mvcc.DBUserMeta(item.UserMeta())
if !req.Force {
if userMeta.CommitTS() > req.ForUpdateTs {
return nil, &ErrConflict{
StartTS: req.StartVersion,
ConflictTS: userMeta.StartTS(),
ConflictCommitTS: userMeta.CommitTS(),
Key: item.KeyCopy(nil),
}
}
}
if m.Assertion == kvrpcpb.Assertion_NotExist && !item.IsEmpty() {
return nil, &ErrKeyAlreadyExists{Key: m.Key}
}
}
lock := &mvcc.MvccLock{
MvccLockHdr: mvcc.MvccLockHdr{
StartTS: req.StartVersion,
ForUpdateTS: req.ForUpdateTs,
Op: uint8(kvrpcpb.Op_PessimisticLock),
TTL: uint32(req.LockTtl),
PrimaryLen: uint16(len(req.PrimaryLock)),
},
Primary: req.PrimaryLock,
}
return lock, nil
}
func (store *MVCCStore) Prewrite(reqCtx *requestCtx, req *kvrpcpb.PrewriteRequest) error {
mutations := sortPrewrite(req)
regCtx := reqCtx.regCtx
hashVals := mutationsToHashVals(mutations)
regCtx.AcquireLatches(hashVals)
defer regCtx.ReleaseLatches(hashVals)
isPessimistic := req.ForUpdateTs > 0
var err error
if isPessimistic {
err = store.prewritePessimistic(reqCtx, mutations, req)
} else {
err = store.prewriteOptimistic(reqCtx, mutations, req)
}
if err != nil {
return err
}
if reqCtx.onePCCommitTS != 0 {
// TODO: Is it correct to pass the hashVals directly here, considering that some of the keys may
// have no pessimistic lock?
if isPessimistic {
store.lockWaiterManager.WakeUp(req.StartVersion, reqCtx.onePCCommitTS, hashVals)
store.DeadlockDetectCli.CleanUp(req.StartVersion)
}
}
return nil
}
func (store *MVCCStore) prewriteOptimistic(reqCtx *requestCtx, mutations []*kvrpcpb.Mutation, req *kvrpcpb.PrewriteRequest) error {
startTS := req.StartVersion
// Must check the LockStore first.
for _, m := range mutations {
lock, err := store.checkConflictInLockStore(reqCtx, m, startTS)
if err != nil {
return err
}
if lock != nil {
// duplicated command
return nil
}
if bytes.Equal(m.Key, req.PrimaryLock) {
status := store.checkExtraTxnStatus(reqCtx, m.Key, req.StartVersion)
if status.isRollback {
return ErrAlreadyRollback
}
if status.isOpLockCommitted() {
// duplicated command
return nil
}
}
}
items, err := store.getDBItems(reqCtx, mutations)
if err != nil {
return err
}
for i, m := range mutations {
item := items[i]
if item != nil {
userMeta := mvcc.DBUserMeta(item.UserMeta())
if userMeta.CommitTS() > startTS {
return &ErrConflict{
StartTS: startTS,
ConflictTS: userMeta.StartTS(),
ConflictCommitTS: userMeta.CommitTS(),
Key: item.KeyCopy(nil),
}
}
}
// Op_CheckNotExists type requests should not add lock
if m.Op == kvrpcpb.Op_CheckNotExists {
if item != nil {
val, err := item.Value()
if err != nil {
return err
}
if len(val) > 0 {
return &ErrKeyAlreadyExists{Key: m.Key}
}
}
continue
}
// TODO add memory lock for async commit protocol.
}
return store.prewriteMutations(reqCtx, mutations, req, items)
}
func (store *MVCCStore) prewritePessimistic(reqCtx *requestCtx, mutations []*kvrpcpb.Mutation, req *kvrpcpb.PrewriteRequest) error {
startTS := req.StartVersion
for i, m := range mutations {
if m.Op == kvrpcpb.Op_CheckNotExists {
return ErrInvalidOp{op: m.Op}
}
lock := store.getLock(reqCtx, m.Key)
isPessimisticLock := len(req.IsPessimisticLock) > 0 && req.IsPessimisticLock[i]
lockExists := lock != nil
lockMatch := lockExists && lock.StartTS == startTS
if isPessimisticLock {
valid := lockExists && lockMatch
if !valid {
return errors.New("pessimistic lock not found")
}
if lock.Op != uint8(kvrpcpb.Op_PessimisticLock) {
// Duplicated command.
return nil
}
// Do not overwrite lock ttl if prewrite ttl smaller than pessimisitc lock ttl
if uint64(lock.TTL) > req.LockTtl {
req.LockTtl = uint64(lock.TTL)
}
} else {
// non pessimistic lock in pessimistic transaction, e.g. non-unique index.
valid := !lockExists || lockMatch
if !valid {
// Safe to set TTL to zero because the transaction of the lock is committed
// or rollbacked or must be rollbacked.
lock.TTL = 0
return BuildLockErr(m.Key, lock)
}
if lockMatch {
// Duplicate command.
return nil
}
}
// TODO add memory lock for async commit protocol.
}
items, err := store.getDBItems(reqCtx, mutations)
if err != nil {
return err
}
return store.prewriteMutations(reqCtx, mutations, req, items)
}
func (store *MVCCStore) prewriteMutations(reqCtx *requestCtx, mutations []*kvrpcpb.Mutation,
req *kvrpcpb.PrewriteRequest, items []*badger.Item) error {
var minCommitTS uint64
if req.UseAsyncCommit || req.TryOnePc {
// Get minCommitTS for async commit protocol. After all keys are locked in memory lock.
physical, logical, tsErr := store.pdClient.GetTS(context.Background())
if tsErr != nil {
return tsErr
}
minCommitTS = uint64(physical)<<18 + uint64(logical)
if req.MaxCommitTs > 0 && minCommitTS > req.MaxCommitTs {
req.UseAsyncCommit = false
req.TryOnePc = false
}
if req.UseAsyncCommit {
reqCtx.asyncMinCommitTS = minCommitTS
}
}
if req.UseAsyncCommit && minCommitTS > req.MinCommitTs {
req.MinCommitTs = minCommitTS
}
if req.TryOnePc {
committed, err := store.tryOnePC(reqCtx, mutations, req, items, minCommitTS, req.MaxCommitTs)
if err != nil {
return err
}
// If 1PC succeeded, exit immediately.
if committed {
return nil
}
}
batch := store.dbWriter.NewWriteBatch(req.StartVersion, 0, reqCtx.rpcCtx)
for i, m := range mutations {
if m.Op == kvrpcpb.Op_CheckNotExists {
continue
}
lock, err1 := store.buildPrewriteLock(reqCtx, m, items[i], req)
if err1 != nil {
return err1
}
batch.Prewrite(m.Key, lock)
}
return store.dbWriter.Write(batch)
}
func (store *MVCCStore) tryOnePC(reqCtx *requestCtx, mutations []*kvrpcpb.Mutation,
req *kvrpcpb.PrewriteRequest, items []*badger.Item, minCommitTS uint64, maxCommitTS uint64) (bool, error) {
if maxCommitTS != 0 && minCommitTS > maxCommitTS {
log.Debug("1pc transaction fallbacks due to minCommitTS exceeds maxCommitTS",
zap.Uint64("startTS", req.StartVersion),
zap.Uint64("minCommitTS", minCommitTS),
zap.Uint64("maxCommitTS", maxCommitTS))
return false, nil
}
if minCommitTS < req.StartVersion {
log.Fatal("1pc commitTS less than startTS", zap.Uint64("startTS", req.StartVersion), zap.Uint64("minCommitTS", minCommitTS))
}
reqCtx.onePCCommitTS = minCommitTS
store.updateLatestTS(minCommitTS)
batch := store.dbWriter.NewWriteBatch(req.StartVersion, minCommitTS, reqCtx.rpcCtx)
for i, m := range mutations {
if m.Op == kvrpcpb.Op_CheckNotExists {
continue
}
lock, err1 := store.buildPrewriteLock(reqCtx, m, items[i], req)
if err1 != nil {
return false, err1
}
// batch.Commit will panic if the key is not locked. So there need to be a special function
// for it to commit without deleting lock.
batch.Commit(m.Key, lock)
}
if err := store.dbWriter.Write(batch); err != nil {
return false, err
}
return true, nil
}
func encodeFromOldRow(oldRow, buf []byte) ([]byte, error) {
var (
colIDs []int64
datums []types.Datum
)
for len(oldRow) > 1 {
var d types.Datum
var err error
oldRow, d, err = codec.DecodeOne(oldRow)
if err != nil {
return nil, err
}
colID := d.GetInt64()
oldRow, d, err = codec.DecodeOne(oldRow)
if err != nil {
return nil, err
}
colIDs = append(colIDs, colID)
datums = append(datums, d)
}
var encoder rowcodec.Encoder
return encoder.Encode(&stmtctx.StatementContext{}, colIDs, datums, buf)
}
func (store *MVCCStore) buildPrewriteLock(reqCtx *requestCtx, m *kvrpcpb.Mutation, item *badger.Item,
req *kvrpcpb.PrewriteRequest) (*mvcc.MvccLock, error) {
lock := &mvcc.MvccLock{
MvccLockHdr: mvcc.MvccLockHdr{
StartTS: req.StartVersion,
TTL: uint32(req.LockTtl),
PrimaryLen: uint16(len(req.PrimaryLock)),
MinCommitTS: req.MinCommitTs,
UseAsyncCommit: req.UseAsyncCommit,
SecondaryNum: uint32(len(req.Secondaries)),
},
Primary: req.PrimaryLock,
Value: m.Value,
Secondaries: req.Secondaries,
}
var err error
lock.Op = uint8(m.Op)
if lock.Op == uint8(kvrpcpb.Op_Insert) {
if item != nil && item.ValueSize() > 0 {
return nil, &ErrKeyAlreadyExists{Key: m.Key}
}
lock.Op = uint8(kvrpcpb.Op_Put)
}
if rowcodec.IsRowKey(m.Key) && lock.Op == uint8(kvrpcpb.Op_Put) {
if rowcodec.IsNewFormat(m.Value) {
reqCtx.buf = m.Value
} else {
reqCtx.buf, err = encodeFromOldRow(m.Value, reqCtx.buf)
if err != nil {
log.Error("encode data failed", zap.Binary("value", m.Value), zap.Binary("key", m.Key), zap.Stringer("op", m.Op), zap.Error(err))
return nil, err
}
}
lock.Value = reqCtx.buf
}
lock.ForUpdateTS = req.ForUpdateTs
return lock, nil
}
func (store *MVCCStore) getLock(req *requestCtx, key []byte) *mvcc.MvccLock {
req.buf = store.lockStore.Get(key, req.buf)
if len(req.buf) == 0 {
return nil
}
lock := mvcc.DecodeLock(req.buf)
return &lock
}
func (store *MVCCStore) checkConflictInLockStore(
req *requestCtx, mutation *kvrpcpb.Mutation, startTS uint64) (*mvcc.MvccLock, error) {
req.buf = store.lockStore.Get(mutation.Key, req.buf)
if len(req.buf) == 0 {
return nil, nil
}
lock := mvcc.DecodeLock(req.buf)
if lock.StartTS == startTS {
// Same ts, no need to overwrite.
return &lock, nil
}
return nil, BuildLockErr(mutation.Key, &lock)
}
const maxSystemTS uint64 = math.MaxUint64
// Commit implements the MVCCStore interface.
func (store *MVCCStore) Commit(req *requestCtx, keys [][]byte, startTS, commitTS uint64) error {
sortKeys(keys)
store.updateLatestTS(commitTS)
regCtx := req.regCtx
hashVals := keysToHashVals(keys...)
batch := store.dbWriter.NewWriteBatch(startTS, commitTS, req.rpcCtx)
regCtx.AcquireLatches(hashVals)
defer regCtx.ReleaseLatches(hashVals)
var buf []byte
var tmpDiff int
var isPessimisticTxn bool
for _, key := range keys {
var lockErr error
var checkErr error
var lock mvcc.MvccLock
buf = store.lockStore.Get(key, buf)
if len(buf) == 0 {
// We never commit partial keys in Commit request, so if one lock is not found,
// the others keys must not be found too.
lockErr = ErrLockNotFound
} else {
lock = mvcc.DecodeLock(buf)
if lock.StartTS != startTS {
lockErr = ErrReplaced
}
}
if lockErr != nil {
// Maybe the secondary keys committed by other concurrent transactions using lock resolver,
// check commit info from store
checkErr = store.handleLockNotFound(req, key, startTS, commitTS)
if checkErr == nil {
continue
}
log.Error("commit failed, no correspond lock found",
zap.Binary("key", key), zap.Uint64("start ts", startTS), zap.String("lock", fmt.Sprintf("%v", lock)), zap.Error(lockErr))
return lockErr
}
if commitTS < lock.MinCommitTS {
log.Info("trying to commit with smaller commitTs than minCommitTs",
zap.Uint64("commit ts", commitTS), zap.Uint64("min commit ts", lock.MinCommitTS), zap.Binary("key", key))
return &ErrCommitExpire{
StartTs: startTS,
CommitTs: commitTS,
MinCommitTs: lock.MinCommitTS,
Key: key,
}
}
if lock.Op == uint8(kvrpcpb.Op_PessimisticLock) {
log.Warn("commit a pessimistic lock with Lock type", zap.Binary("key", key), zap.Uint64("start ts", startTS), zap.Uint64("commit ts", commitTS))
lock.Op = uint8(kvrpcpb.Op_Lock)
}
isPessimisticTxn = lock.ForUpdateTS > 0
tmpDiff += len(key) + len(lock.Value)
batch.Commit(key, &lock)
}
atomic.AddInt64(®Ctx.diff, int64(tmpDiff))
err := store.dbWriter.Write(batch)
store.lockWaiterManager.WakeUp(startTS, commitTS, hashVals)
if isPessimisticTxn {
store.DeadlockDetectCli.CleanUp(startTS)
}
return err
}
func (store *MVCCStore) handleLockNotFound(reqCtx *requestCtx, key []byte, startTS, commitTS uint64) error {
txn := reqCtx.getDBReader().GetTxn()
txn.SetReadTS(commitTS)
item, err := txn.Get(key)
if err != nil && err != badger.ErrKeyNotFound {
return errors.Trace(err)
}
if item == nil {
return ErrLockNotFound
}
userMeta := mvcc.DBUserMeta(item.UserMeta())
if userMeta.StartTS() == startTS {
// Already committed.
return nil
}
return ErrLockNotFound
}
const (
rollbackStatusDone = 0
rollbackStatusNoLock = 1
rollbackStatusNewLock = 2
rollbackPessimistic = 3
rollbackStatusLocked = 4
)
func (store *MVCCStore) Rollback(reqCtx *requestCtx, keys [][]byte, startTS uint64) error {
sortKeys(keys)
hashVals := keysToHashVals(keys...)
log.S().Debugf("%d rollback %v", startTS, hashVals)
regCtx := reqCtx.regCtx
batch := store.dbWriter.NewWriteBatch(startTS, 0, reqCtx.rpcCtx)
regCtx.AcquireLatches(hashVals)
defer regCtx.ReleaseLatches(hashVals)
statuses := make([]int, len(keys))
for i, key := range keys {
var rollbackErr error
statuses[i], rollbackErr = store.rollbackKeyReadLock(reqCtx, batch, key, startTS, 0)
if rollbackErr != nil {
return errors.Trace(rollbackErr)
}
}
for i, key := range keys {
status := statuses[i]
if status == rollbackStatusDone || status == rollbackPessimistic {
// rollback pessimistic lock doesn't need to read db.
continue
}
err := store.rollbackKeyReadDB(reqCtx, batch, key, startTS, statuses[i] == rollbackStatusNewLock)
if err != nil {
return err