forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrie.go
781 lines (683 loc) · 21.4 KB
/
brie.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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
// Copyright 2020 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 executor
import (
"bytes"
"context"
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
backuppb "github.com/pingcap/kvproto/pkg/brpb"
"github.com/pingcap/kvproto/pkg/encryptionpb"
"github.com/pingcap/log"
"github.com/pingcap/tidb/br/pkg/glue"
"github.com/pingcap/tidb/br/pkg/storage"
"github.com/pingcap/tidb/br/pkg/task"
"github.com/pingcap/tidb/br/pkg/task/show"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/domain"
"github.com/pingcap/tidb/expression"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta/autoid"
"github.com/pingcap/tidb/parser/ast"
"github.com/pingcap/tidb/parser/format"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/parser/mysql"
"github.com/pingcap/tidb/parser/terror"
"github.com/pingcap/tidb/sessionctx"
"github.com/pingcap/tidb/sessionctx/stmtctx"
"github.com/pingcap/tidb/types"
"github.com/pingcap/tidb/util/chunk"
"github.com/pingcap/tidb/util/dbterror/exeerrors"
"github.com/pingcap/tidb/util/printer"
"github.com/pingcap/tidb/util/sem"
"github.com/pingcap/tidb/util/sqlexec"
"github.com/pingcap/tidb/util/syncutil"
filter "github.com/pingcap/tidb/util/table-filter"
"github.com/tikv/client-go/v2/oracle"
pd "github.com/tikv/pd/client"
"go.uber.org/zap"
)
const clearInterval = 10 * time.Minute
var outdatedDuration = types.Duration{
Duration: 30 * time.Minute,
Fsp: types.DefaultFsp,
}
// brieTaskProgress tracks a task's current progress.
type brieTaskProgress struct {
// current progress of the task.
// this field is atomically updated outside of the lock below.
current int64
// lock is the mutex protected the two fields below.
lock syncutil.Mutex
// cmd is the name of the step the BRIE task is currently performing.
cmd string
// total is the total progress of the task.
// the percentage of completeness is `(100%) * current / total`.
total int64
}
// Inc implements glue.Progress
func (p *brieTaskProgress) Inc() {
atomic.AddInt64(&p.current, 1)
}
// IncBy implements glue.Progress
func (p *brieTaskProgress) IncBy(cnt int64) {
atomic.AddInt64(&p.current, cnt)
}
// GetCurrent implements glue.Progress
func (p *brieTaskProgress) GetCurrent() int64 {
return atomic.LoadInt64(&p.current)
}
// Close implements glue.Progress
func (p *brieTaskProgress) Close() {
p.lock.Lock()
current := atomic.LoadInt64(&p.current)
if current < p.total {
p.cmd = fmt.Sprintf("%s Cacneled", p.cmd)
}
atomic.StoreInt64(&p.current, p.total)
p.lock.Unlock()
}
type brieTaskInfo struct {
id uint64
query string
queueTime types.Time
execTime types.Time
finishTime types.Time
kind ast.BRIEKind
storage string
connID uint64
backupTS uint64
restoreTS uint64
archiveSize uint64
message string
}
type brieQueueItem struct {
info *brieTaskInfo
progress *brieTaskProgress
cancel func()
}
type brieQueue struct {
nextID uint64
tasks sync.Map
lastClearTime time.Time
workerCh chan struct{}
}
// globalBRIEQueue is the BRIE execution queue. Only one BRIE task can be executed each time.
// TODO: perhaps copy the DDL Job queue so only one task can be executed in the whole cluster.
var globalBRIEQueue = &brieQueue{
workerCh: make(chan struct{}, 1),
}
// ResetGlobalBRIEQueueForTest resets the ID allocation for the global BRIE queue.
// In some of our test cases, we rely on the ID is allocated from 1.
// When batch executing test cases, the assumation may be broken and make the cases fail.
func ResetGlobalBRIEQueueForTest() {
globalBRIEQueue = &brieQueue{
workerCh: make(chan struct{}, 1),
}
}
// registerTask registers a BRIE task in the queue.
func (bq *brieQueue) registerTask(
ctx context.Context,
info *brieTaskInfo,
) (context.Context, uint64) {
taskCtx, taskCancel := context.WithCancel(ctx)
item := &brieQueueItem{
info: info,
cancel: taskCancel,
progress: &brieTaskProgress{
cmd: "Wait",
total: 1,
},
}
taskID := atomic.AddUint64(&bq.nextID, 1)
bq.tasks.Store(taskID, item)
info.id = taskID
return taskCtx, taskID
}
// query task queries a task from the queue.
func (bq *brieQueue) queryTask(taskID uint64) (*brieTaskInfo, bool) {
if item, ok := bq.tasks.Load(taskID); ok {
return item.(*brieQueueItem).info, true
}
return nil, false
}
// acquireTask prepares to execute a BRIE task. Only one BRIE task can be
// executed at a time, and this function blocks until the task is ready.
//
// Returns an object to track the task's progress.
func (bq *brieQueue) acquireTask(taskCtx context.Context, taskID uint64) (*brieTaskProgress, error) {
// wait until we are at the front of the queue.
select {
case bq.workerCh <- struct{}{}:
if item, ok := bq.tasks.Load(taskID); ok {
return item.(*brieQueueItem).progress, nil
}
// cannot find task, perhaps it has been canceled. allow the next task to run.
bq.releaseTask()
return nil, errors.Errorf("backup/restore task %d is canceled", taskID)
case <-taskCtx.Done():
return nil, taskCtx.Err()
}
}
func (bq *brieQueue) releaseTask() {
<-bq.workerCh
}
func (bq *brieQueue) cancelTask(taskID uint64) bool {
item, ok := bq.tasks.Load(taskID)
if !ok {
return false
}
i := item.(*brieQueueItem)
i.cancel()
i.progress.Close()
log.Info("BRIE job canceled.", zap.Uint64("ID", i.info.id))
return true
}
func (bq *brieQueue) clearTask(sc *stmtctx.StatementContext) {
if time.Since(bq.lastClearTime) < clearInterval {
return
}
bq.lastClearTime = time.Now()
currTime := types.CurrentTime(mysql.TypeDatetime)
bq.tasks.Range(func(key, value interface{}) bool {
item := value.(*brieQueueItem)
if d := currTime.Sub(sc, &item.info.finishTime); d.Compare(outdatedDuration) > 0 {
bq.tasks.Delete(key)
}
return true
})
}
func (b *executorBuilder) parseTSString(ts string) (uint64, error) {
sc := &stmtctx.StatementContext{TimeZone: b.ctx.GetSessionVars().Location()}
t, err := types.ParseTime(sc, ts, mysql.TypeTimestamp, types.MaxFsp, nil)
if err != nil {
return 0, err
}
t1, err := t.GoTime(sc.TimeZone)
if err != nil {
return 0, err
}
return oracle.GoTimeToTS(t1), nil
}
func (b *executorBuilder) buildBRIE(s *ast.BRIEStmt, schema *expression.Schema) Executor {
if s.Kind == ast.BRIEKindShowBackupMeta {
return execOnce(&showMetaExec{
baseExecutor: newBaseExecutor(b.ctx, schema, 0),
showConfig: buildShowMetadataConfigFrom(s),
})
}
if s.Kind == ast.BRIEKindShowQuery {
return execOnce(&showQueryExec{
baseExecutor: newBaseExecutor(b.ctx, schema, 0),
targetID: uint64(s.JobID),
})
}
if s.Kind == ast.BRIEKindCancelJob {
return &cancelJobExec{
baseExecutor: newBaseExecutor(b.ctx, schema, 0),
targetID: uint64(s.JobID),
}
}
e := &BRIEExec{
baseExecutor: newBaseExecutor(b.ctx, schema, 0),
info: &brieTaskInfo{
kind: s.Kind,
},
}
tidbCfg := config.GetGlobalConfig()
cfg := task.Config{
TLS: task.TLSConfig{
CA: tidbCfg.Security.ClusterSSLCA,
Cert: tidbCfg.Security.ClusterSSLCert,
Key: tidbCfg.Security.ClusterSSLKey,
},
PD: strings.Split(tidbCfg.Path, ","),
Concurrency: 4,
Checksum: true,
SendCreds: true,
LogProgress: true,
CipherInfo: backuppb.CipherInfo{
CipherType: encryptionpb.EncryptionMethod_PLAINTEXT,
},
}
storageURL, err := storage.ParseRawURL(s.Storage)
if err != nil {
b.err = errors.Annotate(err, "invalid destination URL")
return nil
}
switch storageURL.Scheme {
case "s3":
storage.ExtractQueryParameters(storageURL, &cfg.S3)
case "gs", "gcs":
storage.ExtractQueryParameters(storageURL, &cfg.GCS)
case "hdfs":
if sem.IsEnabled() {
// Storage is not permitted to be hdfs when SEM is enabled.
b.err = exeerrors.ErrNotSupportedWithSem.GenWithStackByArgs("hdfs storage")
return nil
}
case "local", "file", "":
if sem.IsEnabled() {
// Storage is not permitted to be local when SEM is enabled.
b.err = exeerrors.ErrNotSupportedWithSem.GenWithStackByArgs("local storage")
return nil
}
default:
}
if tidbCfg.Store != "tikv" {
b.err = errors.Errorf("%s requires tikv store, not %s", s.Kind, tidbCfg.Store)
return nil
}
cfg.Storage = storageURL.String()
e.info.storage = cfg.Storage
for _, opt := range s.Options {
switch opt.Tp {
case ast.BRIEOptionRateLimit:
cfg.RateLimit = opt.UintValue
case ast.BRIEOptionConcurrency:
cfg.Concurrency = uint32(opt.UintValue)
case ast.BRIEOptionChecksum:
cfg.Checksum = opt.UintValue != 0
case ast.BRIEOptionSendCreds:
cfg.SendCreds = opt.UintValue != 0
}
}
switch {
case len(s.Tables) != 0:
tables := make([]filter.Table, 0, len(s.Tables))
for _, tbl := range s.Tables {
tables = append(tables, filter.Table{Name: tbl.Name.O, Schema: tbl.Schema.O})
}
cfg.TableFilter = filter.NewTablesFilter(tables...)
case len(s.Schemas) != 0:
cfg.TableFilter = filter.NewSchemasFilter(s.Schemas...)
default:
cfg.TableFilter = filter.All()
}
// table options are stored in original case, but comparison
// is expected to be performed insensitive.
cfg.TableFilter = filter.CaseInsensitive(cfg.TableFilter)
// We cannot directly use the query string, or the secret may be print.
// NOTE: the ownership of `s.Storage` is taken here.
s.Storage = e.info.storage
e.info.query = restoreQuery(s)
switch s.Kind {
case ast.BRIEKindBackup:
e.backupCfg = &task.BackupConfig{Config: cfg}
for _, opt := range s.Options {
switch opt.Tp {
case ast.BRIEOptionLastBackupTS:
tso, err := b.parseTSString(opt.StrValue)
if err != nil {
b.err = err
return nil
}
e.backupCfg.LastBackupTS = tso
case ast.BRIEOptionLastBackupTSO:
e.backupCfg.LastBackupTS = opt.UintValue
case ast.BRIEOptionBackupTimeAgo:
e.backupCfg.TimeAgo = time.Duration(opt.UintValue)
case ast.BRIEOptionBackupTSO:
e.backupCfg.BackupTS = opt.UintValue
case ast.BRIEOptionBackupTS:
tso, err := b.parseTSString(opt.StrValue)
if err != nil {
b.err = err
return nil
}
e.backupCfg.BackupTS = tso
}
}
case ast.BRIEKindRestore:
e.restoreCfg = &task.RestoreConfig{Config: cfg}
for _, opt := range s.Options {
switch opt.Tp {
case ast.BRIEOptionOnline:
e.restoreCfg.Online = opt.UintValue != 0
}
}
default:
b.err = errors.Errorf("unsupported BRIE statement kind: %s", s.Kind)
return nil
}
return e
}
// oneshotExecutor wraps a executor, making its `Next` would only be called once.
type oneshotExecutor struct {
Executor
finished bool
}
func (o *oneshotExecutor) Next(ctx context.Context, req *chunk.Chunk) error {
if o.finished {
req.Reset()
return nil
}
if err := o.Executor.Next(ctx, req); err != nil {
return err
}
o.finished = true
return nil
}
func execOnce(ex Executor) Executor {
return &oneshotExecutor{Executor: ex}
}
type showQueryExec struct {
baseExecutor
targetID uint64
}
func (s *showQueryExec) Next(ctx context.Context, req *chunk.Chunk) error {
req.Reset()
tsk, ok := globalBRIEQueue.queryTask(s.targetID)
if !ok {
return nil
}
req.AppendString(0, tsk.query)
return nil
}
type cancelJobExec struct {
baseExecutor
targetID uint64
}
func (s cancelJobExec) Next(ctx context.Context, req *chunk.Chunk) error {
req.Reset()
if !globalBRIEQueue.cancelTask(s.targetID) {
s.ctx.GetSessionVars().StmtCtx.AppendWarning(exeerrors.ErrLoadDataJobNotFound.FastGenByArgs(s.targetID))
}
return nil
}
type showMetaExec struct {
baseExecutor
showConfig show.Config
}
// BRIEExec represents an executor for BRIE statements (BACKUP, RESTORE, etc)
type BRIEExec struct {
baseExecutor
backupCfg *task.BackupConfig
restoreCfg *task.RestoreConfig
showConfig *show.Config
info *brieTaskInfo
}
func buildShowMetadataConfigFrom(s *ast.BRIEStmt) show.Config {
if s.Kind != ast.BRIEKindShowBackupMeta {
panic(fmt.Sprintf("precondition failed: `fillByShowMetadata` should always called by a ast.BRIEKindShowBackupMeta, but it is %s.", s.Kind))
}
store := s.Storage
cfg := show.Config{
Storage: store,
Cipher: backuppb.CipherInfo{
CipherType: encryptionpb.EncryptionMethod_PLAINTEXT,
},
}
return cfg
}
func (e *showMetaExec) Next(ctx context.Context, req *chunk.Chunk) error {
exe, err := show.CreateExec(ctx, e.showConfig)
if err != nil {
return errors.Annotate(err, "failed to create show exec")
}
res, err := exe.Read(ctx)
if err != nil {
return errors.Annotate(err, "failed to read metadata from backupmeta")
}
startTime := oracle.GetTimeFromTS(uint64(res.StartVersion))
endTime := oracle.GetTimeFromTS(uint64(res.EndVersion))
for _, table := range res.Tables {
req.AppendString(0, table.DBName)
req.AppendString(1, table.TableName)
req.AppendInt64(2, int64(table.KVCount))
req.AppendInt64(3, int64(table.KVSize))
if res.StartVersion > 0 {
req.AppendTime(4, types.NewTime(types.FromGoTime(startTime), mysql.TypeDatetime, 0))
} else {
req.AppendNull(4)
}
req.AppendTime(5, types.NewTime(types.FromGoTime(endTime), mysql.TypeDatetime, 0))
}
return nil
}
// Next implements the Executor Next interface.
func (e *BRIEExec) Next(ctx context.Context, req *chunk.Chunk) error {
req.Reset()
if e.info == nil {
return nil
}
bq := globalBRIEQueue
bq.clearTask(e.ctx.GetSessionVars().StmtCtx)
e.info.connID = e.ctx.GetSessionVars().ConnectionID
e.info.queueTime = types.CurrentTime(mysql.TypeDatetime)
taskCtx, taskID := bq.registerTask(ctx, e.info)
defer bq.cancelTask(taskID)
failpoint.Inject("block-on-brie", func() {
log.Warn("You shall not pass, nya. :3")
<-taskCtx.Done()
if taskCtx.Err() != nil {
failpoint.Return(taskCtx.Err())
}
})
// manually monitor the Killed status...
go func() {
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if atomic.LoadUint32(&e.ctx.GetSessionVars().Killed) == 1 {
bq.cancelTask(taskID)
return
}
case <-taskCtx.Done():
return
}
}
}()
progress, err := bq.acquireTask(taskCtx, taskID)
if err != nil {
return err
}
defer bq.releaseTask()
e.info.execTime = types.CurrentTime(mysql.TypeDatetime)
glue := &tidbGlueSession{se: e.ctx, progress: progress, info: e.info}
switch e.info.kind {
case ast.BRIEKindBackup:
err = handleBRIEError(task.RunBackup(taskCtx, glue, "Backup", e.backupCfg), exeerrors.ErrBRIEBackupFailed)
case ast.BRIEKindRestore:
err = handleBRIEError(task.RunRestore(taskCtx, glue, "Restore", e.restoreCfg), exeerrors.ErrBRIERestoreFailed)
default:
err = errors.Errorf("unsupported BRIE statement kind: %s", e.info.kind)
}
e.info.finishTime = types.CurrentTime(mysql.TypeDatetime)
if err != nil {
e.info.message = err.Error()
return err
}
e.info.message = ""
req.AppendString(0, e.info.storage)
req.AppendUint64(1, e.info.archiveSize)
switch e.info.kind {
case ast.BRIEKindBackup:
req.AppendUint64(2, e.info.backupTS)
req.AppendTime(3, e.info.queueTime)
req.AppendTime(4, e.info.execTime)
case ast.BRIEKindRestore:
req.AppendUint64(2, e.info.backupTS)
req.AppendUint64(3, e.info.restoreTS)
req.AppendTime(4, e.info.queueTime)
req.AppendTime(5, e.info.execTime)
}
e.info = nil
return nil
}
func handleBRIEError(err error, terror *terror.Error) error {
if err == nil {
return nil
}
return terror.GenWithStackByArgs(err)
}
func (e *ShowExec) fetchShowBRIE(kind ast.BRIEKind) error {
globalBRIEQueue.tasks.Range(func(key, value interface{}) bool {
item := value.(*brieQueueItem)
if item.info.kind == kind {
item.progress.lock.Lock()
defer item.progress.lock.Unlock()
current := atomic.LoadInt64(&item.progress.current)
e.result.AppendUint64(0, item.info.id)
e.result.AppendString(1, item.info.storage)
e.result.AppendString(2, item.progress.cmd)
e.result.AppendFloat64(3, 100.0*float64(current)/float64(item.progress.total))
e.result.AppendTime(4, item.info.queueTime)
e.result.AppendTime(5, item.info.execTime)
e.result.AppendTime(6, item.info.finishTime)
e.result.AppendUint64(7, item.info.connID)
if len(item.info.message) > 0 {
e.result.AppendString(8, item.info.message)
} else {
e.result.AppendNull(8)
}
}
return true
})
globalBRIEQueue.clearTask(e.ctx.GetSessionVars().StmtCtx)
return nil
}
type tidbGlueSession struct {
se sessionctx.Context
progress *brieTaskProgress
info *brieTaskInfo
}
// GetSessionCtx implements glue.Glue
func (gs *tidbGlueSession) GetSessionCtx() sessionctx.Context {
return gs.se
}
// GetDomain implements glue.Glue
func (gs *tidbGlueSession) GetDomain(store kv.Storage) (*domain.Domain, error) {
return domain.GetDomain(gs.se), nil
}
// CreateSession implements glue.Glue
func (gs *tidbGlueSession) CreateSession(store kv.Storage) (glue.Session, error) {
return gs, nil
}
// Execute implements glue.Session
// These queries execute without privilege checking, since the calling statements
// such as BACKUP and RESTORE have already been privilege checked.
// NOTE: Maybe drain the restult too? See `gluetidb.tidbSession.ExecuteInternal` for more details.
func (gs *tidbGlueSession) Execute(ctx context.Context, sql string) error {
ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnBR)
_, _, err := gs.se.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, nil, sql)
return err
}
func (gs *tidbGlueSession) ExecuteInternal(ctx context.Context, sql string, args ...interface{}) error {
ctx = kv.WithInternalSourceType(ctx, kv.InternalTxnBR)
exec := gs.se.(sqlexec.SQLExecutor)
_, err := exec.ExecuteInternal(ctx, sql, args...)
return err
}
// CreateDatabase implements glue.Session
func (gs *tidbGlueSession) CreateDatabase(ctx context.Context, schema *model.DBInfo) error {
d := domain.GetDomain(gs.se).DDL()
// 512 is defaultCapOfCreateTable.
result := bytes.NewBuffer(make([]byte, 0, 512))
if err := ConstructResultOfShowCreateDatabase(gs.se, schema, true, result); err != nil {
return err
}
gs.se.SetValue(sessionctx.QueryString, result.String())
schema = schema.Clone()
if len(schema.Charset) == 0 {
schema.Charset = mysql.DefaultCharset
}
return d.CreateSchemaWithInfo(gs.se, schema, ddl.OnExistIgnore)
}
// CreateTable implements glue.Session
func (gs *tidbGlueSession) CreateTable(ctx context.Context, dbName model.CIStr, table *model.TableInfo, cs ...ddl.CreateTableWithInfoConfigurier) error {
d := domain.GetDomain(gs.se).DDL()
// 512 is defaultCapOfCreateTable.
result := bytes.NewBuffer(make([]byte, 0, 512))
if err := ConstructResultOfShowCreateTable(gs.se, table, autoid.Allocators{}, result); err != nil {
return err
}
gs.se.SetValue(sessionctx.QueryString, result.String())
// Disable foreign key check when batch create tables.
gs.se.GetSessionVars().ForeignKeyChecks = false
// Clone() does not clone partitions yet :(
table = table.Clone()
if table.Partition != nil {
newPartition := *table.Partition
newPartition.Definitions = append([]model.PartitionDefinition{}, table.Partition.Definitions...)
table.Partition = &newPartition
}
return d.CreateTableWithInfo(gs.se, dbName, table, append(cs, ddl.OnExistIgnore)...)
}
// CreatePlacementPolicy implements glue.Session
func (gs *tidbGlueSession) CreatePlacementPolicy(ctx context.Context, policy *model.PolicyInfo) error {
gs.se.SetValue(sessionctx.QueryString, ConstructResultOfShowCreatePlacementPolicy(policy))
d := domain.GetDomain(gs.se).DDL()
// the default behaviour is ignoring duplicated policy during restore.
return d.CreatePlacementPolicyWithInfo(gs.se, policy, ddl.OnExistIgnore)
}
// Close implements glue.Session
func (gs *tidbGlueSession) Close() {
}
// GetGlobalVariables implements glue.Session.
func (gs *tidbGlueSession) GetGlobalVariable(name string) (string, error) {
return gs.se.GetSessionVars().GlobalVarsAccessor.GetTiDBTableValue(name)
}
// Open implements glue.Glue
func (gs *tidbGlueSession) Open(string, pd.SecurityOption) (kv.Storage, error) {
return gs.se.GetStore(), nil
}
// OwnsStorage implements glue.Glue
func (gs *tidbGlueSession) OwnsStorage() bool {
return false
}
// StartProgress implements glue.Glue
func (gs *tidbGlueSession) StartProgress(ctx context.Context, cmdName string, total int64, redirectLog bool) glue.Progress {
gs.progress.lock.Lock()
gs.progress.cmd = cmdName
gs.progress.total = total
atomic.StoreInt64(&gs.progress.current, 0)
gs.progress.lock.Unlock()
return gs.progress
}
// Record implements glue.Glue
func (gs *tidbGlueSession) Record(name string, value uint64) {
switch name {
case "BackupTS":
gs.info.backupTS = value
case "RestoreTS":
gs.info.restoreTS = value
case "Size":
gs.info.archiveSize = value
}
}
func (gs *tidbGlueSession) GetVersion() string {
return "TiDB\n" + printer.GetTiDBInfo()
}
// UseOneShotSession implements glue.Glue
func (gs *tidbGlueSession) UseOneShotSession(store kv.Storage, closeDomain bool, fn func(se glue.Session) error) error {
// in SQL backup. we don't need to close domain.
return fn(gs)
}
func restoreQuery(stmt *ast.BRIEStmt) string {
out := bytes.NewBuffer(nil)
rc := format.NewRestoreCtx(format.RestoreNameBackQuotes|format.RestoreStringSingleQuotes, out)
if err := stmt.Restore(rc); err != nil {
return "N/A"
}
return out.String()
}