forked from dolthub/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_engine.go
336 lines (302 loc) · 10.2 KB
/
query_engine.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
// Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tabletserver
import (
"net/http"
"time"
log "github.com/golang/glog"
"golang.org/x/net/context"
"github.com/youtube/vitess/go/stats"
"github.com/youtube/vitess/go/sync2"
"github.com/youtube/vitess/go/vt/concurrency"
"github.com/youtube/vitess/go/vt/dbconfigs"
"github.com/youtube/vitess/go/vt/dbconnpool"
"github.com/youtube/vitess/go/vt/logutil"
"github.com/youtube/vitess/go/vt/tableacl"
"github.com/youtube/vitess/go/vt/tableacl/acl"
vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
)
// QueryEngine implements the core functionality of tabletserver.
// It assumes that no requests will be sent to it before Open is
// called and succeeds.
// Shutdown is done in the following order:
//
// WaitForTxEmpty: There should be no more new calls to Begin
// once this function is called. This will return when there
// are no more pending transactions.
//
// Close: There should be no more pending queries when this
// function is called.
//
// Functions of QueryEngine do not return errors. They instead
// panic with NewTabletError as the error type.
// TODO(sougou): Switch to error return scheme.
type QueryEngine struct {
schemaInfo *SchemaInfo
config Config
dbconfigs dbconfigs.DBConfigs
// Pools
connPool *ConnPool
streamConnPool *ConnPool
// Services
txPool *TxPool
preparedPool *TxPreparedPool
consolidator *sync2.Consolidator
streamQList *QueryList
twoPC *TwoPC
// Vars
strictMode sync2.AtomicInt64
autoCommit sync2.AtomicInt64
maxResultSize sync2.AtomicInt64
maxDMLRows sync2.AtomicInt64
streamBufferSize sync2.AtomicInt64
// tableaclExemptCount count the number of accesses allowed
// based on membership in the superuser ACL
tableaclExemptCount sync2.AtomicInt64
tableaclAllowed *stats.MultiCounters
tableaclDenied *stats.MultiCounters
tableaclPseudoDenied *stats.MultiCounters
strictTableAcl bool
enableTableAclDryRun bool
exemptACL acl.ACL
// Loggers
accessCheckerLogger *logutil.ThrottledLogger
// Stats
queryServiceStats *QueryServiceStats
}
// Helper method for conn pools to convert errors
func getOrPanic(ctx context.Context, pool *ConnPool) *DBConn {
conn, err := pool.Get(ctx)
if err == nil {
return conn
}
if err == ErrConnPoolClosed {
panic(ErrConnPoolClosed)
}
// If there's a problem with getting a connection out of the pool, that is
// probably not due to the query itself. The query might succeed on a different
// tablet.
panic(NewTabletErrorSQL(vtrpcpb.ErrorCode_INTERNAL_ERROR, err))
}
// NewQueryEngine creates a new QueryEngine.
// This is a singleton class.
// You must call this only once.
func NewQueryEngine(checker MySQLChecker, config Config) *QueryEngine {
qe := &QueryEngine{config: config}
qe.queryServiceStats = NewQueryServiceStats(config.StatsPrefix, config.EnablePublishStats)
qe.schemaInfo = NewSchemaInfo(
config.StatsPrefix,
checker,
config.QueryCacheSize,
time.Duration(config.SchemaReloadTime*1e9),
time.Duration(config.IdleTimeout*1e9),
map[string]string{
debugQueryPlansKey: config.DebugURLPrefix + "/query_plans",
debugQueryStatsKey: config.DebugURLPrefix + "/query_stats",
debugSchemaKey: config.DebugURLPrefix + "/schema",
debugQueryRulesKey: config.DebugURLPrefix + "/query_rules",
},
config.EnablePublishStats,
qe.queryServiceStats,
)
qe.connPool = NewConnPool(
config.PoolNamePrefix+"ConnPool",
config.PoolSize,
time.Duration(config.IdleTimeout*1e9),
config.EnablePublishStats,
qe.queryServiceStats,
checker,
)
qe.streamConnPool = NewConnPool(
config.PoolNamePrefix+"StreamConnPool",
config.StreamPoolSize,
time.Duration(config.IdleTimeout*1e9),
config.EnablePublishStats,
qe.queryServiceStats,
checker,
)
qe.txPool = NewTxPool(
config.PoolNamePrefix+"TransactionPool",
config.StatsPrefix,
config.TransactionCap,
time.Duration(config.TransactionTimeout*1e9),
time.Duration(config.IdleTimeout*1e9),
config.EnablePublishStats,
qe.queryServiceStats,
checker,
)
// Set the prepared pool capacity to something lower than
// tx pool capacity. Those spare connections are needed to
// perform metadata state change operations. Without this,
// the system can deadlock if all connections get moved to
// the TxPreparedPool.
prepCap := config.TransactionCap - 2
if prepCap < 0 {
// A capacity of 0 means that Prepare will always fail.
prepCap = 0
}
qe.preparedPool = NewTxPreparedPool(prepCap)
qe.twoPC = NewTwoPC()
qe.consolidator = sync2.NewConsolidator()
http.Handle(config.DebugURLPrefix+"/consolidations", qe.consolidator)
qe.streamQList = NewQueryList()
if config.StrictMode {
qe.strictMode.Set(1)
}
if config.EnableAutoCommit {
qe.autoCommit.Set(1)
}
qe.strictTableAcl = config.StrictTableAcl
qe.enableTableAclDryRun = config.EnableTableAclDryRun
if config.TableAclExemptACL != "" {
if f, err := tableacl.GetCurrentAclFactory(); err == nil {
if exemptACL, err := f.New([]string{config.TableAclExemptACL}); err == nil {
log.Infof("Setting Table ACL exempt rule for %v", config.TableAclExemptACL)
qe.exemptACL = exemptACL
} else {
log.Infof("Cannot build exempt ACL for table ACL: %v", err)
}
} else {
log.Infof("Cannot get current ACL Factory: %v", err)
}
}
qe.maxResultSize = sync2.NewAtomicInt64(int64(config.MaxResultSize))
qe.maxDMLRows = sync2.NewAtomicInt64(int64(config.MaxDMLRows))
qe.streamBufferSize = sync2.NewAtomicInt64(int64(config.StreamBufferSize))
qe.accessCheckerLogger = logutil.NewThrottledLogger("accessChecker", 1*time.Second)
var tableACLAllowedName string
var tableACLDeniedName string
var tableACLPseudoDeniedName string
if config.EnablePublishStats {
stats.Publish(config.StatsPrefix+"MaxResultSize", stats.IntFunc(qe.maxResultSize.Get))
stats.Publish(config.StatsPrefix+"MaxDMLRows", stats.IntFunc(qe.maxDMLRows.Get))
stats.Publish(config.StatsPrefix+"StreamBufferSize", stats.IntFunc(qe.streamBufferSize.Get))
stats.Publish(config.StatsPrefix+"TableACLExemptCount", stats.IntFunc(qe.tableaclExemptCount.Get))
tableACLAllowedName = "TableACLAllowed"
tableACLDeniedName = "TableACLDenied"
tableACLPseudoDeniedName = "TableACLPseudoDenied"
}
qe.tableaclAllowed = stats.NewMultiCounters(tableACLAllowedName, []string{"TableName", "TableGroup", "PlanID", "Username"})
qe.tableaclDenied = stats.NewMultiCounters(tableACLDeniedName, []string{"TableName", "TableGroup", "PlanID", "Username"})
qe.tableaclPseudoDenied = stats.NewMultiCounters(tableACLPseudoDeniedName, []string{"TableName", "TableGroup", "PlanID", "Username"})
return qe
}
// Open must be called before sending requests to QueryEngine.
func (qe *QueryEngine) Open(dbconfigs dbconfigs.DBConfigs) {
qe.dbconfigs = dbconfigs
appParams := dbconfigs.App
// Create dba params based on App connection params
// and Dba credentials.
dbaParams := dbconfigs.App
if dbconfigs.Dba.Uname != "" {
dbaParams.Uname = dbconfigs.Dba.Uname
dbaParams.Pass = dbconfigs.Dba.Pass
}
strictMode := false
if qe.strictMode.Get() != 0 {
strictMode = true
}
start := time.Now()
qe.schemaInfo.Open(&dbaParams, strictMode)
log.Infof("Time taken to load the schema: %v", time.Now().Sub(start))
qe.connPool.Open(&appParams, &dbaParams)
qe.streamConnPool.Open(&appParams, &dbaParams)
qe.txPool.Open(&appParams, &dbaParams)
qe.twoPC.Open(qe.dbconfigs.SidecarDBName, &dbaParams)
}
// IsMySQLReachable returns true if we can connect to MySQL.
func (qe *QueryEngine) IsMySQLReachable() bool {
conn, err := dbconnpool.NewDBConnection(&qe.dbconfigs.App, qe.queryServiceStats.MySQLStats)
if err != nil {
if IsConnErr(err) {
return false
}
log.Warningf("checking MySQL, unexpected error: %v", err)
return true
}
conn.Close()
return true
}
// PrepareFromRedo replays and prepares the transactions
// from the redo log. It also loads previously failed transactions
// into the reserved list. This is called when a tablet becomes
// a master.
// TODO(sougou): Make this function set the lastId for tx pool to be
// greater than all those used by dtids. This will prevent dtid
// collisions.
func (qe *QueryEngine) PrepareFromRedo() error {
ctx := context.Background()
var allErr concurrency.AllErrorRecorder
readConn, err := qe.connPool.Get(ctx)
if err != nil {
return err
}
defer readConn.Recycle()
prepared, failed, err := qe.twoPC.ReadAllRedo(ctx, readConn)
if err != nil {
return err
}
outer:
for dtid, tx := range prepared {
conn, err := qe.txPool.LocalBegin(ctx)
if err != nil {
allErr.RecordError(err)
continue
}
for _, stmt := range tx {
conn.RecordQuery(stmt)
_, err := conn.Exec(ctx, stmt, 1, false)
if err != nil {
allErr.RecordError(err)
qe.txPool.LocalConclude(ctx, conn)
continue outer
}
}
// We should not use the external Prepare because
// we don't want to write again to the redo log.
err = qe.preparedPool.Put(conn, dtid)
if err != nil {
allErr.RecordError(err)
continue
}
}
for _, dtid := range failed {
qe.preparedPool.SetFailed(dtid)
}
return allErr.Error()
}
// RollbackTransactions rolls back all open transactions
// including the prepared ones.
// This is used for transitioning from a master to a non-master
// serving type.
func (qe *QueryEngine) RollbackTransactions() {
ctx := context.Background()
// The order of rollbacks is currently not material because
// we don't allow new statements or commits during
// this function. In case of any such change, this will
// have to be revisited.
qe.txPool.RollbackNonBusy(ctx)
for _, c := range qe.preparedPool.FetchAll() {
qe.txPool.LocalConclude(ctx, c)
}
// If there are stray transactions, we must wait.
qe.WaitForTxEmpty()
}
// WaitForTxEmpty must be called before calling Close.
// Before calling WaitForTxEmpty, you must ensure that there
// will be no more calls to Begin.
func (qe *QueryEngine) WaitForTxEmpty() {
qe.txPool.WaitForEmpty()
}
// Close must be called to shut down QueryEngine.
// You must ensure that no more queries will be sent
// before calling Close.
func (qe *QueryEngine) Close() {
// Close in reverse order of Open.
qe.twoPC.Close()
qe.txPool.Close()
qe.streamConnPool.Close()
qe.connPool.Close()
qe.schemaInfo.Close()
}