-
Notifications
You must be signed in to change notification settings - Fork 220
/
2pc.go
1899 lines (1718 loc) · 62.5 KB
/
2pc.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 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"
"encoding/hex"
"math"
"math/rand"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/parser/terror"
"github.com/prometheus/client_golang/prometheus"
"github.com/tikv/client-go/v2/config"
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/retry"
"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"
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
String() string
}
// Global variable set by config file.
var (
ManagedLockTTL uint64 = 20000 // 20s
)
var (
// PrewriteMaxBackoff is max sleep time of the `pre-write` command.
PrewriteMaxBackoff = 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
}
// 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
primaryKey []byte
forUpdateTS 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
minCommitTS uint64
maxCommitTS uint64
prewriteStarted bool
prewriteCancelled uint32
useOnePC uint32
onePCCommitTS uint64
hasTriedAsyncCommit bool
hasTriedOnePC bool
// doingAmend means the amend prewrite is ongoing.
doingAmend bool
binlog BinlogExecutor
resourceGroupTag []byte
// allowed when tikv disk full happened.
diskFullOpt kvrpcpb.DiskFullOpt
}
type memBufferMutations struct {
storage *unionstore.MemDB
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 >> 1)
}
func (m *memBufferMutations) IsPessimisticLock(i int) bool {
return m.handles[i].UserData&1 != 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 bool, handle unionstore.MemKeyHandle) {
aux := uint16(op) << 1
if isPessimisticLock {
aux |= 1
}
handle.UserData = aux
m.handles = append(m.handles, handle)
}
// 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
}
// PlainMutations contains transaction operations.
type PlainMutations struct {
ops []kvrpcpb.Op
keys [][]byte
values [][]byte
isPessimisticLock []bool
}
// 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),
isPessimisticLock: make([]bool, 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.isPessimisticLock != nil {
res.isPessimisticLock = c.isPessimisticLock[from:to]
}
return &res
}
// Push another mutation into mutations.
func (c *PlainMutations) Push(op kvrpcpb.Op, key []byte, value []byte, isPessimisticLock bool) {
c.ops = append(c.ops, op)
c.keys = append(c.keys, key)
c.values = append(c.values, value)
c.isPessimisticLock = append(c.isPessimisticLock, isPessimisticLock)
}
// 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
}
// GetPessimisticFlags returns the key pessimistic flags.
func (c *PlainMutations) GetPessimisticFlags() []bool {
return c.isPessimisticLock
}
// 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.isPessimisticLock[i]
}
// PlainMutation represents a single transaction operation.
type PlainMutation struct {
KeyOp kvrpcpb.Op
Key []byte
Value []byte
IsPessimisticLock bool
}
// 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.isPessimisticLock = append(c.isPessimisticLock, mutations.isPessimisticLock...)
}
// 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.isPessimisticLock = append(c.isPessimisticLock, mutation.IsPessimisticLock)
}
// newTwoPhaseCommitter creates a twoPhaseCommitter.
func newTwoPhaseCommitter(txn *KVTxn, sessionID uint64) (*twoPhaseCommitter, error) {
return &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,
}, nil
}
func (c *twoPhaseCommitter) extractKeyExistsErr(err *tikverr.ErrKeyExist) error {
if !c.txn.us.HasPresumeKeyNotExists(err.GetKey()) {
return errors.Errorf("session %d, existErr for key:%s should not be nil", c.sessionID, err.GetKey())
}
return errors.Trace(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
}
func (c *twoPhaseCommitter) initKeysAndMutations() error {
var size, putCnt, delCnt, lockCnt, checkCnt int
txn := c.txn
memBuf := txn.GetMemBuffer()
sizeHint := txn.us.GetMemBuffer().Len()
c.mutations = newMemBufferMutations(sizeHint, memBuf)
c.isPessimistic = txn.IsPessimistic()
filter := txn.kvFilter
var err 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()
isUnnecessaryKV := filter != nil && filter.IsUnnecessaryKeyValue(key, value, flags)
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 {
// normal delete keys in optimistic txn can be delete without not exists checking
// delete-your-writes keys in pessimistic txn can ensure must be no exists so can directly delete them
op = kvrpcpb.Op_Del
delCnt++
}
}
}
var isPessimistic bool
if flags.HasLocked() {
isPessimistic = c.isPessimistic
}
c.mutations.Push(op, isPessimistic, it.Handle())
size += len(key) + len(value)
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", kv.StrKey(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 errors.Trace(err)
}
commitDetail := &util.CommitDetails{WriteSize: size, WriteKeys: c.mutations.Len()}
metrics.TiKVTxnWriteKVCountHistogram.Observe(float64(commitDetail.WriteKeys))
metrics.TiKVTxnWriteSizeHistogram.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.setDetail(commitDetail)
return nil
}
func (c *twoPhaseCommitter) primary() []byte {
if len(c.primaryKey) == 0 {
return c.mutations.GetKey(0)
}
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 >= txnCommitBatchSize {
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 errors.Trace(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, errors.Trace(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, errors.Trace(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()))
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, errors.Trace(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))
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))
}
}
// 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 {
action.tiKVTxnRegionsNumHistogram().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.LockCtx.Stats != nil {
act.LockCtx.Stats.RegionNum = int32(len(groups))
}
}
batchBuilder := newBatched(c.primary())
for _, group := range groups {
batchBuilder.appendBatchMutationsBySize(group.region, group.mutations, sizeFunc, txnCommitBatchSize)
}
firstIsPrimary := batchBuilder.setPrimary()
actionCommit, actionIsCommit := action.(actionCommit)
_, actionIsCleanup := action.(actionCleanup)
_, actionIsPessimisticLock := action.(actionPessimisticLock)
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 firstIsPrimary &&
((actionIsCommit && !c.isAsyncCommit()) || actionIsCleanup || actionIsPessimisticLock) {
// primary should be committed(not async commit)/cleanup/pessimistically locked first
err = c.doActionOnBatches(bo, action, batchBuilder.primaryBatch())
if err != nil {
return errors.Trace(err)
}
if actionIsCommit && c.testingKnobs.bkAfterCommitPrimary != nil && c.testingKnobs.acAfterCommitPrimary != nil {
c.testingKnobs.acAfterCommitPrimary <- struct{}{}
<-c.testingKnobs.bkAfterCommitPrimary
}
batchBuilder.forgetPrimary()
}
util.EvalFailpoint("afterPrimaryBatch")
// Already spawned a goroutine for async commit transaction.
if actionIsCommit && !actionCommit.retry && !c.isAsyncCommit() {
secondaryBo := retry.NewBackofferWithVars(c.store.Ctx(), CommitSecondaryMaxBackoff, c.txn.vars)
c.store.WaitGroup().Add(1)
go func() {
defer c.store.WaitGroup().Done()
if c.sessionID > 0 {
if v, err := util.EvalFailpoint("beforeCommitSecondaries"); err == nil {
if s, ok := v.(string); !ok {
logutil.Logger(bo.GetCtx()).Info("[failpoint] sleep 2s before commit secondary keys",
zap.Uint64("sessionID", c.sessionID), zap.Uint64("txnStartTS", c.startTS), zap.Uint64("txnCommitTS", c.commitTS))
time.Sleep(2 * time.Second)
} else if s == "skip" {
logutil.Logger(bo.GetCtx()).Info("[failpoint] injected skip committing secondaries",
zap.Uint64("sessionID", c.sessionID), zap.Uint64("txnStartTS", c.startTS), zap.Uint64("txnCommitTS", c.commitTS))
return
}
}
}
e := c.doActionOnBatches(secondaryBo, action, batchBuilder.allBatches())
if e != nil {
logutil.BgLogger().Debug("2PC async doActionOnBatches",
zap.Uint64("session", c.sessionID),
zap.Stringer("action type", action),
zap.Error(e))
metrics.SecondaryLockCleanupFailureCounterCommit.Inc()
}
}()
} else {
err = c.doActionOnBatches(bo, action, batchBuilder.allBatches())
}
return errors.Trace(err)
}
// doActionOnBatches does action to batches in parallel.
func (c *twoPhaseCommitter) doActionOnBatches(bo *retry.Backoffer, action twoPhaseCommitAction, batches []batchMutations) error {
if len(batches) == 0 {
return nil
}
noNeedFork := len(batches) == 1
if !noNeedFork {
if ac, ok := action.(actionCommit); ok && ac.retry {
noNeedFork = true
}
}
if noNeedFork {
for _, b := range batches {
e := action.handleSingleBatch(c, bo, b)
if e != nil {
logutil.BgLogger().Debug("2PC doActionOnBatches failed",
zap.Uint64("session", c.sessionID),
zap.Stringer("action type", action),
zap.Error(e),
zap.Uint64("txnStartTS", c.startTS))
return errors.Trace(e)
}
}
return nil
}
rateLim := len(batches)
// Set rateLim here for the large transaction.
// If the rate limit is too high, tikv will report service is busy.
// If the rate limit is too low, we can't full utilize the tikv's throughput.
// TODO: Find a self-adaptive way to control the rate limit here.
if rateLim > config.GetGlobalConfig().CommitterConcurrency {
rateLim = config.GetGlobalConfig().CommitterConcurrency
}
batchExecutor := newBatchExecutor(rateLim, c, action, bo)
err := batchExecutor.process(batches)
return errors.Trace(err)
}
func (c *twoPhaseCommitter) keyValueSize(key, value []byte) int {
return len(key) + len(value)
}
func (c *twoPhaseCommitter) keySize(key, value []byte) int {
return len(key)
}
func (c *twoPhaseCommitter) SetDiskFullOpt(level kvrpcpb.DiskFullOpt) {
c.diskFullOpt = level
}
type ttlManagerState uint32
const (
stateUninitialized ttlManagerState = iota
stateRunning
stateClosed
)
type ttlManager struct {
state ttlManagerState
ch chan struct{}
lockCtx *kv.LockCtx
}
func (tm *ttlManager) run(c *twoPhaseCommitter, lockCtx *kv.LockCtx) {
if _, err := util.EvalFailpoint("doNotKeepAlive"); err == nil {
return
}
// Run only once.
if !atomic.CompareAndSwapUint32((*uint32)(&tm.state), uint32(stateUninitialized), uint32(stateRunning)) {
return
}
tm.ch = make(chan struct{})
tm.lockCtx = lockCtx
go keepAlive(c, tm.ch, c.primary(), lockCtx)
}
func (tm *ttlManager) close() {
if !atomic.CompareAndSwapUint32((*uint32)(&tm.state), uint32(stateRunning), uint32(stateClosed)) {
return
}
close(tm.ch)
}
func (tm *ttlManager) reset() {
if !atomic.CompareAndSwapUint32((*uint32)(&tm.state), uint32(stateRunning), uint32(stateUninitialized)) {
return
}
close(tm.ch)
}
const keepAliveMaxBackoff = 20000 // 20 seconds
const pessimisticLockMaxBackoff = 600000 // 10 minutes
const maxConsecutiveFailure = 10
func keepAlive(c *twoPhaseCommitter, closeCh chan struct{}, primaryKey []byte, lockCtx *kv.LockCtx) {
// Ticker is set to 1/2 of the ManagedLockTTL.
ticker := time.NewTicker(time.Duration(atomic.LoadUint64(&ManagedLockTTL)) * time.Millisecond / 2)
defer ticker.Stop()
keepFail := 0
for {
select {
case <-closeCh:
return
case <-ticker.C:
// If kill signal is received, the ttlManager should exit.
if lockCtx != nil && lockCtx.Killed != nil && atomic.LoadUint32(lockCtx.Killed) != 0 {
return
}
bo := retry.NewBackofferWithVars(context.Background(), keepAliveMaxBackoff, c.txn.vars)
now, err := c.store.GetTimestampWithRetry(bo, c.txn.GetScope())
if err != nil {
logutil.Logger(bo.GetCtx()).Warn("keepAlive get tso fail",
zap.Error(err))
return
}
uptime := uint64(oracle.ExtractPhysical(now) - oracle.ExtractPhysical(c.startTS))
if uptime > config.GetGlobalConfig().MaxTxnTTL {
// Checks maximum lifetime for the ttlManager, so when something goes wrong
// the key will not be locked forever.
logutil.Logger(bo.GetCtx()).Info("ttlManager live up to its lifetime",
zap.Uint64("txnStartTS", c.startTS),
zap.Uint64("uptime", uptime),
zap.Uint64("maxTxnTTL", config.GetGlobalConfig().MaxTxnTTL))
metrics.TiKVTTLLifeTimeReachCounter.Inc()
// the pessimistic locks may expire if the ttl manager has timed out, set `LockExpired` flag
// so that this transaction could only commit or rollback with no more statement executions
if c.isPessimistic && lockCtx != nil && lockCtx.LockExpired != nil {
atomic.StoreUint32(lockCtx.LockExpired, 1)
}
return
}
newTTL := uptime + atomic.LoadUint64(&ManagedLockTTL)
logutil.Logger(bo.GetCtx()).Info("send TxnHeartBeat",
zap.Uint64("startTS", c.startTS), zap.Uint64("newTTL", newTTL))
startTime := time.Now()
_, stopHeartBeat, err := sendTxnHeartBeat(bo, c.store, primaryKey, c.startTS, newTTL)
if err != nil {
keepFail++
metrics.TxnHeartBeatHistogramError.Observe(time.Since(startTime).Seconds())
logutil.Logger(bo.GetCtx()).Debug("send TxnHeartBeat failed",
zap.Error(err),
zap.Uint64("txnStartTS", c.startTS))
if stopHeartBeat || keepFail > maxConsecutiveFailure {
logutil.Logger(bo.GetCtx()).Warn("stop TxnHeartBeat",
zap.Error(err),
zap.Int("consecutiveFailure", keepFail),
zap.Uint64("txnStartTS", c.startTS))
return
}
continue
}
keepFail = 0
metrics.TxnHeartBeatHistogramOK.Observe(time.Since(startTime).Seconds())
}
}
}
func sendTxnHeartBeat(bo *retry.Backoffer, store kvstore, primary []byte, startTS, ttl uint64) (newTTL uint64, stopHeartBeat bool, err error) {
req := tikvrpc.NewRequest(tikvrpc.CmdTxnHeartBeat, &kvrpcpb.TxnHeartBeatRequest{
PrimaryLock: primary,
StartVersion: startTS,
AdviseLockTtl: ttl,
})
for {
loc, err := store.GetRegionCache().LocateKey(bo, primary)
if err != nil {
return 0, false, errors.Trace(err)
}
req.MaxExecutionDurationMs = uint64(client.MaxWriteExecutionTime.Milliseconds())
resp, err := store.SendReq(bo, req, loc.Region, client.ReadTimeoutShort)
if err != nil {
return 0, false, errors.Trace(err)
}
regionErr, err := resp.GetRegionError()
if err != nil {
return 0, false, errors.Trace(err)
}
if regionErr != nil {
// For other region error and the fake region error, backoff because
// there's something wrong.
// For the real EpochNotMatch error, don't backoff.
if regionErr.GetEpochNotMatch() == nil || locate.IsFakeRegionError(regionErr) {
err = bo.Backoff(retry.BoRegionMiss, errors.New(regionErr.String()))
if err != nil {
return 0, false, errors.Trace(err)
}
}
continue
}
if resp.Resp == nil {
return 0, false, errors.Trace(tikverr.ErrBodyMissing)
}
cmdResp := resp.Resp.(*kvrpcpb.TxnHeartBeatResponse)
if keyErr := cmdResp.GetError(); keyErr != nil {
return 0, true, errors.Errorf("txn %d heartbeat fail, primary key = %v, err = %s", startTS, hex.EncodeToString(primary), tikverr.ExtractKeyErr(keyErr))
}
return cmdResp.GetLockTtl(), false, nil