This repository has been archived by the owner on Dec 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
lightning.go
executable file
·701 lines (604 loc) · 19.6 KB
/
lightning.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
// Copyright 2019 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package lightning
import (
"compress/gzip"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/pprof"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/pingcap/br/pkg/storage"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb-lightning/lightning/glue"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/shurcooL/httpgzip"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"golang.org/x/net/http/httpproxy"
"github.com/pingcap/tidb-lightning/lightning/backend"
"github.com/pingcap/tidb-lightning/lightning/checkpoints"
"github.com/pingcap/tidb-lightning/lightning/common"
"github.com/pingcap/tidb-lightning/lightning/config"
"github.com/pingcap/tidb-lightning/lightning/log"
"github.com/pingcap/tidb-lightning/lightning/mydump"
"github.com/pingcap/tidb-lightning/lightning/restore"
"github.com/pingcap/tidb-lightning/lightning/web"
)
type Lightning struct {
globalCfg *config.GlobalConfig
globalTLS *common.TLS
// taskCfgs is the list of task configurations enqueued in the server mode
taskCfgs *config.ConfigList
ctx context.Context
shutdown context.CancelFunc // for whole lightning context
server http.Server
serverAddr net.Addr
serverLock sync.Mutex
cancelLock sync.Mutex
curTask *config.Config
cancel context.CancelFunc // for per task context, which maybe different from lightning context
}
func initEnv(cfg *config.GlobalConfig) error {
return log.InitLogger(&cfg.App.Config, cfg.TiDB.LogLevel)
}
func New(globalCfg *config.GlobalConfig) *Lightning {
if err := initEnv(globalCfg); err != nil {
fmt.Println("Failed to initialize environment:", err)
os.Exit(1)
}
tls, err := common.NewTLS(globalCfg.Security.CAPath, globalCfg.Security.CertPath, globalCfg.Security.KeyPath, globalCfg.App.StatusAddr)
if err != nil {
log.L().Fatal("failed to load TLS certificates", zap.Error(err))
}
log.InitRedact(globalCfg.Security.RedactInfoLog)
ctx, shutdown := context.WithCancel(context.Background())
return &Lightning{
globalCfg: globalCfg,
globalTLS: tls,
ctx: ctx,
shutdown: shutdown,
}
}
func (l *Lightning) GoServe() error {
handleSigUsr1(func() {
l.serverLock.Lock()
statusAddr := l.globalCfg.App.StatusAddr
shouldStartServer := len(statusAddr) == 0
if shouldStartServer {
l.globalCfg.App.StatusAddr = ":"
}
l.serverLock.Unlock()
if shouldStartServer {
// open a random port and start the server if SIGUSR1 is received.
if err := l.goServe(":", os.Stderr); err != nil {
log.L().Warn("failed to start HTTP server", log.ShortError(err))
}
} else {
// just prints the server address if it is already started.
log.L().Info("already started HTTP server", zap.Stringer("address", l.serverAddr))
}
})
l.serverLock.Lock()
statusAddr := l.globalCfg.App.StatusAddr
l.serverLock.Unlock()
if len(statusAddr) == 0 {
return nil
}
return l.goServe(statusAddr, ioutil.Discard)
}
func (l *Lightning) goServe(statusAddr string, realAddrWriter io.Writer) error {
mux := http.NewServeMux()
mux.Handle("/", http.RedirectHandler("/web/", http.StatusFound))
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
handleTasks := http.StripPrefix("/tasks", http.HandlerFunc(l.handleTask))
mux.Handle("/tasks", handleTasks)
mux.Handle("/tasks/", handleTasks)
mux.HandleFunc("/progress/task", handleProgressTask)
mux.HandleFunc("/progress/table", handleProgressTable)
mux.HandleFunc("/pause", handlePause)
mux.HandleFunc("/resume", handleResume)
mux.HandleFunc("/loglevel", handleLogLevel)
mux.Handle("/web/", http.StripPrefix("/web", httpgzip.FileServer(web.Res, httpgzip.FileServerOptions{
IndexHTML: true,
ServeError: func(w http.ResponseWriter, req *http.Request, err error) {
if os.IsNotExist(err) && !strings.Contains(req.URL.Path, ".") {
http.Redirect(w, req, "/web/", http.StatusFound)
} else {
httpgzip.NonSpecific(w, req, err)
}
},
})))
listener, err := net.Listen("tcp", statusAddr)
if err != nil {
return err
}
l.serverAddr = listener.Addr()
log.L().Info("starting HTTP server", zap.Stringer("address", l.serverAddr))
fmt.Fprintln(realAddrWriter, "started HTTP server on", l.serverAddr)
l.server.Handler = mux
listener = l.globalTLS.WrapListener(listener)
go func() {
err := l.server.Serve(listener)
log.L().Info("stopped HTTP server", log.ShortError(err))
}()
return nil
}
// RunOnce is used by binary lightning and host when using lightning as a library.
// - for binary lightning, taskCtx could be context.Background which means taskCtx wouldn't be canceled directly by its
// cancel function, but only by Lightning.Stop or HTTP DELETE using l.cancel. and glue could be nil to let lightning
// use a default glue later.
// - for lightning as a library, taskCtx could be a meaningful context that get canceled outside, and glue could be a
// caller implemented glue.
func (l *Lightning) RunOnce(taskCtx context.Context, taskCfg *config.Config, glue glue.Glue, replaceLogger *zap.Logger) error {
if err := taskCfg.Adjust(taskCtx); err != nil {
return err
}
taskCfg.TaskID = time.Now().UnixNano()
failpoint.Inject("SetTaskID", func(val failpoint.Value) {
taskCfg.TaskID = int64(val.(int))
})
if replaceLogger != nil {
log.SetAppLogger(replaceLogger)
}
return l.run(taskCtx, taskCfg, glue)
}
func (l *Lightning) RunServer() error {
l.taskCfgs = config.NewConfigList()
log.L().Info(
"Lightning server is running, post to /tasks to start an import task",
zap.Stringer("address", l.serverAddr),
)
for {
task, err := l.taskCfgs.Pop(l.ctx)
if err != nil {
return err
}
err = l.run(context.Background(), task, nil)
if err != nil {
restore.DeliverPauser.Pause() // force pause the progress on error
log.L().Error("tidb lightning encountered error", zap.Error(err))
}
}
}
var taskCfgRecorderKey struct{}
func (l *Lightning) run(taskCtx context.Context, taskCfg *config.Config, g glue.Glue) (err error) {
common.PrintInfo("lightning", func() {
log.L().Info("cfg", zap.Stringer("cfg", taskCfg))
})
logEnvVariables()
ctx, cancel := context.WithCancel(taskCtx)
l.cancelLock.Lock()
l.cancel = cancel
l.curTask = taskCfg
l.cancelLock.Unlock()
web.BroadcastStartTask()
defer func() {
cancel()
l.cancelLock.Lock()
l.cancel = nil
l.cancelLock.Unlock()
web.BroadcastEndTask(err)
}()
failpoint.Inject("SkipRunTask", func() {
if recorder, ok := l.ctx.Value(&taskCfgRecorderKey).(chan *config.Config); ok {
select {
case recorder <- taskCfg:
case <-ctx.Done():
failpoint.Return(ctx.Err())
}
}
failpoint.Return(nil)
})
if err := taskCfg.TiDB.Security.RegisterMySQL(); err != nil {
return err
}
defer func() {
// deregister TLS config with name "cluster"
if taskCfg.TiDB.Security == nil {
return
}
taskCfg.TiDB.Security.CAPath = ""
taskCfg.TiDB.Security.RegisterMySQL()
}()
// initiation of default glue should be after RegisterMySQL, which is ready to be called after taskCfg.Adjust
// and also put it here could avoid injecting another two SkipRunTask failpoint to caller
if g == nil {
db, err := restore.DBFromConfig(taskCfg.TiDB)
if err != nil {
return err
}
g = glue.NewExternalTiDBGlue(db, taskCfg.TiDB.SQLMode)
}
u, err := storage.ParseBackend(taskCfg.Mydumper.SourceDir, &storage.BackendOptions{})
if err != nil {
return errors.Annotate(err, "parse backend failed")
}
s, err := storage.Create(ctx, u, true)
if err != nil {
return errors.Annotate(err, "create storage failed")
}
loadTask := log.L().Begin(zap.InfoLevel, "load data source")
var mdl *mydump.MDLoader
mdl, err = mydump.NewMyDumpLoaderWithStore(ctx, taskCfg, s)
loadTask.End(zap.ErrorLevel, err)
if err != nil {
return errors.Trace(err)
}
err = checkSystemRequirement(taskCfg, mdl.GetDatabases())
if err != nil {
log.L().Error("check system requirements failed", zap.Error(err))
return errors.Trace(err)
}
// check table schema conflicts
err = checkSchemaConflict(taskCfg, mdl.GetDatabases())
if err != nil {
log.L().Error("checkpoint schema conflicts with data files", zap.Error(err))
return errors.Trace(err)
}
dbMetas := mdl.GetDatabases()
web.BroadcastInitProgress(dbMetas)
var procedure *restore.RestoreController
procedure, err = restore.NewRestoreController(ctx, dbMetas, taskCfg, s, g)
if err != nil {
log.L().Error("restore failed", log.ShortError(err))
return errors.Trace(err)
}
defer procedure.Close()
err = procedure.Run(ctx)
return errors.Trace(err)
}
func (l *Lightning) Stop() {
l.cancelLock.Lock()
if l.cancel != nil {
l.cancel()
}
l.cancelLock.Unlock()
if err := l.server.Shutdown(l.ctx); err != nil {
log.L().Warn("failed to shutdown HTTP server", log.ShortError(err))
}
l.shutdown()
}
// logEnvVariables add related environment variables to log
func logEnvVariables() {
// log http proxy settings, it will be used in gRPC connection by default
proxyCfg := httpproxy.FromEnvironment()
if proxyCfg.HTTPProxy != "" || proxyCfg.HTTPSProxy != "" {
log.L().Info("environment variables", zap.Reflect("httpproxy", proxyCfg))
}
}
func writeJSONError(w http.ResponseWriter, code int, prefix string, err error) {
type errorResponse struct {
Error string `json:"error"`
}
w.WriteHeader(code)
if err != nil {
prefix += ": " + err.Error()
}
json.NewEncoder(w).Encode(errorResponse{Error: prefix})
}
func parseTaskID(req *http.Request) (int64, string, error) {
path := strings.TrimPrefix(req.URL.Path, "/")
taskIDString := path
verb := ""
if i := strings.IndexByte(path, '/'); i >= 0 {
taskIDString = path[:i]
verb = path[i+1:]
}
taskID, err := strconv.ParseInt(taskIDString, 10, 64)
if err != nil {
return 0, "", err
}
return taskID, verb, nil
}
func (l *Lightning) handleTask(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch req.Method {
case http.MethodGet:
taskID, _, err := parseTaskID(req)
if e, ok := err.(*strconv.NumError); ok && e.Num == "" {
l.handleGetTask(w)
} else if err == nil {
l.handleGetOneTask(w, req, taskID)
} else {
writeJSONError(w, http.StatusBadRequest, "invalid task ID", err)
}
case http.MethodPost:
l.handlePostTask(w, req)
case http.MethodDelete:
l.handleDeleteOneTask(w, req)
case http.MethodPatch:
l.handlePatchOneTask(w, req)
default:
w.Header().Set("Allow", http.MethodGet+", "+http.MethodPost+", "+http.MethodDelete+", "+http.MethodPatch)
writeJSONError(w, http.StatusMethodNotAllowed, "only GET, POST, DELETE and PATCH are allowed", nil)
}
}
func (l *Lightning) handleGetTask(w http.ResponseWriter) {
var response struct {
Current *int64 `json:"current"`
QueuedIDs []int64 `json:"queue"`
}
if l.taskCfgs != nil {
response.QueuedIDs = l.taskCfgs.AllIDs()
} else {
response.QueuedIDs = []int64{}
}
l.cancelLock.Lock()
if l.cancel != nil && l.curTask != nil {
response.Current = new(int64)
*response.Current = l.curTask.TaskID
}
l.cancelLock.Unlock()
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}
func (l *Lightning) handleGetOneTask(w http.ResponseWriter, req *http.Request, taskID int64) {
var task *config.Config
l.cancelLock.Lock()
if l.curTask != nil && l.curTask.TaskID == taskID {
task = l.curTask
}
l.cancelLock.Unlock()
if task == nil && l.taskCfgs != nil {
task, _ = l.taskCfgs.Get(taskID)
}
if task == nil {
writeJSONError(w, http.StatusNotFound, "task ID not found", nil)
return
}
json, err := json.Marshal(task)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "unable to serialize task", err)
return
}
writeBytesCompressed(w, req, json)
}
func (l *Lightning) handlePostTask(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Cache-Control", "no-store")
if l.taskCfgs == nil {
// l.taskCfgs is non-nil only if Lightning is started with RunServer().
// Without the server mode this pointer is default to be nil.
writeJSONError(w, http.StatusNotImplemented, "server-mode not enabled", nil)
return
}
type taskResponse struct {
ID int64 `json:"id"`
}
data, err := ioutil.ReadAll(req.Body)
if err != nil {
writeJSONError(w, http.StatusBadRequest, "cannot read request", err)
return
}
log.L().Debug("received task config", zap.ByteString("content", data))
cfg := config.NewConfig()
if err = cfg.LoadFromGlobal(l.globalCfg); err != nil {
writeJSONError(w, http.StatusInternalServerError, "cannot restore from global config", err)
return
}
if err = cfg.LoadFromTOML(data); err != nil {
writeJSONError(w, http.StatusBadRequest, "cannot parse task (must be TOML)", err)
return
}
if err = cfg.Adjust(l.ctx); err != nil {
writeJSONError(w, http.StatusBadRequest, "invalid task configuration", err)
return
}
l.taskCfgs.Push(cfg)
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(taskResponse{ID: cfg.TaskID})
}
func (l *Lightning) handleDeleteOneTask(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
taskID, _, err := parseTaskID(req)
if err != nil {
writeJSONError(w, http.StatusBadRequest, "invalid task ID", err)
return
}
var cancel context.CancelFunc
cancelSuccess := false
l.cancelLock.Lock()
if l.cancel != nil && l.curTask != nil && l.curTask.TaskID == taskID {
cancel = l.cancel
l.cancel = nil
}
l.cancelLock.Unlock()
if cancel != nil {
cancel()
cancelSuccess = true
} else if l.taskCfgs != nil {
cancelSuccess = l.taskCfgs.Remove(taskID)
}
log.L().Info("canceled task", zap.Int64("taskID", taskID), zap.Bool("success", cancelSuccess))
if cancelSuccess {
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
} else {
writeJSONError(w, http.StatusNotFound, "task ID not found", nil)
}
}
func (l *Lightning) handlePatchOneTask(w http.ResponseWriter, req *http.Request) {
if l.taskCfgs == nil {
writeJSONError(w, http.StatusNotImplemented, "server-mode not enabled", nil)
return
}
taskID, verb, err := parseTaskID(req)
if err != nil {
writeJSONError(w, http.StatusBadRequest, "invalid task ID", err)
return
}
moveSuccess := false
switch verb {
case "front":
moveSuccess = l.taskCfgs.MoveToFront(taskID)
case "back":
moveSuccess = l.taskCfgs.MoveToBack(taskID)
default:
writeJSONError(w, http.StatusBadRequest, "unknown patch action", nil)
return
}
if moveSuccess {
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
} else {
writeJSONError(w, http.StatusNotFound, "task ID not found", nil)
}
}
func writeBytesCompressed(w http.ResponseWriter, req *http.Request, b []byte) {
if !strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
w.Write(b)
return
}
w.Header().Set("Content-Encoding", "gzip")
w.WriteHeader(http.StatusOK)
gw, _ := gzip.NewWriterLevel(w, gzip.BestSpeed)
gw.Write(b)
gw.Close()
}
func handleProgressTask(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
res, err := web.MarshalTaskProgress()
if err == nil {
writeBytesCompressed(w, req, res)
} else {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(err.Error())
}
}
func handleProgressTable(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
tableName := req.URL.Query().Get("t")
res, err := web.MarshalTableCheckpoints(tableName)
if err == nil {
writeBytesCompressed(w, req, res)
} else {
if errors.IsNotFound(err) {
w.WriteHeader(http.StatusNotFound)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
json.NewEncoder(w).Encode(err.Error())
}
}
func handlePause(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch req.Method {
case http.MethodGet:
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `{"paused":%v}`, restore.DeliverPauser.IsPaused())
case http.MethodPut:
w.WriteHeader(http.StatusOK)
restore.DeliverPauser.Pause()
log.L().Info("progress paused")
w.Write([]byte("{}"))
default:
w.Header().Set("Allow", http.MethodGet+", "+http.MethodPut)
writeJSONError(w, http.StatusMethodNotAllowed, "only GET and PUT are allowed", nil)
}
}
func handleResume(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch req.Method {
case http.MethodPut:
w.WriteHeader(http.StatusOK)
restore.DeliverPauser.Resume()
log.L().Info("progress resumed")
w.Write([]byte("{}"))
default:
w.Header().Set("Allow", http.MethodPut)
writeJSONError(w, http.StatusMethodNotAllowed, "only PUT is allowed", nil)
}
}
func handleLogLevel(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
var logLevel struct {
Level zapcore.Level `json:"level"`
}
switch req.Method {
case http.MethodGet:
logLevel.Level = log.Level()
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(logLevel)
case http.MethodPut, http.MethodPost:
if err := json.NewDecoder(req.Body).Decode(&logLevel); err != nil {
writeJSONError(w, http.StatusBadRequest, "invalid log level", err)
return
}
oldLevel := log.SetLevel(zapcore.InfoLevel)
log.L().Info("changed log level", zap.Stringer("old", oldLevel), zap.Stringer("new", logLevel.Level))
log.SetLevel(logLevel.Level)
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
default:
w.Header().Set("Allow", http.MethodGet+", "+http.MethodPut+", "+http.MethodPost)
writeJSONError(w, http.StatusMethodNotAllowed, "only GET, PUT and POST are allowed", nil)
}
}
func checkSystemRequirement(cfg *config.Config, dbsMeta []*mydump.MDDatabaseMeta) error {
if !cfg.App.CheckRequirements {
log.L().Info("check-requirement is disabled, skip check system rlimit")
return nil
}
// in local mode, we need to read&write a lot of L0 sst files, so we need to check system max open files limit
if cfg.TikvImporter.Backend == config.BackendLocal {
// estimate max open files = {top N(TableConcurrency) table sizes} / {MemoryTableSize}
tableTotalSizes := make([]int64, 0)
for _, dbs := range dbsMeta {
for _, tb := range dbs.Tables {
tableTotalSizes = append(tableTotalSizes, tb.TotalSize)
}
}
sort.Slice(tableTotalSizes, func(i, j int) bool {
return tableTotalSizes[i] > tableTotalSizes[j]
})
topNTotalSize := int64(0)
for i := 0; i < len(tableTotalSizes) && i < cfg.App.TableConcurrency; i++ {
topNTotalSize += tableTotalSizes[i]
}
estimateMaxFiles := uint64(topNTotalSize/backend.LocalMemoryTableSize) * 2
if err := backend.VerifyRLimit(estimateMaxFiles); err != nil {
return err
}
}
return nil
}
/// checkSchemaConflict return error if checkpoint table scheme is conflict with data files
func checkSchemaConflict(cfg *config.Config, dbsMeta []*mydump.MDDatabaseMeta) error {
if cfg.Checkpoint.Enable && cfg.Checkpoint.Driver == config.CheckpointDriverMySQL {
for _, db := range dbsMeta {
if db.Name == cfg.Checkpoint.Schema {
for _, tb := range db.Tables {
if checkpoints.IsCheckpointTable(tb.Name) {
return errors.Errorf("checkpoint table `%s`.`%s` conflict with data files. Please change the `checkpoint.schema` config or set `checkpoint.driver` to \"file\" instead", db.Name, tb.Name)
}
}
}
}
}
return nil
}