-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy path2pc.go
More file actions
2390 lines (2150 loc) · 77.2 KB
/
2pc.go
File metadata and controls
2390 lines (2150 loc) · 77.2 KB
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 2021 TiKV 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.
// NOTE: The code in this file is based on code from the
// TiDB project, licensed under the Apache License v 2.0
//
// https://github.com/pingcap/tidb/tree/cc5e161ac06827589c4966674597c137cc9e809c/store/tikv/2pc.go
//
// Copyright 2016 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,
// 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.
package transaction
import (
"bytes"
"context"
errors2 "errors"
"math"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/tikv/client-go/v2/config"
"github.com/tikv/client-go/v2/config/retry"
tikverr "github.com/tikv/client-go/v2/error"
"github.com/tikv/client-go/v2/internal/client"
"github.com/tikv/client-go/v2/internal/latch"
"github.com/tikv/client-go/v2/internal/locate"
"github.com/tikv/client-go/v2/internal/logutil"
"github.com/tikv/client-go/v2/internal/unionstore"
"github.com/tikv/client-go/v2/kv"
"github.com/tikv/client-go/v2/metrics"
"github.com/tikv/client-go/v2/oracle"
"github.com/tikv/client-go/v2/tikvrpc"
"github.com/tikv/client-go/v2/txnkv/txnlock"
"github.com/tikv/client-go/v2/util"
"github.com/tikv/client-go/v2/util/redact"
atomicutil "go.uber.org/atomic"
zap "go.uber.org/zap"
)
// If the duration of a single request exceeds the slowRequestThreshold, a warning log will be logged.
const slowRequestThreshold = time.Minute
type twoPhaseCommitAction interface {
handleSingleBatch(*twoPhaseCommitter, *retry.Backoffer, batchMutations) error
tiKVTxnRegionsNumHistogram() prometheus.Observer
isInterruptible() bool
String() string
}
// Global variable set by config file.
var (
ManagedLockTTL uint64 = 20000 // 20s
MaxPipelinedTxnTTL uint64 = 24 * 60 * 60 * 1000 // 24h
)
var (
// PrewriteMaxBackoff is max sleep time of the `pre-write` command.
PrewriteMaxBackoff = atomicutil.NewUint64(40000)
// CommitMaxBackoff is max sleep time of the 'commit' command
CommitMaxBackoff = uint64(40000)
)
type kvstore interface {
// GetRegionCache gets the RegionCache.
GetRegionCache() *locate.RegionCache
// SplitRegions splits regions by splitKeys.
SplitRegions(ctx context.Context, splitKeys [][]byte, scatter bool, tableID *int64) (regionIDs []uint64, err error)
// WaitScatterRegionFinish implements SplittableStore interface.
// backOff is the back off time of the wait scatter region.(Milliseconds)
// if backOff <= 0, the default wait scatter back off time will be used.
WaitScatterRegionFinish(ctx context.Context, regionID uint64, backOff int) error
// GetTimestampWithRetry returns latest timestamp.
GetTimestampWithRetry(bo *retry.Backoffer, scope string) (uint64, error)
// GetOracle gets a timestamp oracle client.
GetOracle() oracle.Oracle
CurrentTimestamp(txnScope string) (uint64, error)
// SendReq sends a request to TiKV.
SendReq(bo *retry.Backoffer, req *tikvrpc.Request, regionID locate.RegionVerID, timeout time.Duration) (*tikvrpc.Response, error)
// GetTiKVClient gets the client instance.
GetTiKVClient() (client client.Client)
GetLockResolver() *txnlock.LockResolver
Ctx() context.Context
WaitGroup() *sync.WaitGroup
// TxnLatches returns txnLatches.
TxnLatches() *latch.LatchesScheduler
GetClusterID() uint64
// IsClose checks whether the store is closed.
IsClose() bool
// Go run the function in a separate goroutine.
Go(f func()) error
// IsActiveActiveCommitSupportDisabled indicates whether to disable active-active commit support.
// The default value is false, which disables the async-commit and 1PC to ensure the commit timestamp should
// always follow the constraint by PD settings `tso-unique-index`.
IsActiveActiveCommitSupportDisabled() bool
}
// twoPhaseCommitter executes a two-phase commit protocol.
type twoPhaseCommitter struct {
store kvstore
txn *KVTxn
startTS uint64
mutations *memBufferMutations
lockTTL uint64
commitTS uint64
priority kvrpcpb.CommandPri
sessionID uint64 // sessionID is used for log.
cleanWg sync.WaitGroup
detail unsafe.Pointer
txnSize int
hasNoNeedCommitKeys bool
resourceGroupName string
primaryKey []byte
forUpdateTS uint64
maxLockedWithConflictTS uint64
mu struct {
sync.RWMutex
undeterminedErr error // undeterminedErr saves the rpc error we encounter when commit primary key.
committed bool
}
syncLog bool
// For pessimistic transaction
isPessimistic bool
isFirstLock bool
// regionTxnSize stores the number of keys involved in each region
regionTxnSize map[uint64]int
// Used by pessimistic transaction and large transaction.
ttlManager
testingKnobs struct {
acAfterCommitPrimary chan struct{}
bkAfterCommitPrimary chan struct{}
noFallBack bool
}
useAsyncCommit uint32
minCommitTSMgr *minCommitTsManager
maxCommitTS uint64
prewriteStarted bool
prewriteCancelled uint32
useOnePC uint32
onePCCommitTS uint64
hasTriedAsyncCommit bool
hasTriedOnePC bool
binlog BinlogExecutor
resourceGroupTag []byte
resourceGroupTagger tikvrpc.ResourceGroupTagger // use this when resourceGroupTag is nil
// allowed when tikv disk full happened.
diskFullOpt kvrpcpb.DiskFullOpt
// txnSource is used to record the source of the transaction.
txnSource uint64
// The total number of kv request after batch split.
prewriteTotalReqNum int
// assertion error happened when initializing mutations, could be false positive if pessimistic lock is lost
stashedAssertionError error
// isInternal means it's related to an internal transaction. It's only used by `asyncPessimisticRollback` as the
// committer may contain a nil `txn` pointer.
isInternal bool
forUpdateTSConstraints map[string]uint64
pipelinedCommitInfo struct {
primaryOp kvrpcpb.Op
pipelinedStart, pipelinedEnd []byte
}
}
type memBufferMutations struct {
storage *unionstore.MemDB
// The format to put to the UserData of the handles:
// MSB LSB
// [12 bits: Op][1 bit: NeedConstraintCheckInPrewrite][1 bit: assertNotExist][1 bit: assertExist][1 bit: isPessimisticLock]
handles []unionstore.MemKeyHandle
}
func newMemBufferMutations(sizeHint int, storage *unionstore.MemDB) *memBufferMutations {
return &memBufferMutations{
handles: make([]unionstore.MemKeyHandle, 0, sizeHint),
storage: storage,
}
}
func (m *memBufferMutations) Len() int {
return len(m.handles)
}
func (m *memBufferMutations) GetKey(i int) []byte {
return m.storage.GetKeyByHandle(m.handles[i])
}
func (m *memBufferMutations) GetKeys() [][]byte {
ret := make([][]byte, m.Len())
for i := range ret {
ret[i] = m.GetKey(i)
}
return ret
}
func (m *memBufferMutations) GetValue(i int) []byte {
v, _ := m.storage.GetValueByHandle(m.handles[i])
return v
}
func (m *memBufferMutations) GetOp(i int) kvrpcpb.Op {
return kvrpcpb.Op(m.handles[i].UserData >> 4)
}
func (m *memBufferMutations) IsPessimisticLock(i int) bool {
return m.handles[i].UserData&1 != 0
}
func (m *memBufferMutations) IsAssertExists(i int) bool {
return m.handles[i].UserData&(1<<1) != 0
}
func (m *memBufferMutations) IsAssertNotExist(i int) bool {
return m.handles[i].UserData&(1<<2) != 0
}
func (m *memBufferMutations) NeedConstraintCheckInPrewrite(i int) bool {
return m.handles[i].UserData&(1<<3) != 0
}
func (m *memBufferMutations) Slice(from, to int) CommitterMutations {
return &memBufferMutations{
handles: m.handles[from:to],
storage: m.storage,
}
}
func (m *memBufferMutations) Push(op kvrpcpb.Op, isPessimisticLock, assertExist, assertNotExist, NeedConstraintCheckInPrewrite bool,
handle unionstore.MemKeyHandle) {
// See comments of `m.handles` field about the format of the user data `aux`.
aux := uint16(op) << 4
if isPessimisticLock {
aux |= 1
}
if assertExist {
aux |= 1 << 1
}
if assertNotExist {
aux |= 1 << 2
}
if NeedConstraintCheckInPrewrite {
aux |= 1 << 3
}
handle.UserData = aux
m.handles = append(m.handles, handle)
}
// CommitterMutationFlags represents various bit flags of mutations.
type CommitterMutationFlags uint8
const (
// MutationFlagIsPessimisticLock is the flag that marks a mutation needs to be pessimistic-locked.
MutationFlagIsPessimisticLock CommitterMutationFlags = 1 << iota
// MutationFlagIsAssertExists is the flag that marks a mutation needs to be asserted to be existed when prewriting.
MutationFlagIsAssertExists
// MutationFlagIsAssertNotExists is the flag that marks a mutation needs to be asserted to be not-existed when prewriting.
MutationFlagIsAssertNotExists
// MutationFlagNeedConstraintCheckInPrewrite is the flag that marks a mutation needs to be checked for conflicts in prewrite.
MutationFlagNeedConstraintCheckInPrewrite
)
func makeMutationFlags(isPessimisticLock, assertExist, assertNotExist, NeedConstraintCheckInPrewrite bool) CommitterMutationFlags {
var flags CommitterMutationFlags = 0
if isPessimisticLock {
flags |= MutationFlagIsPessimisticLock
}
if assertExist {
flags |= MutationFlagIsAssertExists
}
if assertNotExist {
flags |= MutationFlagIsAssertNotExists
}
if NeedConstraintCheckInPrewrite {
flags |= MutationFlagNeedConstraintCheckInPrewrite
}
return flags
}
// CommitterMutations contains the mutations to be submitted.
type CommitterMutations interface {
Len() int
GetKey(i int) []byte
GetKeys() [][]byte
GetOp(i int) kvrpcpb.Op
GetValue(i int) []byte
IsPessimisticLock(i int) bool
Slice(from, to int) CommitterMutations
IsAssertExists(i int) bool
IsAssertNotExist(i int) bool
NeedConstraintCheckInPrewrite(i int) bool
}
// PlainMutations contains transaction operations.
type PlainMutations struct {
ops []kvrpcpb.Op
keys [][]byte
values [][]byte
flags []CommitterMutationFlags
}
// NewPlainMutations creates a PlainMutations object with sizeHint reserved.
func NewPlainMutations(sizeHint int) PlainMutations {
return PlainMutations{
ops: make([]kvrpcpb.Op, 0, sizeHint),
keys: make([][]byte, 0, sizeHint),
values: make([][]byte, 0, sizeHint),
flags: make([]CommitterMutationFlags, 0, sizeHint),
}
}
// Slice return a sub mutations in range [from, to).
func (c *PlainMutations) Slice(from, to int) CommitterMutations {
var res PlainMutations
res.keys = c.keys[from:to]
if c.ops != nil {
res.ops = c.ops[from:to]
}
if c.values != nil {
res.values = c.values[from:to]
}
if c.flags != nil {
res.flags = c.flags[from:to]
}
return &res
}
// Push another mutation into mutations.
func (c *PlainMutations) Push(op kvrpcpb.Op, key []byte, value []byte, isPessimisticLock, assertExist,
assertNotExist, NeedConstraintCheckInPrewrite bool) {
c.ops = append(c.ops, op)
c.keys = append(c.keys, key)
c.values = append(c.values, value)
c.flags = append(c.flags, makeMutationFlags(isPessimisticLock, assertExist, assertNotExist, NeedConstraintCheckInPrewrite))
}
// Len returns the count of mutations.
func (c *PlainMutations) Len() int {
return len(c.keys)
}
// GetKey returns the key at index.
func (c *PlainMutations) GetKey(i int) []byte {
return c.keys[i]
}
// GetKeys returns the keys.
func (c *PlainMutations) GetKeys() [][]byte {
return c.keys
}
// GetOps returns the key ops.
func (c *PlainMutations) GetOps() []kvrpcpb.Op {
return c.ops
}
// GetValues returns the key values.
func (c *PlainMutations) GetValues() [][]byte {
return c.values
}
// GetFlags returns the flags on the mutations.
func (c *PlainMutations) GetFlags() []CommitterMutationFlags {
return c.flags
}
// IsAssertExists returns the key assertExist flag at index.
func (c *PlainMutations) IsAssertExists(i int) bool {
return c.flags[i]&MutationFlagIsAssertExists != 0
}
// IsAssertNotExist returns the key assertNotExist flag at index.
func (c *PlainMutations) IsAssertNotExist(i int) bool {
return c.flags[i]&MutationFlagIsAssertNotExists != 0
}
// NeedConstraintCheckInPrewrite returns the key NeedConstraintCheckInPrewrite flag at index.
func (c *PlainMutations) NeedConstraintCheckInPrewrite(i int) bool {
return c.flags[i]&MutationFlagNeedConstraintCheckInPrewrite != 0
}
// GetOp returns the key op at index.
func (c *PlainMutations) GetOp(i int) kvrpcpb.Op {
return c.ops[i]
}
// GetValue returns the key value at index.
func (c *PlainMutations) GetValue(i int) []byte {
if len(c.values) <= i {
return nil
}
return c.values[i]
}
// IsPessimisticLock returns the key pessimistic flag at index.
func (c *PlainMutations) IsPessimisticLock(i int) bool {
return c.flags[i]&MutationFlagIsPessimisticLock != 0
}
// PlainMutation represents a single transaction operation.
type PlainMutation struct {
KeyOp kvrpcpb.Op
Key []byte
Value []byte
Flags CommitterMutationFlags
}
// MergeMutations append input mutations into current mutations.
func (c *PlainMutations) MergeMutations(mutations PlainMutations) {
c.ops = append(c.ops, mutations.ops...)
c.keys = append(c.keys, mutations.keys...)
c.values = append(c.values, mutations.values...)
c.flags = append(c.flags, mutations.flags...)
}
// AppendMutation merges a single Mutation into the current mutations.
func (c *PlainMutations) AppendMutation(mutation PlainMutation) {
c.ops = append(c.ops, mutation.KeyOp)
c.keys = append(c.keys, mutation.Key)
c.values = append(c.values, mutation.Value)
c.flags = append(c.flags, mutation.Flags)
}
// newTwoPhaseCommitter creates a twoPhaseCommitter.
func newTwoPhaseCommitter(txn *KVTxn, sessionID uint64) (*twoPhaseCommitter, error) {
committer := &twoPhaseCommitter{
store: txn.store,
txn: txn,
startTS: txn.StartTS(),
sessionID: sessionID,
regionTxnSize: map[uint64]int{},
isPessimistic: txn.IsPessimistic(),
binlog: txn.binlog,
diskFullOpt: kvrpcpb.DiskFullOpt_NotAllowedOnFull,
resourceGroupName: txn.resourceGroupName,
minCommitTSMgr: newMinCommitTsManager(),
}
return committer, nil
}
func (c *twoPhaseCommitter) extractKeyExistsErr(err *tikverr.ErrKeyExist) error {
c.txn.GetMemBuffer().RLock()
defer c.txn.GetMemBuffer().RUnlock()
if !c.txn.us.HasPresumeKeyNotExists(err.GetKey()) {
return errors.Errorf("session %d, existErr for key:%s should not be nil", c.sessionID, redact.Key(err.GetKey()))
}
return errors.WithStack(err)
}
// KVFilter is a filter that filters out unnecessary KV pairs.
type KVFilter interface {
// IsUnnecessaryKeyValue returns whether this KV pair should be committed.
IsUnnecessaryKeyValue(key, value []byte, flags kv.KeyFlags) (bool, error)
}
func (c *twoPhaseCommitter) checkAssertionByPessimisticLockResults(ctx context.Context, key []byte, flags kv.KeyFlags, mustExist, mustNotExist bool) error {
var assertionFailed *tikverr.ErrAssertionFailed
if flags.HasLockedValueExists() && mustNotExist {
assertionFailed = &tikverr.ErrAssertionFailed{
AssertionFailed: &kvrpcpb.AssertionFailed{
StartTs: c.startTS,
Key: key,
Assertion: kvrpcpb.Assertion_NotExist,
ExistingStartTs: 0,
ExistingCommitTs: 0,
},
}
} else if !flags.HasLockedValueExists() && mustExist {
assertionFailed = &tikverr.ErrAssertionFailed{
AssertionFailed: &kvrpcpb.AssertionFailed{
StartTs: c.startTS,
Key: key,
Assertion: kvrpcpb.Assertion_Exist,
ExistingStartTs: 0,
ExistingCommitTs: 0,
},
}
}
if assertionFailed != nil {
err := c.checkSchemaOnAssertionFail(ctx, assertionFailed)
if errors2.Is(err, assertionFailed) {
logutil.Logger(ctx).Error("assertion failed when checking by pessimistic lock results")
}
return err
}
return nil
}
func (c *twoPhaseCommitter) checkSchemaOnAssertionFail(ctx context.Context, assertionFailed *tikverr.ErrAssertionFailed) error {
// If the schema has changed, it might be a false-positive. In this case we should return schema changed, which
// is a usual case, instead of assertion failed.
ts, err := c.store.GetTimestampWithRetry(retry.NewBackofferWithVars(ctx, TsoMaxBackoff, c.txn.vars), c.txn.GetScope())
if err != nil {
return err
}
err = c.checkSchemaValid(ctx, ts, c.txn.schemaVer)
if err != nil {
return err
}
return assertionFailed
}
func (c *twoPhaseCommitter) initKeysAndMutations(ctx context.Context) error {
var size, putCnt, delCnt, lockCnt, checkCnt int
txn := c.txn
memBuf := txn.GetMemBuffer().GetMemDB()
sizeHint := txn.us.GetMemBuffer().Len()
c.mutations = newMemBufferMutations(sizeHint, memBuf)
c.isPessimistic = txn.IsPessimistic()
filter := txn.kvFilter
var err error
var assertionError error
for it := memBuf.IterWithFlags(nil, nil); it.Valid(); err = it.Next() {
_ = err
key := it.Key()
flags := it.Flags()
var value []byte
var op kvrpcpb.Op
if !it.HasValue() {
if !flags.HasLocked() {
continue
}
op = kvrpcpb.Op_Lock
lockCnt++
} else {
value = it.Value()
var isUnnecessaryKV bool
if filter != nil {
isUnnecessaryKV, err = filter.IsUnnecessaryKeyValue(key, value, flags)
if err != nil {
return err
}
}
if len(value) > 0 {
if isUnnecessaryKV {
if !flags.HasLocked() {
continue
}
// If the key was locked before, we should prewrite the lock even if
// the KV needn't be committed according to the filter. Otherwise, we
// were forgetting removing pessimistic locks added before.
op = kvrpcpb.Op_Lock
lockCnt++
} else {
op = kvrpcpb.Op_Put
if flags.HasPresumeKeyNotExists() {
op = kvrpcpb.Op_Insert
}
putCnt++
}
} else {
if isUnnecessaryKV {
continue
}
if !txn.IsPessimistic() && flags.HasPresumeKeyNotExists() {
// delete-your-writes keys in optimistic txn need check not exists in prewrite-phase
// due to `Op_CheckNotExists` doesn't prewrite lock, so mark those keys should not be used in commit-phase.
op = kvrpcpb.Op_CheckNotExists
checkCnt++
memBuf.UpdateFlags(key, kv.SetPrewriteOnly)
} else {
if flags.HasNewlyInserted() {
// The delete-your-write keys in pessimistic transactions, only lock needed keys and skip
// other deletes for example the secondary index delete.
// Here if `tidb_constraint_check_in_place` is enabled and the transaction is in optimistic mode,
// the logic is same as the pessimistic mode.
if flags.HasLocked() {
op = kvrpcpb.Op_Lock
lockCnt++
} else {
continue
}
} else {
op = kvrpcpb.Op_Del
delCnt++
}
}
}
}
var isPessimistic bool
if flags.HasLocked() {
isPessimistic = c.isPessimistic
}
mustExist, mustNotExist, hasAssertUnknown := flags.HasAssertExist(), flags.HasAssertNotExist(), flags.HasAssertUnknown()
if c.txn.assertionLevel == kvrpcpb.AssertionLevel_Off {
mustExist, mustNotExist, hasAssertUnknown = false, false, false
}
c.mutations.Push(op, isPessimistic, mustExist, mustNotExist, flags.HasNeedConstraintCheckInPrewrite(), it.Handle())
size += len(key) + len(value)
if c.txn.assertionLevel != kvrpcpb.AssertionLevel_Off {
// Check mutations for pessimistic-locked keys with the read results of pessimistic lock requests.
// This can be disabled by failpoint.
skipCheckFromLock := false
if _, err := util.EvalFailpoint("assertionSkipCheckFromLock"); err == nil {
skipCheckFromLock = true
}
if isPessimistic && !skipCheckFromLock {
err1 := c.checkAssertionByPessimisticLockResults(ctx, key, flags, mustExist, mustNotExist)
// Do not exit immediately here. To rollback the pessimistic locks (if any), we need to finish
// collecting all the keys.
// Keep only the first assertion error.
// assertion errors is treated differently from other errors. If there is an assertion error,
// it's probably cause by loss of pessimistic locks, so we can't directly return the assertion error.
// Instead, we stash the error, forbid async commit and 1PC, then let the prewrite continue.
// If the prewrite requests all succeed, the assertion error is returned, otherwise return the error
// from the prewrite phase.
if err1 != nil && assertionError == nil {
assertionError = errors.WithStack(err1)
c.stashedAssertionError = assertionError
c.txn.enableAsyncCommit = false
c.txn.enable1PC = false
}
}
// Update metrics
if mustExist {
metrics.PrewriteAssertionUsageCounterExist.Inc()
} else if mustNotExist {
metrics.PrewriteAssertionUsageCounterNotExist.Inc()
} else if hasAssertUnknown {
metrics.PrewriteAssertionUsageCounterUnknown.Inc()
} else {
metrics.PrewriteAssertionUsageCounterNone.Inc()
}
}
if len(c.primaryKey) == 0 && op != kvrpcpb.Op_CheckNotExists {
c.primaryKey = key
}
}
if c.mutations.Len() == 0 {
return nil
}
c.txnSize = size
const logEntryCount = 10000
const logSize = 4 * 1024 * 1024 // 4MB
if c.mutations.Len() > logEntryCount || size > logSize {
logutil.BgLogger().Info("[BIG_TXN]",
zap.Uint64("session", c.sessionID),
zap.String("key sample", redact.Key(c.mutations.GetKey(0))),
zap.Int("size", size),
zap.Int("keys", c.mutations.Len()),
zap.Int("puts", putCnt),
zap.Int("dels", delCnt),
zap.Int("locks", lockCnt),
zap.Int("checks", checkCnt),
zap.Uint64("txnStartTS", txn.startTS))
}
// Sanity check for startTS.
if txn.StartTS() == math.MaxUint64 {
err = errors.Errorf("try to commit with invalid txnStartTS: %d", txn.StartTS())
logutil.BgLogger().Error("commit failed",
zap.Uint64("session", c.sessionID),
zap.Error(err))
return err
}
commitDetail := &util.CommitDetails{
WriteSize: size,
WriteKeys: c.mutations.Len(),
ResolveLock: util.ResolveLockDetail{},
}
isInternalReq := util.IsInternalRequest(c.txn.GetRequestSource())
if isInternalReq {
metrics.TxnWriteKVCountHistogramInternal.Observe(float64(commitDetail.WriteKeys))
metrics.TxnWriteSizeHistogramInternal.Observe(float64(commitDetail.WriteSize))
} else {
metrics.TxnWriteKVCountHistogramGeneral.Observe(float64(commitDetail.WriteKeys))
metrics.TxnWriteSizeHistogramGeneral.Observe(float64(commitDetail.WriteSize))
}
c.hasNoNeedCommitKeys = checkCnt > 0
c.lockTTL = txnLockTTL(txn.startTime, size)
c.priority = txn.priority.ToPB()
c.syncLog = txn.syncLog
c.resourceGroupTag = txn.resourceGroupTag
c.resourceGroupTagger = txn.resourceGroupTagger
c.resourceGroupName = txn.resourceGroupName
c.setDetail(commitDetail)
return nil
}
func (c *twoPhaseCommitter) primary() []byte {
if len(c.primaryKey) == 0 {
if c.mutations != nil {
return c.mutations.GetKey(0)
}
return nil
}
return c.primaryKey
}
// asyncSecondaries returns all keys that must be checked in the recovery phase of an async commit.
func (c *twoPhaseCommitter) asyncSecondaries() [][]byte {
secondaries := make([][]byte, 0, c.mutations.Len())
for i := 0; i < c.mutations.Len(); i++ {
k := c.mutations.GetKey(i)
if bytes.Equal(k, c.primary()) || c.mutations.GetOp(i) == kvrpcpb.Op_CheckNotExists {
continue
}
secondaries = append(secondaries, k)
}
return secondaries
}
const bytesPerMiB = 1024 * 1024
// ttl = ttlFactor * sqrt(writeSizeInMiB)
var ttlFactor = 6000
// By default, locks after 3000ms is considered unusual (the client created the
// lock might be dead). Other client may cleanup this kind of lock.
// For locks created recently, we will do backoff and retry.
var defaultLockTTL uint64 = 3000
func txnLockTTL(startTime time.Time, txnSize int) uint64 {
// Increase lockTTL for large transactions.
// The formula is `ttl = ttlFactor * sqrt(sizeInMiB)`.
// When writeSize is less than 256KB, the base ttl is defaultTTL (3s);
// When writeSize is 1MiB, 4MiB, or 10MiB, ttl is 6s, 12s, 20s correspondingly;
lockTTL := defaultLockTTL
if txnSize >= int(kv.TxnCommitBatchSize.Load()) {
sizeMiB := float64(txnSize) / bytesPerMiB
lockTTL = uint64(float64(ttlFactor) * math.Sqrt(sizeMiB))
if lockTTL < defaultLockTTL {
lockTTL = defaultLockTTL
}
if lockTTL > ManagedLockTTL {
lockTTL = ManagedLockTTL
}
}
// Increase lockTTL by the transaction's read time.
// When resolving a lock, we compare current ts and startTS+lockTTL to decide whether to clean up. If a txn
// takes a long time to read, increasing its TTL will help to prevent it from been aborted soon after prewrite.
elapsed := time.Since(startTime) / time.Millisecond
return lockTTL + uint64(elapsed)
}
var preSplitDetectThreshold uint32 = 100000
var preSplitSizeThreshold uint32 = 32 << 20
// doActionOnMutations groups keys into primary batch and secondary batches, if primary batch exists in the key,
// it does action on primary batch first, then on secondary batches. If action is commit, secondary batches
// is done in background goroutine.
func (c *twoPhaseCommitter) doActionOnMutations(bo *retry.Backoffer, action twoPhaseCommitAction, mutations CommitterMutations) error {
if mutations.Len() == 0 {
return nil
}
groups, err := c.groupMutations(bo, mutations)
if err != nil {
return err
}
// This is redundant since `doActionOnGroupMutations` will still split groups into batches and
// check the number of batches. However we don't want the check fail after any code changes.
c.checkOnePCFallBack(action, len(groups))
return c.doActionOnGroupMutations(bo, action, groups)
}
type groupedMutations struct {
region locate.RegionVerID
mutations CommitterMutations
}
// groupSortedMutationsByRegion separates keys into groups by their belonging Regions.
func groupSortedMutationsByRegion(c *locate.RegionCache, bo *retry.Backoffer, m CommitterMutations) ([]groupedMutations, error) {
var (
groups []groupedMutations
lastLoc *locate.KeyLocation
)
lastUpperBound := 0
for i := 0; i < m.Len(); i++ {
if lastLoc == nil || !lastLoc.Contains(m.GetKey(i)) {
if lastLoc != nil {
groups = append(groups, groupedMutations{
region: lastLoc.Region,
mutations: m.Slice(lastUpperBound, i),
})
lastUpperBound = i
}
var err error
lastLoc, err = c.LocateKey(bo, m.GetKey(i))
if err != nil {
return nil, err
}
}
}
if lastLoc != nil {
groups = append(groups, groupedMutations{
region: lastLoc.Region,
mutations: m.Slice(lastUpperBound, m.Len()),
})
}
return groups, nil
}
// groupMutations groups mutations by region, then checks for any large groups and in that case pre-splits the region.
func (c *twoPhaseCommitter) groupMutations(bo *retry.Backoffer, mutations CommitterMutations) ([]groupedMutations, error) {
groups, err := groupSortedMutationsByRegion(c.store.GetRegionCache(), bo, mutations)
if err != nil {
return nil, err
}
// Pre-split regions to avoid too much write workload into a single region.
// In the large transaction case, this operation is important to avoid TiKV 'server is busy' error.
var didPreSplit bool
preSplitDetectThresholdVal := atomic.LoadUint32(&preSplitDetectThreshold)
for _, group := range groups {
if uint32(group.mutations.Len()) >= preSplitDetectThresholdVal {
logutil.BgLogger().Info("2PC detect large amount of mutations on a single region",
zap.Uint64("region", group.region.GetID()),
zap.Int("mutations count", group.mutations.Len()),
zap.Uint64("startTS", c.startTS))
if c.preSplitRegion(bo.GetCtx(), group) {
didPreSplit = true
}
}
}
// Reload region cache again.
if didPreSplit {
groups, err = groupSortedMutationsByRegion(c.store.GetRegionCache(), bo, mutations)
if err != nil {
return nil, err
}
}
return groups, nil
}
func (c *twoPhaseCommitter) preSplitRegion(ctx context.Context, group groupedMutations) bool {
splitKeys := make([][]byte, 0, 4)
preSplitSizeThresholdVal := atomic.LoadUint32(&preSplitSizeThreshold)
regionSize := 0
keysLength := group.mutations.Len()
// The value length maybe zero for pessimistic lock keys
for i := 0; i < keysLength; i++ {
regionSize = regionSize + len(group.mutations.GetKey(i)) + len(group.mutations.GetValue(i))
// The second condition is used for testing.
if regionSize >= int(preSplitSizeThresholdVal) {
regionSize = 0
splitKeys = append(splitKeys, group.mutations.GetKey(i))
}
}
if len(splitKeys) == 0 {
return false
}
regionIDs, err := c.store.SplitRegions(ctx, splitKeys, true, nil)
if err != nil {
logutil.BgLogger().Warn("2PC split regions failed", zap.Uint64("regionID", group.region.GetID()),
zap.Int("keys count", keysLength), zap.Error(err), zap.Uint64("startTS", c.startTS))
return false
}
for _, regionID := range regionIDs {
err := c.store.WaitScatterRegionFinish(ctx, regionID, 0)
if err != nil {
logutil.BgLogger().Warn("2PC wait scatter region failed", zap.Uint64("regionID", regionID), zap.Error(err),
zap.Uint64("startTS", c.startTS))
}
}
// Invalidate the old region cache information.
c.store.GetRegionCache().InvalidateCachedRegion(group.region)
return true
}
// CommitSecondaryMaxBackoff is max sleep time of the 'commit' command
const CommitSecondaryMaxBackoff = 41000
// doActionOnGroupedMutations splits groups into batches (there is one group per region, and potentially many batches per group, but all mutations
// in a batch will belong to the same region).
func (c *twoPhaseCommitter) doActionOnGroupMutations(bo *retry.Backoffer, action twoPhaseCommitAction, groups []groupedMutations) error {
if histogram := action.tiKVTxnRegionsNumHistogram(); histogram != nil {
histogram.Observe(float64(len(groups)))
}
var sizeFunc = c.keySize
switch act := action.(type) {
case actionPrewrite:
// Do not update regionTxnSize on retries. They are not used when building a PrewriteRequest.
if !act.retry {
for _, group := range groups {
c.regionTxnSize[group.region.GetID()] = group.mutations.Len()
}
}
sizeFunc = c.keyValueSize
atomic.AddInt32(&c.getDetail().PrewriteRegionNum, int32(len(groups)))
case actionPessimisticLock:
if act.Stats != nil {
act.Stats.RegionNum = int32(len(groups))
}
}
batchBuilder := newBatched(c.primary())
for _, group := range groups {
batchBuilder.appendBatchMutationsBySize(group.region, group.mutations, sizeFunc,
int(kv.TxnCommitBatchSize.Load()))
}
firstIsPrimary := batchBuilder.setPrimary()
actionCommit, actionIsCommit := action.(actionCommit)
_, actionIsCleanup := action.(actionCleanup)
_, actionIsPessimisticLock := action.(actionPessimisticLock)
_, actionIsPrewrite := action.(actionPrewrite)
c.checkOnePCFallBack(action, len(batchBuilder.allBatches()))
var err error
if val, err := util.EvalFailpoint("skipKeyReturnOK"); err == nil {
valStr, ok := val.(string)
if ok && c.sessionID > 0 {
if firstIsPrimary && actionIsPessimisticLock {
logutil.Logger(bo.GetCtx()).Warn("pessimisticLock failpoint", zap.String("valStr", valStr))
switch valStr {
case "pessimisticLockSkipPrimary":
err = c.doActionOnBatches(bo, action, batchBuilder.allBatches())
return err
case "pessimisticLockSkipSecondary":
err = c.doActionOnBatches(bo, action, batchBuilder.primaryBatch())
return err
}
}
}
}
if _, err := util.EvalFailpoint("pessimisticRollbackDoNth"); err == nil {
_, actionIsPessimisticRollback := action.(actionPessimisticRollback)
if actionIsPessimisticRollback && c.sessionID > 0 {
logutil.Logger(bo.GetCtx()).Warn("pessimisticRollbackDoNth failpoint")
return nil
}
}
if actionIsPrewrite && c.prewriteTotalReqNum == 0 && len(batchBuilder.allBatches()) > 0 {
c.prewriteTotalReqNum = len(batchBuilder.allBatches())
}