-
Notifications
You must be signed in to change notification settings - Fork 271
/
internal_executor.go
465 lines (382 loc) · 12.2 KB
/
internal_executor.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
// Copyright 2022 Matrix Origin
//
// 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 frontend
import (
"context"
"sync"
"github.com/fagongzi/goetty/v2"
"go.uber.org/zap"
"github.com/matrixorigin/matrixone/pkg/common/mpool"
"github.com/matrixorigin/matrixone/pkg/common/runtime"
"github.com/matrixorigin/matrixone/pkg/defines"
"github.com/matrixorigin/matrixone/pkg/logutil"
ie "github.com/matrixorigin/matrixone/pkg/util/internalExecutor"
"github.com/matrixorigin/matrixone/pkg/util/trace"
"github.com/matrixorigin/matrixone/pkg/vm/process"
)
const DefaultTenantMoAdmin = "sys:internal:moadmin"
func applyOverride(sess *Session, opts ie.SessionOverrideOptions) {
if opts.Database != nil {
sess.SetDatabaseName(*opts.Database)
}
if opts.Username != nil {
sess.GetMysqlProtocol().SetUserName(*opts.Username)
}
if opts.IsInternal != nil {
sess.isInternal = *opts.IsInternal
}
acc := sess.GetTenantInfo()
if acc != nil {
if opts.AccountId != nil {
acc.SetTenantID(*opts.AccountId)
}
if opts.UserId != nil {
acc.SetUserID(*opts.UserId)
}
if opts.DefaultRoleId != nil {
acc.SetDefaultRoleID(*opts.DefaultRoleId)
}
}
}
type internalExecutor struct {
sync.Mutex
proto *internalProtocol
baseSessOpts ie.SessionOverrideOptions
}
func NewInternalExecutor() *internalExecutor {
return newIe()
}
func newIe() *internalExecutor {
proto := &internalProtocol{result: &internalExecResult{}}
ret := &internalExecutor{
proto: proto,
baseSessOpts: ie.NewOptsBuilder().Finish(),
}
return ret
}
type internalExecResult struct {
affectedRows uint64
resultSet *MysqlResultSet
dropped uint64
err error
}
func (res *internalExecResult) Error() error {
return res.err
}
func (res *internalExecResult) ColumnCount() uint64 {
return res.resultSet.GetColumnCount()
}
func (res *internalExecResult) Column(ctx context.Context, i uint64) (name string, typ uint8, signed bool, err error) {
col, err := res.resultSet.GetColumn(ctx, i)
if err == nil {
name = col.Name()
typ = uint8(col.ColumnType())
signed = col.IsSigned()
}
return
}
func (res *internalExecResult) RowCount() uint64 {
return res.resultSet.GetRowCount()
}
func (res *internalExecResult) Row(ctx context.Context, i uint64) ([]interface{}, error) {
return res.resultSet.GetRow(ctx, i)
}
func (res *internalExecResult) Value(ctx context.Context, ridx uint64, cidx uint64) (interface{}, error) {
return res.resultSet.GetValue(ctx, ridx, cidx)
}
func (res *internalExecResult) ValueByName(ctx context.Context, ridx uint64, col string) (interface{}, error) {
return res.resultSet.GetValueByName(ctx, ridx, col)
}
func (res *internalExecResult) StringValueByName(ctx context.Context, ridx uint64, col string) (string, error) {
if cidx, err := res.resultSet.columnName2Index(ctx, col); err != nil {
return "", err
} else {
return res.resultSet.GetString(ctx, ridx, cidx)
}
}
func (res *internalExecResult) Float64ValueByName(ctx context.Context, ridx uint64, col string) (float64, error) {
if cidx, err := res.resultSet.columnName2Index(ctx, col); err != nil {
return 0.0, err
} else {
return res.resultSet.GetFloat64(ctx, ridx, cidx)
}
}
func (ie *internalExecutor) Exec(ctx context.Context, sql string, opts ie.SessionOverrideOptions) (err error) {
ie.Lock()
defer ie.Unlock()
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, getGlobalPu().SV.SessionTimeout.Duration)
defer cancel()
sess := ie.newCmdSession(ctx, opts)
defer func() {
sess.Close()
}()
ie.proto.stashResult = false
if sql == "" {
return
}
tempExecCtx := ExecCtx{
reqCtx: ctx,
ses: sess,
}
return doComQuery(sess, &tempExecCtx, &UserInput{sql: sql})
}
func (ie *internalExecutor) Query(ctx context.Context, sql string, opts ie.SessionOverrideOptions) ie.InternalExecResult {
ie.Lock()
defer ie.Unlock()
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, getGlobalPu().SV.SessionTimeout.Duration)
defer cancel()
sess := ie.newCmdSession(ctx, opts)
defer sess.Close()
ie.proto.stashResult = true
logutil.Info("internalExecutor new session", trace.ContextField(ctx), zap.String("session uuid", sess.uuid.String()))
tempExecCtx := ExecCtx{
reqCtx: ctx,
ses: sess,
}
err := doComQuery(sess, &tempExecCtx, &UserInput{sql: sql})
res := ie.proto.swapOutResult()
res.err = err
return res
}
func (ie *internalExecutor) newCmdSession(ctx context.Context, opts ie.SessionOverrideOptions) *Session {
// Use the Mid configuration for session. We can make Mid a configuration
// param, or, compute from GuestMmuLimitation. Lazy.
//
// XXX MPOOL
// Cannot use Mid. Turns out we create a Session for *EVERY QUERY*
// If we preallocate anything, we will explode.
//
// Session does not have a close call. We need a Close() call in the Exec/Query method above.
//
mp, err := mpool.NewMPool("internal_exec_cmd_session", getGlobalPu().SV.GuestMmuLimitation, mpool.NoFixed)
if err != nil {
logutil.Fatalf("internalExecutor cannot create mpool in newCmdSession")
panic(err)
}
sess := NewSession(ctx, ie.proto, mp, GSysVariables, true, nil)
sess.disableTrace = true
var t *TenantInfo
if accountId, err := defines.GetAccountId(ctx); err == nil {
t = &TenantInfo{
TenantID: accountId,
UserID: defines.GetUserId(ctx),
DefaultRoleID: defines.GetRoleId(ctx),
}
if accountId == sysAccountID {
t.Tenant = sysAccountName // fixme: fix empty tencent value, while do metric collection.
t.User = "internal"
// more details in authenticateUserCanExecuteStatementWithObjectTypeNone()
t.DefaultRole = moAdminRoleName
}
} else {
t, _ = GetTenantInfo(ctx, DefaultTenantMoAdmin)
}
sess.SetTenantInfo(t)
applyOverride(sess, ie.baseSessOpts)
applyOverride(sess, opts)
//make sure init tasks can see the prev task's data
now, _ := runtime.ProcessLevelRuntime().Clock().Now()
sess.lastCommitTS = now
return sess
}
func (ie *internalExecutor) ApplySessionOverride(opts ie.SessionOverrideOptions) {
ie.baseSessOpts = opts
}
// func showCaller() {
// pc, _, _, _ := runtime.Caller(1)
// callFunc := runtime.FuncForPC(pc)
// logutil.Infof("[Metric] called: %s", callFunc.Name())
// }
var _ MysqlProtocol = &internalProtocol{}
type internalProtocol struct {
sync.Mutex
stashResult bool
result *internalExecResult
database string
username string
}
func (ip *internalProtocol) UpdateCtx(ctx context.Context) {
}
func (ip *internalProtocol) GetCapability() uint32 {
return DefaultCapability
}
func (ip *internalProtocol) SetCapability(uint32) {
}
func (ip *internalProtocol) IsTlsEstablished() bool {
return true
}
func (ip *internalProtocol) SetTlsEstablished() {
}
func (ip *internalProtocol) HandleHandshake(ctx context.Context, payload []byte) (bool, error) {
return false, nil
}
func (ip *internalProtocol) Authenticate(ctx context.Context) error {
return nil
}
func (ip *internalProtocol) GetTcpConnection() goetty.IOSession {
return nil
}
func (ip *internalProtocol) GetDebugString() string {
return "internal protocol"
}
func (ip *internalProtocol) GetSequenceId() uint8 {
return 0
}
func (ip *internalProtocol) GetConnectAttrs() map[string]string {
return nil
}
func (ip *internalProtocol) SetSequenceID(value uint8) {
}
func (ip *internalProtocol) IsEstablished() bool {
return true
}
func (ip *internalProtocol) ParseSendLongData(ctx context.Context, proc *process.Process, stmt *PrepareStmt, data []byte, pos int) error {
return nil
}
func (ip *internalProtocol) ParseExecuteData(ctx context.Context, proc *process.Process, stmt *PrepareStmt, data []byte, pos int) error {
return nil
}
func (ip *internalProtocol) SendPrepareResponse(ctx context.Context, stmt *PrepareStmt) error {
return nil
}
func (ip *internalProtocol) SetEstablished() {}
func (ip *internalProtocol) GetRequest(payload []byte) *Request {
panic("not impl")
}
// ConnectionID the identity of the client
func (ip *internalProtocol) ConnectionID() uint32 {
return 74751101
}
// Peer gets the address [Host:Port] of the client
func (ip *internalProtocol) Peer() string {
return "0.0.0.0:0"
}
func (ip *internalProtocol) GetDatabaseName() string {
return ip.database
}
func (ip *internalProtocol) SetDatabaseName(database string) {
ip.database = database
}
func (ip *internalProtocol) GetUserName() string {
return ip.username
}
func (ip *internalProtocol) SetUserName(username string) {
ip.username = username
}
func (ip *internalProtocol) Quit() {}
func (ip *internalProtocol) sendRows(mrs *MysqlResultSet, cnt uint64) error {
if ip.stashResult {
res := ip.result.resultSet
if res == nil {
res = &MysqlResultSet{}
ip.result.resultSet = res
}
if res.GetRowCount() > 100 {
ip.result.dropped += cnt
return nil
}
if res.GetColumnCount() == 0 {
for _, col := range mrs.Columns {
res.AddColumn(col)
}
}
colCnt := res.GetColumnCount()
for i := uint64(0); i < cnt; i++ {
row := make([]any, colCnt)
copy(row, mrs.Data[i])
res.Data = append(res.Data, row)
}
}
ip.result.affectedRows += cnt
return nil
}
func (ip *internalProtocol) swapOutResult() *internalExecResult {
ret := ip.result
if ret.resultSet == nil {
ret.resultSet = &MysqlResultSet{}
}
ip.result = &internalExecResult{}
return ret
}
// the server send group row of the result set as an independent packet thread safe
func (ip *internalProtocol) SendResultSetTextBatchRow(mrs *MysqlResultSet, cnt uint64) error {
ip.Lock()
defer ip.Unlock()
return ip.sendRows(mrs, cnt)
}
func (ip *internalProtocol) SendResultSetTextBatchRowSpeedup(mrs *MysqlResultSet, cnt uint64) error {
ip.Lock()
defer ip.Unlock()
return ip.sendRows(mrs, cnt)
}
// SendColumnDefinitionPacket the server send the column definition to the client
func (ip *internalProtocol) SendColumnDefinitionPacket(ctx context.Context, column Column, cmd int) error {
return nil
}
// SendColumnCountPacket makes the column count packet
func (ip *internalProtocol) SendColumnCountPacket(count uint64) error {
return nil
}
// SendResponse sends a response to the client for the application request
func (ip *internalProtocol) SendResponse(ctx context.Context, resp *Response) error {
ip.Lock()
defer ip.Unlock()
ip.ResetStatistics()
if resp.category == ResultResponse {
if mer := resp.data.(*MysqlExecutionResult); mer != nil && mer.Mrs() != nil {
ip.sendRows(mer.Mrs(), mer.mrs.GetRowCount())
}
} else {
// OkResponse. this is NOT ErrorResponse because error will be returned by doComQuery
ip.result.affectedRows = resp.affectedRows
}
return nil
}
// SendEOFPacketIf ends the sending of columns definations
func (ip *internalProtocol) SendEOFPacketIf(warnings uint16, status uint16) error {
return nil
}
// sendOKPacket sends OK packet to the client, used in the end of sql like use <database>
func (ip *internalProtocol) sendOKPacket(affectedRows uint64, lastInsertId uint64, status uint16, warnings uint16, message string) error {
ip.result.affectedRows = affectedRows
return nil
}
// sendEOFOrOkPacket sends the OK or EOF packet thread safe, and ends the sending of result set
func (ip *internalProtocol) sendEOFOrOkPacket(warnings uint16, status uint16) error {
return nil
}
func (ip *internalProtocol) ResetStatistics() {
ip.result.affectedRows = 0
ip.result.dropped = 0
ip.result.err = nil
ip.result.resultSet = nil
}
func (ip *internalProtocol) GetStats() string { return "internal unknown stats" }
func (ip *internalProtocol) CalculateOutTrafficBytes(reset bool) (int64, int64) { return 0, 0 }
func (ip *internalProtocol) sendLocalInfileRequest(filename string) error {
return nil
}
func (ip *internalProtocol) incDebugCount(int) {}
func (ip *internalProtocol) resetDebugCount() []uint64 {
return nil
}
func (ip *internalProtocol) DisableAutoFlush() {
}
func (ip *internalProtocol) EnableAutoFlush() {
}
func (ip *internalProtocol) Flush() error {
return nil
}