-
Notifications
You must be signed in to change notification settings - Fork 269
/
dumpling.go
436 lines (387 loc) · 12.6 KB
/
dumpling.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
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package dumpling
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/tidb/dumpling/export"
tidbpromutil "github.com/pingcap/tidb/util/promutil"
filter "github.com/pingcap/tidb/util/table-filter"
"github.com/pingcap/tiflow/dm/pkg/storage"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic"
"go.uber.org/zap"
"github.com/pingcap/tiflow/engine/pkg/promutil"
"github.com/pingcap/tiflow/dm/config"
"github.com/pingcap/tiflow/dm/pb"
"github.com/pingcap/tiflow/dm/pkg/binlog"
"github.com/pingcap/tiflow/dm/pkg/conn"
dutils "github.com/pingcap/tiflow/dm/pkg/dumpling"
"github.com/pingcap/tiflow/dm/pkg/log"
"github.com/pingcap/tiflow/dm/pkg/terror"
"github.com/pingcap/tiflow/dm/pkg/utils"
"github.com/pingcap/tiflow/dm/unit"
)
// Dumpling dumps full data from a MySQL-compatible database.
type Dumpling struct {
cfg *config.SubTaskConfig
metricProxies *metricProxies
logger log.Logger
dumpConfig *export.Config
closed atomic.Bool
core *export.Dumper
mu sync.RWMutex
}
// NewDumpling creates a new Dumpling.
func NewDumpling(cfg *config.SubTaskConfig) *Dumpling {
logger := log.L()
if cfg.FrameworkLogger != nil {
logger = log.Logger{Logger: cfg.FrameworkLogger}
}
m := &Dumpling{
cfg: cfg,
logger: logger.WithFields(zap.String("task", cfg.Name), zap.String("unit", "dump")),
}
return m
}
// Init implements Unit.Init.
func (m *Dumpling) Init(ctx context.Context) error {
var err error
if m.dumpConfig, err = m.constructArgs(ctx); err != nil {
return err
}
if m.cfg.MetricsFactory != nil {
// this branch means dataflow engine has set a Factory, the Factory itself
// will register and deregister metrics, so we must use NoopRegistry
// to avoid duplicated registration.
m.metricProxies = &metricProxies{}
m.metricProxies.dumplingExitWithErrorCounter = m.cfg.MetricsFactory.NewCounterVec(
prometheus.CounterOpts{
Namespace: "dm",
Subsystem: "dumpling",
Name: "exit_with_error_count",
Help: "counter for dumpling exit with error",
}, []string{"task", "source_id"},
)
m.dumpConfig.PromFactory = promutil.NewWrappingFactory(
m.cfg.MetricsFactory,
"",
prometheus.Labels{
"task": m.cfg.Name, "source_id": m.cfg.SourceID,
},
)
m.dumpConfig.PromRegistry = tidbpromutil.NewNoopRegistry()
} else {
m.metricProxies = defaultMetricProxies
m.dumpConfig.PromFactory = promutil.NewWrappingFactory(
promutil.NewPromFactory(),
"",
prometheus.Labels{
"task": m.cfg.Name, "source_id": m.cfg.SourceID,
},
)
m.dumpConfig.PromRegistry = prometheus.DefaultGatherer.(prometheus.Registerer)
}
m.logger.Info("create dumpling", zap.Stringer("config", m.dumpConfig))
return nil
}
// Process implements Unit.Process.
func (m *Dumpling) Process(ctx context.Context, pr chan pb.ProcessResult) {
m.metricProxies.dumplingExitWithErrorCounter.WithLabelValues(m.cfg.Name, m.cfg.SourceID).Add(0)
failpoint.Inject("dumpUnitProcessWithError", func(val failpoint.Value) {
m.logger.Info("dump unit runs with injected error", zap.String("failpoint", "dumpUnitProcessWithError"), zap.Reflect("error", val))
msg, ok := val.(string)
if !ok {
msg = "unknown process error"
}
pr <- pb.ProcessResult{
IsCanceled: false,
Errors: []*pb.ProcessError{unit.NewProcessError(errors.New(msg))},
}
failpoint.Return()
})
begin := time.Now()
errs := make([]*pb.ProcessError, 0, 1)
failpoint.Inject("dumpUnitProcessForever", func() {
m.logger.Info("dump unit runs forever", zap.String("failpoint", "dumpUnitProcessForever"))
<-ctx.Done()
pr <- pb.ProcessResult{
IsCanceled: true,
Errors: []*pb.ProcessError{unit.NewProcessError(ctx.Err())},
}
failpoint.Return()
})
// NOTE: remove output dir before start dumping
// every time re-dump, loader should re-prepare
// when engine has opened an ExternalStorage, we can assume it's empty.
if m.cfg.ExtStorage == nil {
err := storage.RemoveAll(ctx, m.cfg.Dir, nil)
if err != nil {
m.logger.Error("fail to remove output directory", zap.String("directory", m.cfg.Dir), log.ShortError(err))
errs = append(errs, unit.NewProcessError(terror.ErrDumpUnitRuntime.Delegate(err, "fail to remove output directory: "+m.cfg.Dir)))
pr <- pb.ProcessResult{
IsCanceled: false,
Errors: errs,
}
return
}
}
failpoint.Inject("dumpUnitProcessCancel", func() {
m.logger.Info("mock dump unit cancel", zap.String("failpoint", "dumpUnitProcessCancel"))
<-ctx.Done()
})
newCtx, cancel := context.WithCancel(ctx)
var (
dumpling *export.Dumper
err error
)
if dumpling, err = export.NewDumper(newCtx, m.dumpConfig); err == nil {
m.mu.Lock()
m.core = dumpling
m.mu.Unlock()
err = dumpling.Dump()
failpoint.Inject("SleepBeforeDumplingClose", func(val failpoint.Value) {
t := val.(int)
time.Sleep(time.Second * time.Duration(t))
m.logger.Info("", zap.String("failpoint", "SleepBeforeDumplingClose"))
})
dumpling.Close()
} else {
m.logger.Warn("error occurred during NewDumper", zap.Error(err))
}
cancel()
if err != nil {
if utils.IsContextCanceledError(err) {
m.logger.Info("filter out error caused by user cancel")
} else {
m.metricProxies.dumplingExitWithErrorCounter.WithLabelValues(m.cfg.Name, m.cfg.SourceID).Inc()
errs = append(errs, unit.NewProcessError(terror.ErrDumpUnitRuntime.Delegate(err, "")))
}
}
isCanceled := false
select {
case <-ctx.Done():
isCanceled = true
default:
}
if len(errs) == 0 {
m.logger.Info("dump data finished", zap.Duration("cost time", time.Since(begin)))
} else {
m.logger.Error("dump data exits with error", zap.Duration("cost time", time.Since(begin)),
zap.String("error", unit.JoinProcessErrors(errs)))
}
failpoint.Inject("dumpUnitProcessNoError", func() {
m.logger.Info("dump unit runs no error", zap.String("failpoint", "dumpUnitProcessNoError"))
errs = errs[:0]
})
pr <- pb.ProcessResult{
IsCanceled: isCanceled,
Errors: errs,
}
}
// Close implements Unit.Close.
func (m *Dumpling) Close() {
if m.closed.Load() {
return
}
m.removeLabelValuesWithTaskInMetrics(m.cfg.Name, m.cfg.SourceID)
// do nothing, external will cancel the command (if running)
m.closed.Store(true)
}
// Kill implements Unit.Kill.
func (m *Dumpling) Kill() {
// TODO: implement kill
m.Close()
}
// Pause implements Unit.Pause.
func (m *Dumpling) Pause() {
if m.closed.Load() {
m.logger.Warn("try to pause, but already closed")
return
}
// do nothing, external will cancel the command (if running)
}
// Resume implements Unit.Resume.
func (m *Dumpling) Resume(ctx context.Context, pr chan pb.ProcessResult) {
if m.closed.Load() {
m.logger.Warn("try to resume, but already closed")
return
}
// just call Process
m.Process(ctx, pr)
}
// Update implements Unit.Update.
func (m *Dumpling) Update(context.Context, *config.SubTaskConfig) error {
// not support update configuration now
return nil
}
// Status implements Unit.Status.
func (m *Dumpling) Status(_ *binlog.SourceStatus) interface{} {
// NOTE: try to add some status, like dumped file count
m.mu.RLock()
defer m.mu.RUnlock()
if m.core == nil {
return &pb.DumpStatus{}
}
return m.status()
}
func (m *Dumpling) status() *pb.DumpStatus {
dumpStatus := m.core.GetStatus()
s := &pb.DumpStatus{
TotalTables: dumpStatus.TotalTables,
CompletedTables: dumpStatus.CompletedTables,
FinishedBytes: dumpStatus.FinishedBytes,
FinishedRows: dumpStatus.FinishedRows,
EstimateTotalRows: dumpStatus.EstimateTotalRows,
}
var estimateProgress string
if s.FinishedRows >= s.EstimateTotalRows {
estimateProgress = "100.00%"
} else {
estimateProgress = fmt.Sprintf("%.2f %%", s.FinishedRows/s.EstimateTotalRows*100)
}
m.logger.Info("progress status of dumpling",
zap.Int64("total_tables", s.TotalTables),
zap.Int64("finished_tables", int64(s.CompletedTables)),
zap.Int64("estimated_total_rows", int64(s.EstimateTotalRows)),
zap.Int64("finished_rows", int64(s.FinishedRows)),
zap.String("estimated_progress", estimateProgress),
)
return s
}
// Type implements Unit.Type.
func (m *Dumpling) Type() pb.UnitType {
return pb.UnitType_Dump
}
// IsFreshTask implements Unit.IsFreshTask.
func (m *Dumpling) IsFreshTask(ctx context.Context) (bool, error) {
return true, nil
}
// constructArgs constructs arguments for exec.Command.
func (m *Dumpling) constructArgs(ctx context.Context) (*export.Config, error) {
cfg := m.cfg
db := cfg.From
dumpConfig := export.DefaultConfig()
// block status addr because we already have it in DM, and if we enable it, may we need more ports for the process.
dumpConfig.StatusAddr = ""
dumpConfig.Host = db.Host
dumpConfig.Port = db.Port
dumpConfig.User = db.User
dumpConfig.Password = db.Password
dumpConfig.OutputDirPath = cfg.Dir // use LoaderConfig.Dir as output dir
dumpConfig.CollationCompatible = cfg.CollationCompatible
tableFilter, err := filter.ParseMySQLReplicationRules(cfg.BAList)
if err != nil {
return nil, err
}
dumpConfig.TableFilter = tableFilter
dumpConfig.CompleteInsert = true // always keep column name in `INSERT INTO` statements.
dumpConfig.Logger = m.logger.Logger
tz := m.cfg.Timezone
if len(tz) == 0 {
// use target db time_zone as default
baseDB, err2 := conn.DefaultDBProvider.Apply(&m.cfg.To)
if err2 != nil {
return nil, err2
}
defer baseDB.Close()
var err1 error
tz, err1 = config.FetchTimeZoneSetting(ctx, baseDB.DB)
if err1 != nil {
return nil, err1
}
}
dumpConfig.SessionParams = map[string]interface{}{
"time_zone": tz,
}
if cfg.Threads > 0 {
dumpConfig.Threads = cfg.Threads
}
if cfg.ChunkFilesize != "" {
dumpConfig.FileSize, err = utils.ParseFileSize(cfg.ChunkFilesize, export.UnspecifiedSize)
if err != nil {
m.logger.Warn("parsed some unsupported arguments", zap.Error(err))
return nil, err
}
}
if cfg.StatementSize > 0 {
dumpConfig.StatementSize = cfg.StatementSize
}
if cfg.Rows > 0 {
dumpConfig.Rows = cfg.Rows
}
if len(cfg.Where) > 0 {
dumpConfig.Where = cfg.Where
}
if db.Security != nil {
dumpConfig.Security.CAPath = db.Security.SSLCA
dumpConfig.Security.CertPath = db.Security.SSLCert
dumpConfig.Security.KeyPath = db.Security.SSLKey
dumpConfig.Security.SSLCABytes = db.Security.SSLCABytes
dumpConfig.Security.SSLCertBytes = db.Security.SSLCertBytes
dumpConfig.Security.SSLKEYBytes = db.Security.SSLKEYBytes
}
// `true` means dumpling will release lock after working connection established
dumpConfig.TransactionalConsistency = true
extraArgs := strings.Fields(cfg.ExtraArgs)
if len(extraArgs) > 0 {
err := dutils.ParseExtraArgs(&m.logger, dumpConfig, dutils.ParseArgLikeBash(extraArgs))
if err != nil {
m.logger.Warn("parsed some unsupported arguments", zap.Error(err))
}
}
// record exit position when consistency is none, to support scenarios like Aurora upstream
if dumpConfig.Consistency == "none" {
dumpConfig.PosAfterConnect = true
}
// set default Rows
if dumpConfig.Rows == export.UnspecifiedSize {
dumpConfig.Rows = 200000
}
if !cfg.CaseSensitive {
dumpConfig.TableFilter = filter.CaseInsensitive(dumpConfig.TableFilter)
}
// update sql_mode if needed
m.detectSQLMode(ctx, dumpConfig)
dumpConfig.ExtStorage = cfg.ExtStorage
return dumpConfig, nil
}
// detectSQLMode tries to detect SQL mode from upstream. If success, write it to LoaderConfig.
// Because loader will use this SQL mode, we need to treat disable `EscapeBackslash` when NO_BACKSLASH_ESCAPES.
func (m *Dumpling) detectSQLMode(ctx context.Context, dumpCfg *export.Config) {
baseDB, err := conn.DefaultDBProvider.Apply(&m.cfg.From)
if err != nil {
log.L().Warn("set up db connect failed", zap.Any("db", m.cfg.From),
zap.Error(err))
return
}
defer baseDB.Close()
db := baseDB.DB
sqlMode, err := utils.GetGlobalVariable(ctx, db, "sql_mode")
if err != nil {
log.L().Warn("get global sql_mode from upstream failed", zap.Any("db", m.cfg.From), zap.Error(err))
return
}
m.logger.Info("found upstream SQL mode", zap.String("SQL mode", sqlMode))
m.cfg.LoaderConfig.SQLMode = sqlMode
if strings.Contains(sqlMode, "NO_BACKSLASH_ESCAPES") {
dumpCfg.EscapeBackslash = false
} else {
dumpCfg.EscapeBackslash = true
}
}