-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
tx_conn.go
405 lines (361 loc) · 12 KB
/
tx_conn.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
/*
Copyright 2019 The Vitess 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.
*/
package vtgate
import (
"fmt"
"sync"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
"vitess.io/vitess/go/vt/vttablet/queryservice"
"context"
"vitess.io/vitess/go/vt/concurrency"
"vitess.io/vitess/go/vt/dtids"
"vitess.io/vitess/go/vt/log"
querypb "vitess.io/vitess/go/vt/proto/query"
vtgatepb "vitess.io/vitess/go/vt/proto/vtgate"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
)
// TxConn is used for executing transactional requests.
type TxConn struct {
tabletGateway *TabletGateway
mode vtgatepb.TransactionMode
}
// NewTxConn builds a new TxConn.
func NewTxConn(gw *TabletGateway, txMode vtgatepb.TransactionMode) *TxConn {
return &TxConn{
tabletGateway: gw,
mode: txMode,
}
}
// Begin begins a new transaction. If one is already in progress, it commits it
// and starts a new one.
func (txc *TxConn) Begin(ctx context.Context, session *SafeSession) error {
if session.InTransaction() {
if err := txc.Commit(ctx, session); err != nil {
return err
}
}
session.Session.InTransaction = true
return nil
}
// Commit commits the current transaction. The type of commit can be
// best effort or 2pc depending on the session setting.
func (txc *TxConn) Commit(ctx context.Context, session *SafeSession) error {
defer session.ResetTx()
if !session.InTransaction() {
return nil
}
twopc := false
switch session.TransactionMode {
case vtgatepb.TransactionMode_TWOPC:
twopc = true
case vtgatepb.TransactionMode_UNSPECIFIED:
twopc = txc.mode == vtgatepb.TransactionMode_TWOPC
}
if twopc {
return txc.commit2PC(ctx, session)
}
return txc.commitNormal(ctx, session)
}
func (txc *TxConn) queryService(alias *topodatapb.TabletAlias) (queryservice.QueryService, error) {
if alias == nil {
return txc.tabletGateway, nil
}
return txc.tabletGateway.QueryServiceByAlias(alias, nil)
}
func (txc *TxConn) commitShard(ctx context.Context, s *vtgatepb.Session_ShardSession) error {
if s.TransactionId == 0 {
return nil
}
var qs queryservice.QueryService
var err error
qs, err = txc.queryService(s.TabletAlias)
if err != nil {
return err
}
reservedID, err := qs.Commit(ctx, s.Target, s.TransactionId)
if err != nil {
return err
}
s.TransactionId = 0
s.ReservedId = reservedID
return nil
}
func (txc *TxConn) commitNormal(ctx context.Context, session *SafeSession) error {
if err := txc.runSessions(ctx, session.PreSessions, txc.commitShard); err != nil {
_ = txc.Release(ctx, session)
return err
}
// Retain backward compatibility on commit order for the normal session.
for _, shardSession := range session.ShardSessions {
if err := txc.commitShard(ctx, shardSession); err != nil {
_ = txc.Release(ctx, session)
return err
}
}
if err := txc.runSessions(ctx, session.PostSessions, txc.commitShard); err != nil {
// If last commit fails, there will be nothing to rollback.
session.RecordWarning(&querypb.QueryWarning{Message: fmt.Sprintf("post-operation transaction had an error: %v", err)})
// With reserved connection we should release them.
if session.InReservedConn() {
_ = txc.Release(ctx, session)
}
}
return nil
}
// commit2PC will not used the pinned tablets - to make sure we use the current source, we need to use the gateway's queryservice
func (txc *TxConn) commit2PC(ctx context.Context, session *SafeSession) error {
if len(session.PreSessions) != 0 || len(session.PostSessions) != 0 {
_ = txc.Rollback(ctx, session)
return vterrors.New(vtrpcpb.Code_FAILED_PRECONDITION, "pre or post actions not allowed for 2PC commits")
}
// If the number of participants is one or less, then it's a normal commit.
if len(session.ShardSessions) <= 1 {
return txc.commitNormal(ctx, session)
}
participants := make([]*querypb.Target, 0, len(session.ShardSessions)-1)
for _, s := range session.ShardSessions[1:] {
participants = append(participants, s.Target)
}
mmShard := session.ShardSessions[0]
dtid := dtids.New(mmShard)
err := txc.tabletGateway.CreateTransaction(ctx, mmShard.Target, dtid, participants)
if err != nil {
// Normal rollback is safe because nothing was prepared yet.
_ = txc.Rollback(ctx, session)
return err
}
err = txc.runSessions(ctx, session.ShardSessions[1:], func(ctx context.Context, s *vtgatepb.Session_ShardSession) error {
return txc.tabletGateway.Prepare(ctx, s.Target, s.TransactionId, dtid)
})
if err != nil {
// TODO(sougou): Perform a more fine-grained cleanup
// including unprepared transactions.
if resumeErr := txc.Resolve(ctx, dtid); resumeErr != nil {
log.Warningf("Rollback failed after Prepare failure: %v", resumeErr)
}
// Return the original error even if the previous operation fails.
return err
}
err = txc.tabletGateway.StartCommit(ctx, mmShard.Target, mmShard.TransactionId, dtid)
if err != nil {
return err
}
err = txc.runSessions(ctx, session.ShardSessions[1:], func(ctx context.Context, s *vtgatepb.Session_ShardSession) error {
return txc.tabletGateway.CommitPrepared(ctx, s.Target, dtid)
})
if err != nil {
return err
}
return txc.tabletGateway.ConcludeTransaction(ctx, mmShard.Target, dtid)
}
// Rollback rolls back the current transaction. There are no retries on this operation.
func (txc *TxConn) Rollback(ctx context.Context, session *SafeSession) error {
if !session.InTransaction() {
return nil
}
defer session.ResetTx()
allsessions := append(session.PreSessions, session.ShardSessions...)
allsessions = append(allsessions, session.PostSessions...)
err := txc.runSessions(ctx, allsessions, func(ctx context.Context, s *vtgatepb.Session_ShardSession) error {
if s.TransactionId == 0 {
return nil
}
qs, err := txc.queryService(s.TabletAlias)
if err != nil {
return err
}
reservedID, err := qs.Rollback(ctx, s.Target, s.TransactionId)
if err != nil {
return err
}
s.TransactionId = 0
s.ReservedId = reservedID
return nil
})
if err != nil {
session.RecordWarning(&querypb.QueryWarning{Message: fmt.Sprintf("rollback encountered an error and connection to all shard for this session is released: %v", err)})
if session.InReservedConn() {
_ = txc.Release(ctx, session)
}
}
return err
}
// Release releases the reserved connection and/or rollbacks the transaction
func (txc *TxConn) Release(ctx context.Context, session *SafeSession) error {
if !session.InTransaction() && !session.InReservedConn() {
return nil
}
defer session.Reset()
allsessions := append(session.PreSessions, session.ShardSessions...)
allsessions = append(allsessions, session.PostSessions...)
return txc.runSessions(ctx, allsessions, func(ctx context.Context, s *vtgatepb.Session_ShardSession) error {
if s.ReservedId == 0 && s.TransactionId == 0 {
return nil
}
qs, err := txc.queryService(s.TabletAlias)
if err != nil {
return err
}
err = qs.Release(ctx, s.Target, s.TransactionId, s.ReservedId)
if err != nil {
return err
}
s.TransactionId = 0
s.ReservedId = 0
return nil
})
}
// ReleaseLock releases the reserved connection used for locking.
func (txc *TxConn) ReleaseLock(ctx context.Context, session *SafeSession) error {
if !session.InLockSession() {
return nil
}
defer session.ResetLock()
session.ClearAdvisoryLock()
ls := session.LockSession
if ls.ReservedId == 0 {
return nil
}
qs, err := txc.queryService(ls.TabletAlias)
if err != nil {
return err
}
return qs.Release(ctx, ls.Target, 0, ls.ReservedId)
}
// ReleaseAll releases all the shard sessions and lock session.
func (txc *TxConn) ReleaseAll(ctx context.Context, session *SafeSession) error {
if !session.InTransaction() && !session.InReservedConn() && !session.InLockSession() {
return nil
}
defer session.ResetAll()
allsessions := append(session.PreSessions, session.ShardSessions...)
allsessions = append(allsessions, session.PostSessions...)
if session.LockSession != nil {
allsessions = append(allsessions, session.LockSession)
}
return txc.runSessions(ctx, allsessions, func(ctx context.Context, s *vtgatepb.Session_ShardSession) error {
if s.ReservedId == 0 && s.TransactionId == 0 {
return nil
}
qs, err := txc.queryService(s.TabletAlias)
if err != nil {
return err
}
err = qs.Release(ctx, s.Target, s.TransactionId, s.ReservedId)
if err != nil {
return err
}
s.TransactionId = 0
s.ReservedId = 0
return nil
})
}
// Resolve resolves the specified 2PC transaction.
func (txc *TxConn) Resolve(ctx context.Context, dtid string) error {
mmShard, err := dtids.ShardSession(dtid)
if err != nil {
return err
}
transaction, err := txc.tabletGateway.ReadTransaction(ctx, mmShard.Target, dtid)
if err != nil {
return err
}
if transaction == nil || transaction.Dtid == "" {
// It was already resolved.
return nil
}
switch transaction.State {
case querypb.TransactionState_PREPARE:
// If state is PREPARE, make a decision to rollback and
// fallthrough to the rollback workflow.
qs, err := txc.queryService(mmShard.TabletAlias)
if err != nil {
return err
}
if err := qs.SetRollback(ctx, mmShard.Target, transaction.Dtid, mmShard.TransactionId); err != nil {
return err
}
fallthrough
case querypb.TransactionState_ROLLBACK:
if err := txc.resumeRollback(ctx, mmShard.Target, transaction); err != nil {
return err
}
case querypb.TransactionState_COMMIT:
if err := txc.resumeCommit(ctx, mmShard.Target, transaction); err != nil {
return err
}
default:
// Should never happen.
return vterrors.Errorf(vtrpcpb.Code_INTERNAL, "invalid state: %v", transaction.State)
}
return nil
}
func (txc *TxConn) resumeRollback(ctx context.Context, target *querypb.Target, transaction *querypb.TransactionMetadata) error {
err := txc.runTargets(transaction.Participants, func(t *querypb.Target) error {
return txc.tabletGateway.RollbackPrepared(ctx, t, transaction.Dtid, 0)
})
if err != nil {
return err
}
return txc.tabletGateway.ConcludeTransaction(ctx, target, transaction.Dtid)
}
func (txc *TxConn) resumeCommit(ctx context.Context, target *querypb.Target, transaction *querypb.TransactionMetadata) error {
err := txc.runTargets(transaction.Participants, func(t *querypb.Target) error {
return txc.tabletGateway.CommitPrepared(ctx, t, transaction.Dtid)
})
if err != nil {
return err
}
return txc.tabletGateway.ConcludeTransaction(ctx, target, transaction.Dtid)
}
// runSessions executes the action for all shardSessions in parallel and returns a consolildated error.
func (txc *TxConn) runSessions(ctx context.Context, shardSessions []*vtgatepb.Session_ShardSession, action func(context.Context, *vtgatepb.Session_ShardSession) error) error {
// Fastpath.
if len(shardSessions) == 1 {
return action(ctx, shardSessions[0])
}
allErrors := new(concurrency.AllErrorRecorder)
var wg sync.WaitGroup
for _, s := range shardSessions {
wg.Add(1)
go func(s *vtgatepb.Session_ShardSession) {
defer wg.Done()
if err := action(ctx, s); err != nil {
allErrors.RecordError(err)
}
}(s)
}
wg.Wait()
return allErrors.AggrError(vterrors.Aggregate)
}
// runTargets executes the action for all targets in parallel and returns a consolildated error.
// Flow is identical to runSessions.
func (txc *TxConn) runTargets(targets []*querypb.Target, action func(*querypb.Target) error) error {
if len(targets) == 1 {
return action(targets[0])
}
allErrors := new(concurrency.AllErrorRecorder)
var wg sync.WaitGroup
for _, t := range targets {
wg.Add(1)
go func(t *querypb.Target) {
defer wg.Done()
if err := action(t); err != nil {
allErrors.RecordError(err)
}
}(t)
}
wg.Wait()
return allErrors.AggrError(vterrors.Aggregate)
}