-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
dbconn.go
541 lines (482 loc) · 15.4 KB
/
dbconn.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
/*
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 connpool
import (
"context"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"vitess.io/vitess/go/mysql/sqlerror"
"vitess.io/vitess/go/pools"
"vitess.io/vitess/go/vt/dbconfigs"
"vitess.io/vitess/go/vt/servenv"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/trace"
"vitess.io/vitess/go/vt/dbconnpool"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"
querypb "vitess.io/vitess/go/vt/proto/query"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
// DBConn is a db connection for tabletserver.
// It performs automatic reconnects as needed.
// Its Execute function has a timeout that can kill
// its own queries and the underlying connection.
// It will also trigger a CheckMySQL whenever applicable.
type DBConn struct {
conn *dbconnpool.DBConnection
info dbconfigs.Connector
pool *Pool
dbaPool *dbconnpool.ConnectionPool
stats *tabletenv.Stats
current atomic.Value
timeCreated time.Time
setting string
resetSetting string
// err will be set if a query is killed through a Kill.
errmu sync.Mutex
err error
}
// NewDBConn creates a new DBConn. It triggers a CheckMySQL if creation fails.
func NewDBConn(ctx context.Context, cp *Pool, appParams dbconfigs.Connector) (*DBConn, error) {
start := time.Now()
defer cp.env.Stats().MySQLTimings.Record("Connect", start)
c, err := dbconnpool.NewDBConnection(ctx, appParams)
if err != nil {
cp.env.Stats().MySQLTimings.Record("ConnectError", start)
cp.env.CheckMySQL()
return nil, err
}
db := &DBConn{
conn: c,
info: appParams,
pool: cp,
dbaPool: cp.dbaPool,
timeCreated: time.Now(),
stats: cp.env.Stats(),
}
db.current.Store("")
return db, nil
}
// NewDBConnNoPool creates a new DBConn without a pool.
func NewDBConnNoPool(ctx context.Context, params dbconfigs.Connector, dbaPool *dbconnpool.ConnectionPool, setting *pools.Setting) (*DBConn, error) {
c, err := dbconnpool.NewDBConnection(ctx, params)
if err != nil {
return nil, err
}
dbconn := &DBConn{
conn: c,
info: params,
dbaPool: dbaPool,
pool: nil,
timeCreated: time.Now(),
stats: tabletenv.NewStats(servenv.NewExporter("Temp", "Tablet")),
}
dbconn.current.Store("")
if setting == nil {
return dbconn, nil
}
if err = dbconn.ApplySetting(ctx, setting); err != nil {
dbconn.Close()
return nil, err
}
return dbconn, nil
}
// Err returns an error if there was a client initiated error
// like a query kill.
func (dbc *DBConn) Err() error {
dbc.errmu.Lock()
defer dbc.errmu.Unlock()
return dbc.err
}
// Exec executes the specified query. If there is a connection error, it will reconnect
// and retry. A failed reconnect will trigger a CheckMySQL.
func (dbc *DBConn) Exec(ctx context.Context, query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
span, ctx := trace.NewSpan(ctx, "DBConn.Exec")
defer span.Finish()
for attempt := 1; attempt <= 2; attempt++ {
r, err := dbc.execOnce(ctx, query, maxrows, wantfields)
switch {
case err == nil:
// Success.
return r, nil
case sqlerror.IsConnLostDuringQuery(err):
// Query probably killed. Don't retry.
return nil, err
case !sqlerror.IsConnErr(err):
// Not a connection error. Don't retry.
return nil, err
case attempt == 2:
// Reached the retry limit.
return nil, err
}
// Connection error. Retry if context has not expired.
select {
case <-ctx.Done():
return nil, err
default:
}
if reconnectErr := dbc.reconnect(ctx); reconnectErr != nil {
dbc.pool.env.CheckMySQL()
// Return the error of the reconnect and not the original connection error.
return nil, reconnectErr
}
// Reconnect succeeded. Retry query at second attempt.
}
panic("unreachable")
}
func (dbc *DBConn) execOnce(ctx context.Context, query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
dbc.current.Store(query)
defer dbc.current.Store("")
// Check if the context is already past its deadline before
// trying to execute the query.
select {
case <-ctx.Done():
return nil, fmt.Errorf("%v before execution started", ctx.Err())
default:
}
defer dbc.stats.MySQLTimings.Record("Exec", time.Now())
done, wg := dbc.setDeadline(ctx)
qr, err := dbc.conn.ExecuteFetch(query, maxrows, wantfields)
if done != nil {
close(done)
wg.Wait()
}
if dbcerr := dbc.Err(); dbcerr != nil {
return nil, dbcerr
}
return qr, err
}
// ExecOnce executes the specified query, but does not retry on connection errors.
func (dbc *DBConn) ExecOnce(ctx context.Context, query string, maxrows int, wantfields bool) (*sqltypes.Result, error) {
return dbc.execOnce(ctx, query, maxrows, wantfields)
}
// FetchNext returns the next result set.
func (dbc *DBConn) FetchNext(ctx context.Context, maxrows int, wantfields bool) (*sqltypes.Result, error) {
// Check if the context is already past its deadline before
// trying to fetch the next result.
select {
case <-ctx.Done():
return nil, fmt.Errorf("%v before reading next result set", ctx.Err())
default:
}
res, _, _, err := dbc.conn.ReadQueryResult(maxrows, wantfields)
if err != nil {
return nil, err
}
return res, err
}
// Stream executes the query and streams the results.
func (dbc *DBConn) Stream(ctx context.Context, query string, callback func(*sqltypes.Result) error, alloc func() *sqltypes.Result, streamBufferSize int, includedFields querypb.ExecuteOptions_IncludedFields) error {
span, ctx := trace.NewSpan(ctx, "DBConn.Stream")
trace.AnnotateSQL(span, sqlparser.Preview(query))
defer span.Finish()
resultSent := false
for attempt := 1; attempt <= 2; attempt++ {
err := dbc.streamOnce(
ctx,
query,
func(r *sqltypes.Result) error {
if !resultSent {
resultSent = true
r = r.StripMetadata(includedFields)
}
return callback(r)
},
alloc,
streamBufferSize,
)
switch {
case err == nil:
// Success.
return nil
case sqlerror.IsConnLostDuringQuery(err):
// Query probably killed. Don't retry.
return err
case !sqlerror.IsConnErr(err):
// Not a connection error. Don't retry.
return err
case attempt == 2:
// Reached the retry limit.
return err
case resultSent:
// Don't retry if streaming has started.
return err
}
// Connection error. Retry if context has not expired.
select {
case <-ctx.Done():
return err
default:
}
if reconnectErr := dbc.reconnect(ctx); reconnectErr != nil {
dbc.pool.env.CheckMySQL()
// Return the error of the reconnect and not the original connection error.
return reconnectErr
}
}
panic("unreachable")
}
func (dbc *DBConn) streamOnce(ctx context.Context, query string, callback func(*sqltypes.Result) error, alloc func() *sqltypes.Result, streamBufferSize int) error {
defer dbc.stats.MySQLTimings.Record("ExecStream", time.Now())
dbc.current.Store(query)
defer dbc.current.Store("")
done, wg := dbc.setDeadline(ctx)
err := dbc.conn.ExecuteStreamFetch(query, callback, alloc, streamBufferSize)
if done != nil {
close(done)
wg.Wait()
}
if dbcerr := dbc.Err(); dbcerr != nil {
return dbcerr
}
return err
}
// StreamOnce executes the query and streams the results. But, does not retry on connection errors.
func (dbc *DBConn) StreamOnce(ctx context.Context, query string, callback func(*sqltypes.Result) error, alloc func() *sqltypes.Result, streamBufferSize int, includedFields querypb.ExecuteOptions_IncludedFields) error {
resultSent := false
return dbc.streamOnce(
ctx,
query,
func(r *sqltypes.Result) error {
if !resultSent {
resultSent = true
r = r.StripMetadata(includedFields)
}
return callback(r)
},
alloc,
streamBufferSize,
)
}
var (
getModeSQL = "select @@global.sql_mode"
getAutocommit = "select @@autocommit"
getAutoIsNull = "select @@sql_auto_is_null"
)
// VerifyMode is a helper method to verify mysql is running with
// sql_mode = STRICT_TRANS_TABLES or STRICT_ALL_TABLES and autocommit=ON.
func (dbc *DBConn) VerifyMode(strictTransTables bool) error {
if strictTransTables {
qr, err := dbc.conn.ExecuteFetch(getModeSQL, 2, false)
if err != nil {
return err
}
if len(qr.Rows) != 1 {
return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "incorrect rowcount received for %s: %d", getModeSQL, len(qr.Rows))
}
sqlMode := qr.Rows[0][0].ToString()
if !(strings.Contains(sqlMode, "STRICT_TRANS_TABLES") || strings.Contains(sqlMode, "STRICT_ALL_TABLES")) {
return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "require sql_mode to be STRICT_TRANS_TABLES or STRICT_ALL_TABLES: got '%s'", qr.Rows[0][0].ToString())
}
}
qr, err := dbc.conn.ExecuteFetch(getAutocommit, 2, false)
if err != nil {
return err
}
if len(qr.Rows) != 1 {
return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "incorrect rowcount received for %s: %d", getAutocommit, len(qr.Rows))
}
if !strings.Contains(qr.Rows[0][0].ToString(), "1") {
return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "require autocommit to be 1: got %s", qr.Rows[0][0].ToString())
}
qr, err = dbc.conn.ExecuteFetch(getAutoIsNull, 2, false)
if err != nil {
return err
}
if len(qr.Rows) != 1 {
return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "incorrect rowcount received for %s: %d", getAutoIsNull, len(qr.Rows))
}
if !strings.Contains(qr.Rows[0][0].ToString(), "0") {
return vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "require sql_auto_is_null to be 0: got %s", qr.Rows[0][0].ToString())
}
return nil
}
// Close closes the DBConn.
func (dbc *DBConn) Close() {
dbc.conn.Close()
}
// ApplySetting implements the pools.Resource interface.
func (dbc *DBConn) ApplySetting(ctx context.Context, setting *pools.Setting) error {
query := setting.GetQuery()
if _, err := dbc.execOnce(ctx, query, 1, false); err != nil {
return err
}
dbc.setting = query
dbc.resetSetting = setting.GetResetQuery()
return nil
}
// IsSettingApplied implements the pools.Resource interface.
func (dbc *DBConn) IsSettingApplied() bool {
return dbc.setting != ""
}
// IsSameSetting implements the pools.Resource interface.
func (dbc *DBConn) IsSameSetting(setting string) bool {
return strings.EqualFold(setting, dbc.setting)
}
// ResetSetting implements the pools.Resource interface.
func (dbc *DBConn) ResetSetting(ctx context.Context) error {
if _, err := dbc.execOnce(ctx, dbc.resetSetting, 1, false); err != nil {
return err
}
dbc.setting = ""
dbc.resetSetting = ""
return nil
}
var _ pools.Resource = (*DBConn)(nil)
// IsClosed returns true if DBConn is closed.
func (dbc *DBConn) IsClosed() bool {
return dbc.conn.IsClosed()
}
// Expired returns whether a connection has passed its lifetime
func (dbc *DBConn) Expired(lifetimeTimeout time.Duration) bool {
return lifetimeTimeout > 0 && time.Until(dbc.timeCreated.Add(lifetimeTimeout)) < 0
}
// Recycle returns the DBConn to the pool.
func (dbc *DBConn) Recycle() {
switch {
case dbc.pool == nil:
dbc.Close()
case dbc.conn.IsClosed():
dbc.pool.Put(nil)
default:
dbc.pool.Put(dbc)
}
}
// Taint unregister connection from original pool and taints the connection.
func (dbc *DBConn) Taint() {
if dbc.pool == nil {
return
}
dbc.pool.Put(nil)
dbc.pool = nil
}
// Kill kills the currently executing query both on MySQL side
// and on the connection side. If no query is executing, it's a no-op.
// Kill will also not kill a query more than once.
func (dbc *DBConn) Kill(reason string, elapsed time.Duration) error {
dbc.stats.KillCounters.Add("Queries", 1)
log.Infof("Due to %s, elapsed time: %v, killing query ID %v %s", reason, elapsed, dbc.conn.ID(), dbc.CurrentForLogging())
// Client side action. Set error and close connection.
dbc.errmu.Lock()
dbc.err = vterrors.Errorf(vtrpcpb.Code_CANCELED, "(errno 2013) due to %s, elapsed time: %v, killing query ID %v", reason, elapsed, dbc.conn.ID())
dbc.errmu.Unlock()
dbc.conn.Close()
// Server side action. Kill the session.
killConn, err := dbc.dbaPool.Get(context.TODO())
if err != nil {
log.Warningf("Failed to get conn from dba pool: %v", err)
return err
}
defer killConn.Recycle()
sql := fmt.Sprintf("kill %d", dbc.conn.ID())
_, err = killConn.ExecuteFetch(sql, 10000, false)
if err != nil {
log.Errorf("Could not kill query ID %v %s: %v", dbc.conn.ID(),
dbc.CurrentForLogging(), err)
return err
}
return nil
}
// Current returns the currently executing query.
func (dbc *DBConn) Current() string {
return dbc.current.Load().(string)
}
// ID returns the connection id.
func (dbc *DBConn) ID() int64 {
return dbc.conn.ID()
}
// BaseShowTables returns a query that shows tables
func (dbc *DBConn) BaseShowTables() string {
return dbc.conn.BaseShowTables()
}
// BaseShowTablesWithSizes returns a query that shows tables and their sizes
func (dbc *DBConn) BaseShowTablesWithSizes() string {
return dbc.conn.BaseShowTablesWithSizes()
}
func (dbc *DBConn) reconnect(ctx context.Context) error {
dbc.conn.Close()
// Reuse MySQLTimings from dbc.conn.
newConn, err := dbconnpool.NewDBConnection(ctx, dbc.info)
if err != nil {
return err
}
dbc.conn = newConn
if dbc.IsSettingApplied() {
err = dbc.applySameSetting(ctx)
if err != nil {
return err
}
}
dbc.errmu.Lock()
dbc.err = nil
dbc.errmu.Unlock()
return nil
}
// setDeadline starts a goroutine that will kill the currently executing query
// if the deadline is exceeded. It returns a channel and a waitgroup. After the
// query is done executing, the caller is required to close the done channel
// and wait for the waitgroup to make sure that the necessary cleanup is done.
func (dbc *DBConn) setDeadline(ctx context.Context) (chan bool, *sync.WaitGroup) {
if ctx.Done() == nil {
return nil, nil
}
done := make(chan bool)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
startTime := time.Now()
select {
case <-ctx.Done():
dbc.Kill(ctx.Err().Error(), time.Since(startTime))
case <-done:
return
}
elapsed := time.Since(startTime)
// Give 2x the elapsed time and some buffer as grace period
// for the query to get killed.
tmr2 := time.NewTimer(2*elapsed + 5*time.Second)
defer tmr2.Stop()
select {
case <-tmr2.C:
dbc.stats.InternalErrors.Add("HungQuery", 1)
log.Warningf("Query may be hung: %s", dbc.CurrentForLogging())
case <-done:
return
}
<-done
log.Warningf("Hung query returned")
}()
return done, &wg
}
// CurrentForLogging applies transformations to the query making it suitable to log.
// It applies sanitization rules based on tablet settings and limits the max length of
// queries.
func (dbc *DBConn) CurrentForLogging() string {
var queryToLog string
if dbc.pool != nil && dbc.pool.env != nil && dbc.pool.env.Config() != nil && !dbc.pool.env.Config().SanitizeLogMessages {
queryToLog = dbc.Current()
} else {
queryToLog, _ = sqlparser.RedactSQLQuery(dbc.Current())
}
return sqlparser.TruncateForLog(queryToLog)
}
func (dbc *DBConn) applySameSetting(ctx context.Context) (err error) {
_, err = dbc.execOnce(ctx, dbc.setting, 1, false)
return
}