-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
Copy pathtxn.go
564 lines (487 loc) · 15.5 KB
/
txn.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
// Copyright 2018 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 session
import (
"bytes"
"context"
"fmt"
"runtime/trace"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/session/txninfo"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/binloginfo"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/util/logutil"
"github.com/pingcap/tidb/util/sli"
"github.com/pingcap/tipb/go-binlog"
"github.com/tikv/client-go/v2/oracle"
"github.com/tikv/client-go/v2/tikv"
"go.uber.org/zap"
)
// LazyTxn wraps kv.Transaction to provide a new kv.Transaction.
// 1. It holds all statement related modification in the buffer before flush to the txn,
// so if execute statement meets error, the txn won't be made dirty.
// 2. It's a lazy transaction, that means it's a txnFuture before StartTS() is really need.
type LazyTxn struct {
// States of a LazyTxn should be one of the followings:
// Invalid: kv.Transaction == nil && txnFuture == nil
// Pending: kv.Transaction == nil && txnFuture != nil
// Valid: kv.Transaction != nil && txnFuture == nil
kv.Transaction
txnFuture *txnFuture
initCnt int
stagingHandle kv.StagingHandle
mutations map[int64]*binlog.TableMutation
writeSLI sli.TxnWriteThroughputSLI
// TxnInfo is added for the lock view feature, the data is frequent modified but
// rarely read (just in query select * from information_schema.tidb_trx).
// The data in this session would be query by other sessions, so Mutex is necessary.
// Since read is rare, the reader can copy-on-read to get a data snapshot.
mu struct {
sync.RWMutex
txninfo.TxnInfo
}
}
// GetTableInfo returns the cached index name.
func (txn *LazyTxn) GetTableInfo(id int64) *model.TableInfo {
return txn.Transaction.GetTableInfo(id)
}
// CacheTableInfo caches the index name.
func (txn *LazyTxn) CacheTableInfo(id int64, info *model.TableInfo) {
txn.Transaction.CacheTableInfo(id, info)
}
func (txn *LazyTxn) init() {
txn.mutations = make(map[int64]*binlog.TableMutation)
txn.mu.Lock()
txn.mu.TxnInfo.State = txninfo.TxnIdle
txn.mu.Unlock()
}
func (txn *LazyTxn) initStmtBuf() {
if txn.Transaction == nil {
return
}
buf := txn.Transaction.GetMemBuffer()
txn.initCnt = buf.Len()
txn.stagingHandle = buf.Staging()
}
// countHint is estimated count of mutations.
func (txn *LazyTxn) countHint() int {
if txn.stagingHandle == kv.InvalidStagingHandle {
return 0
}
return txn.Transaction.GetMemBuffer().Len() - txn.initCnt
}
func (txn *LazyTxn) flushStmtBuf() {
if txn.stagingHandle == kv.InvalidStagingHandle {
return
}
buf := txn.Transaction.GetMemBuffer()
buf.Release(txn.stagingHandle)
txn.initCnt = buf.Len()
}
func (txn *LazyTxn) cleanupStmtBuf() {
if txn.stagingHandle == kv.InvalidStagingHandle {
return
}
buf := txn.Transaction.GetMemBuffer()
buf.Cleanup(txn.stagingHandle)
txn.initCnt = buf.Len()
txn.mu.Lock()
defer txn.mu.Unlock()
txn.mu.TxnInfo.EntriesCount = uint64(txn.Transaction.Len())
txn.mu.TxnInfo.EntriesSize = uint64(txn.Transaction.Size())
}
// resetTxnInfo resets the transaction info.
// Note: call it under lock!
func (txn *LazyTxn) resetTxnInfo(
startTS uint64,
state txninfo.TxnRunningState,
entriesCount,
entriesSize uint64,
currentSQLDigest string,
allSQLDigests []string,
) {
txn.mu.TxnInfo = txninfo.TxnInfo{}
txn.mu.TxnInfo.StartTS = startTS
txn.mu.TxnInfo.State = state
txn.mu.TxnInfo.EntriesCount = entriesCount
txn.mu.TxnInfo.EntriesSize = entriesSize
txn.mu.TxnInfo.CurrentSQLDigest = currentSQLDigest
txn.mu.TxnInfo.AllSQLDigests = allSQLDigests
}
// Size implements the MemBuffer interface.
func (txn *LazyTxn) Size() int {
if txn.Transaction == nil {
return 0
}
return txn.Transaction.Size()
}
// Valid implements the kv.Transaction interface.
func (txn *LazyTxn) Valid() bool {
return txn.Transaction != nil && txn.Transaction.Valid()
}
func (txn *LazyTxn) pending() bool {
return txn.Transaction == nil && txn.txnFuture != nil
}
func (txn *LazyTxn) validOrPending() bool {
return txn.txnFuture != nil || txn.Valid()
}
func (txn *LazyTxn) String() string {
if txn.Transaction != nil {
return txn.Transaction.String()
}
if txn.txnFuture != nil {
return "txnFuture"
}
return "invalid transaction"
}
// GoString implements the "%#v" format for fmt.Printf.
func (txn *LazyTxn) GoString() string {
var s strings.Builder
s.WriteString("Txn{")
if txn.pending() {
s.WriteString("state=pending")
} else if txn.Valid() {
s.WriteString("state=valid")
fmt.Fprintf(&s, ", txnStartTS=%d", txn.Transaction.StartTS())
if len(txn.mutations) > 0 {
fmt.Fprintf(&s, ", len(mutations)=%d, %#v", len(txn.mutations), txn.mutations)
}
} else {
s.WriteString("state=invalid")
}
s.WriteString("}")
return s.String()
}
// GetOption implements the GetOption
func (txn *LazyTxn) GetOption(opt int) interface{} {
if txn.Transaction == nil {
switch opt {
case kv.TxnScope:
return ""
}
return nil
}
return txn.Transaction.GetOption(opt)
}
func (txn *LazyTxn) changeInvalidToValid(kvTxn kv.Transaction) {
txn.Transaction = kvTxn
txn.initStmtBuf()
txn.txnFuture = nil
txn.mu.Lock()
defer txn.mu.Unlock()
txn.resetTxnInfo(
kvTxn.StartTS(),
txninfo.TxnIdle,
uint64(txn.Transaction.Len()),
uint64(txn.Transaction.Size()),
"",
nil)
}
func (txn *LazyTxn) changeInvalidToPending(future *txnFuture) {
txn.Transaction = nil
txn.txnFuture = future
}
func (txn *LazyTxn) changePendingToValid(ctx context.Context) error {
if txn.txnFuture == nil {
return errors.New("transaction future is not set")
}
future := txn.txnFuture
txn.txnFuture = nil
defer trace.StartRegion(ctx, "WaitTsoFuture").End()
t, err := future.wait()
if err != nil {
txn.Transaction = nil
return err
}
txn.Transaction = t
txn.initStmtBuf()
// The txnInfo may already recorded the first statement (usually "begin") when it's pending, so keep them.
txn.mu.Lock()
defer txn.mu.Unlock()
txn.resetTxnInfo(
t.StartTS(),
txninfo.TxnIdle,
uint64(txn.Transaction.Len()),
uint64(txn.Transaction.Size()),
txn.mu.TxnInfo.CurrentSQLDigest,
txn.mu.TxnInfo.AllSQLDigests)
return nil
}
func (txn *LazyTxn) changeToInvalid() {
if txn.stagingHandle != kv.InvalidStagingHandle {
txn.Transaction.GetMemBuffer().Cleanup(txn.stagingHandle)
}
txn.stagingHandle = kv.InvalidStagingHandle
txn.Transaction = nil
txn.txnFuture = nil
txn.mu.Lock()
defer txn.mu.Unlock()
txn.mu.TxnInfo = txninfo.TxnInfo{}
}
func (txn *LazyTxn) onStmtStart(currentSQLDigest string) {
if len(currentSQLDigest) == 0 {
return
}
txn.mu.Lock()
defer txn.mu.Unlock()
txn.mu.TxnInfo.State = txninfo.TxnRunning
txn.mu.TxnInfo.CurrentSQLDigest = currentSQLDigest
// Keeps at most 50 history sqls to avoid consuming too much memory.
const maxTransactionStmtHistory int = 50
if len(txn.mu.TxnInfo.AllSQLDigests) < maxTransactionStmtHistory {
txn.mu.TxnInfo.AllSQLDigests = append(txn.mu.TxnInfo.AllSQLDigests, currentSQLDigest)
}
}
func (txn *LazyTxn) onStmtEnd() {
txn.mu.Lock()
txn.mu.TxnInfo.CurrentSQLDigest = ""
txn.mu.TxnInfo.State = txninfo.TxnIdle
txn.mu.Unlock()
}
var hasMockAutoIncIDRetry = int64(0)
func enableMockAutoIncIDRetry() {
atomic.StoreInt64(&hasMockAutoIncIDRetry, 1)
}
func mockAutoIncIDRetry() bool {
return atomic.LoadInt64(&hasMockAutoIncIDRetry) == 1
}
var mockAutoRandIDRetryCount = int64(0)
func needMockAutoRandIDRetry() bool {
return atomic.LoadInt64(&mockAutoRandIDRetryCount) > 0
}
func decreaseMockAutoRandIDRetryCount() {
atomic.AddInt64(&mockAutoRandIDRetryCount, -1)
}
// ResetMockAutoRandIDRetryCount set the number of occurrences of
// `kv.ErrTxnRetryable` when calling TxnState.Commit().
func ResetMockAutoRandIDRetryCount(failTimes int64) {
atomic.StoreInt64(&mockAutoRandIDRetryCount, failTimes)
}
// Commit overrides the Transaction interface.
func (txn *LazyTxn) Commit(ctx context.Context) error {
defer txn.reset()
if len(txn.mutations) != 0 || txn.countHint() != 0 {
logutil.BgLogger().Error("the code should never run here",
zap.String("TxnState", txn.GoString()),
zap.Int("staging handler", int(txn.stagingHandle)),
zap.Stack("something must be wrong"))
return errors.Trace(kv.ErrInvalidTxn)
}
txn.mu.Lock()
txn.mu.TxnInfo.State = txninfo.TxnCommitting
txn.mu.Unlock()
failpoint.Inject("mockSlowCommit", func(_ failpoint.Value) {})
// mockCommitError8942 is used for PR #8942.
failpoint.Inject("mockCommitError8942", func(val failpoint.Value) {
if val.(bool) {
failpoint.Return(kv.ErrTxnRetryable)
}
})
// mockCommitRetryForAutoIncID is used to mock an commit retry for adjustAutoIncrementDatum.
failpoint.Inject("mockCommitRetryForAutoIncID", func(val failpoint.Value) {
if val.(bool) && !mockAutoIncIDRetry() {
enableMockAutoIncIDRetry()
failpoint.Return(kv.ErrTxnRetryable)
}
})
failpoint.Inject("mockCommitRetryForAutoRandID", func(val failpoint.Value) {
if val.(bool) && needMockAutoRandIDRetry() {
decreaseMockAutoRandIDRetryCount()
failpoint.Return(kv.ErrTxnRetryable)
}
})
return txn.Transaction.Commit(ctx)
}
// Rollback overrides the Transaction interface.
func (txn *LazyTxn) Rollback() error {
defer txn.reset()
txn.mu.Lock()
txn.mu.TxnInfo.State = txninfo.TxnRollingBack
txn.mu.Unlock()
// mockSlowRollback is used to mock a rollback which takes a long time
failpoint.Inject("mockSlowRollback", func(_ failpoint.Value) {})
return txn.Transaction.Rollback()
}
// LockKeys Wrap the inner transaction's `LockKeys` to record the status
func (txn *LazyTxn) LockKeys(ctx context.Context, lockCtx *kv.LockCtx, keys ...kv.Key) error {
failpoint.Inject("beforeLockKeys", func() {})
t := time.Now()
var originState txninfo.TxnRunningState
txn.mu.Lock()
originState = txn.mu.TxnInfo.State
txn.mu.TxnInfo.State = txninfo.TxnLockWaiting
txn.mu.TxnInfo.BlockStartTime.Valid = true
txn.mu.TxnInfo.BlockStartTime.Time = t
txn.mu.Unlock()
err := txn.Transaction.LockKeys(ctx, lockCtx, keys...)
txn.mu.Lock()
defer txn.mu.Unlock()
txn.mu.TxnInfo.State = originState
txn.mu.TxnInfo.BlockStartTime.Valid = false
txn.mu.TxnInfo.EntriesCount = uint64(txn.Transaction.Len())
txn.mu.TxnInfo.EntriesSize = uint64(txn.Transaction.Size())
return err
}
func (txn *LazyTxn) reset() {
txn.cleanup()
txn.changeToInvalid()
}
func (txn *LazyTxn) cleanup() {
txn.cleanupStmtBuf()
txn.initStmtBuf()
for key := range txn.mutations {
delete(txn.mutations, key)
}
}
// KeysNeedToLock returns the keys need to be locked.
func (txn *LazyTxn) KeysNeedToLock() ([]kv.Key, error) {
if txn.stagingHandle == kv.InvalidStagingHandle {
return nil, nil
}
keys := make([]kv.Key, 0, txn.countHint())
buf := txn.Transaction.GetMemBuffer()
buf.InspectStage(txn.stagingHandle, func(k kv.Key, flags kv.KeyFlags, v []byte) {
if !keyNeedToLock(k, v, flags) {
return
}
keys = append(keys, k)
})
return keys, nil
}
func keyNeedToLock(k, v []byte, flags kv.KeyFlags) bool {
isTableKey := bytes.HasPrefix(k, tablecodec.TablePrefix())
if !isTableKey {
// meta key always need to lock.
return true
}
if flags.HasPresumeKeyNotExists() {
return true
}
// lock row key, primary key and unique index for delete operation,
if len(v) == 0 {
return flags.HasNeedLocked() || tablecodec.IsRecordKey(k)
}
if tablecodec.IsUntouchedIndexKValue(k, v) {
return false
}
isNonUniqueIndex := tablecodec.IsIndexKey(k) && len(v) == 1
// Put row key and unique index need to lock.
return !isNonUniqueIndex
}
func getBinlogMutation(ctx sessionctx.Context, tableID int64) *binlog.TableMutation {
bin := binloginfo.GetPrewriteValue(ctx, true)
for i := range bin.Mutations {
if bin.Mutations[i].TableId == tableID {
return &bin.Mutations[i]
}
}
idx := len(bin.Mutations)
bin.Mutations = append(bin.Mutations, binlog.TableMutation{TableId: tableID})
return &bin.Mutations[idx]
}
func mergeToMutation(m1, m2 *binlog.TableMutation) {
m1.InsertedRows = append(m1.InsertedRows, m2.InsertedRows...)
m1.UpdatedRows = append(m1.UpdatedRows, m2.UpdatedRows...)
m1.DeletedIds = append(m1.DeletedIds, m2.DeletedIds...)
m1.DeletedPks = append(m1.DeletedPks, m2.DeletedPks...)
m1.DeletedRows = append(m1.DeletedRows, m2.DeletedRows...)
m1.Sequence = append(m1.Sequence, m2.Sequence...)
}
type txnFailFuture struct{}
func (txnFailFuture) Wait() (uint64, error) {
return 0, errors.New("mock get timestamp fail")
}
// txnFuture is a promise, which promises to return a txn in future.
type txnFuture struct {
future oracle.Future
store kv.Storage
txnScope string
}
func (tf *txnFuture) wait() (kv.Transaction, error) {
startTS, err := tf.future.Wait()
failpoint.Inject("txnFutureWait", func() {})
if err == nil {
return tf.store.Begin(tikv.WithTxnScope(tf.txnScope), tikv.WithStartTS(startTS))
} else if config.GetGlobalConfig().Store == "unistore" {
return nil, err
}
logutil.BgLogger().Warn("wait tso failed", zap.Error(err))
// It would retry get timestamp.
return tf.store.Begin(tikv.WithTxnScope(tf.txnScope))
}
func (s *session) getTxnFuture(ctx context.Context) *txnFuture {
if span := opentracing.SpanFromContext(ctx); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("session.getTxnFuture", opentracing.ChildOf(span.Context()))
defer span1.Finish()
ctx = opentracing.ContextWithSpan(ctx, span1)
}
oracleStore := s.store.GetOracle()
var tsFuture oracle.Future
if s.sessionVars.LowResolutionTSO {
tsFuture = oracleStore.GetLowResolutionTimestampAsync(ctx, &oracle.Option{TxnScope: s.sessionVars.CheckAndGetTxnScope()})
} else {
tsFuture = oracleStore.GetTimestampAsync(ctx, &oracle.Option{TxnScope: s.sessionVars.CheckAndGetTxnScope()})
}
ret := &txnFuture{future: tsFuture, store: s.store, txnScope: s.sessionVars.CheckAndGetTxnScope()}
failpoint.InjectContext(ctx, "mockGetTSFail", func() {
ret.future = txnFailFuture{}
})
return ret
}
// HasDirtyContent checks whether there's dirty update on the given table.
// Put this function here is to avoid cycle import.
func (s *session) HasDirtyContent(tid int64) bool {
if s.txn.Transaction == nil {
return false
}
seekKey := tablecodec.EncodeTablePrefix(tid)
it, err := s.txn.GetMemBuffer().Iter(seekKey, nil)
terror.Log(err)
return it.Valid() && bytes.HasPrefix(it.Key(), seekKey)
}
// StmtCommit implements the sessionctx.Context interface.
func (s *session) StmtCommit() {
defer func() {
s.txn.cleanup()
}()
st := &s.txn
st.flushStmtBuf()
// Need to flush binlog.
for tableID, delta := range st.mutations {
mutation := getBinlogMutation(s, tableID)
mergeToMutation(mutation, delta)
}
}
// StmtRollback implements the sessionctx.Context interface.
func (s *session) StmtRollback() {
s.txn.cleanup()
}
// StmtGetMutation implements the sessionctx.Context interface.
func (s *session) StmtGetMutation(tableID int64) *binlog.TableMutation {
st := &s.txn
if _, ok := st.mutations[tableID]; !ok {
st.mutations[tableID] = &binlog.TableMutation{TableId: tableID}
}
return st.mutations[tableID]
}