This repository has been archived by the owner on Nov 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 188
/
mydumper.go
263 lines (230 loc) · 6.29 KB
/
mydumper.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
// 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 mydumper
import (
"bufio"
"bytes"
"context"
"fmt"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
"github.com/pingcap/dm/dm/config"
"github.com/pingcap/dm/dm/pb"
"github.com/pingcap/dm/dm/unit"
"github.com/pingcap/dm/pkg/log"
"github.com/pingcap/errors"
"github.com/siddontang/go/sync2"
)
// Mydumper is a simple wrapper for mydumper binary
type Mydumper struct {
cfg *config.SubTaskConfig
args []string
closed sync2.AtomicBool
}
// NewMydumper creates a new Mydumper
func NewMydumper(cfg *config.SubTaskConfig) *Mydumper {
m := &Mydumper{
cfg: cfg,
}
m.args = m.constructArgs()
return m
}
// Init implements Unit.Init
func (m *Mydumper) Init() error {
return nil // always return nil
}
// Process implements Unit.Process
func (m *Mydumper) Process(ctx context.Context, pr chan pb.ProcessResult) {
mydumperExitWithErrorCounter.WithLabelValues(m.cfg.Name).Add(0)
begin := time.Now()
errs := make([]*pb.ProcessError, 0, 1)
isCanceled := false
// NOTE: remove output dir before start dumping
// every time re-dump, loader should re-prepare
err := os.RemoveAll(m.cfg.Dir)
if err != nil {
log.Errorf("[mydumper] remove output dir %s fail %v", m.cfg.Dir, err)
}
// Cmd cannot be reused, so we create a new cmd when begin processing
output, err := m.spawn(ctx)
if err != nil {
mydumperExitWithErrorCounter.WithLabelValues(m.cfg.Name).Inc()
errs = append(errs, unit.NewProcessError(pb.ErrorType_UnknownError, fmt.Sprintf("%s. %s", err.Error(), output)))
} else {
select {
case <-ctx.Done():
isCanceled = true
default:
}
}
log.Infof("[mydumper] dump data takes %v", time.Since(begin))
pr <- pb.ProcessResult{
IsCanceled: isCanceled,
Errors: errs,
}
}
var mydumperLogRegexp = regexp.MustCompile(
`^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} \[(DEBUG|INFO|WARNING|ERROR)\] - `,
)
func (m *Mydumper) spawn(ctx context.Context) ([]byte, error) {
var (
stdout bytes.Buffer
stderr bytes.Buffer
)
cmd := exec.CommandContext(ctx, m.cfg.MydumperPath, m.args...)
cmd.Stdout = &stdout
stderrPipe, err := cmd.StderrPipe()
if err != nil {
return nil, errors.Trace(err)
}
if err := cmd.Start(); err != nil {
return nil, errors.Trace(err)
}
// Read the stderr from mydumper, which contained the logs.
// mydumper's logs are all in the form
//
// 2016-01-02 15:04:05 [DEBUG] - actual message
//
// so we parse all these lines and translate into our own logs.
scanner := bufio.NewScanner(stderrPipe)
for scanner.Scan() {
line := scanner.Bytes()
if loc := mydumperLogRegexp.FindSubmatchIndex(line); len(loc) == 4 {
level := string(line[loc[2]:loc[3]])
msg := line[loc[1]:]
switch level {
case "DEBUG":
log.Debugf("[mydumper] %s", msg)
continue
case "INFO":
log.Infof("[mydumper] %s", msg)
continue
case "WARNING":
log.Warnf("[mydumper] %s", msg)
continue
case "ERROR":
log.Errorf("[mydumper] %s", msg)
continue
}
}
stderr.Write(line)
stderr.WriteByte('\n')
}
if err := scanner.Err(); err != nil {
stdout.Write(stderr.Bytes())
return stdout.Bytes(), errors.Trace(err)
}
err = cmd.Wait()
stdout.Write(stderr.Bytes())
return stdout.Bytes(), errors.Trace(err)
}
// Close implements Unit.Close
func (m *Mydumper) Close() {
if m.closed.Get() {
return
}
// do nothing, external will cancel the command (if running)
m.closed.Set(true)
}
// Pause implements Unit.Pause
func (m *Mydumper) Pause() {
if m.closed.Get() {
log.Warn("[mydumper] try to pause, but already closed")
return
}
// do nothing, external will cancel the command (if running)
}
// Resume implements Unit.Resume
func (m *Mydumper) Resume(ctx context.Context, pr chan pb.ProcessResult) {
if m.closed.Get() {
log.Warn("[mydumper] try to resume, but already closed")
return
}
// just call Process
m.Process(ctx, pr)
}
// Update implements Unit.Update
func (m *Mydumper) Update(cfg *config.SubTaskConfig) error {
// not support update configuration now
return nil
}
// Status implements Unit.Status
func (m *Mydumper) Status() interface{} {
// NOTE: try to add some status, like dumped file count
return &pb.DumpStatus{}
}
// Error implements Unit.Error
func (m *Mydumper) Error() interface{} {
return &pb.DumpError{}
}
// Type implements Unit.Type
func (m *Mydumper) Type() pb.UnitType {
return pb.UnitType_Dump
}
// IsFreshTask implements Unit.IsFreshTask
func (m *Mydumper) IsFreshTask() (bool, error) {
return true, nil
}
// constructArgs constructs arguments for exec.Command
func (m *Mydumper) constructArgs() []string {
cfg := m.cfg
db := cfg.From
ret := []string{
"--host",
db.Host,
"--port",
strconv.Itoa(db.Port),
"--user",
db.User,
"--outputdir",
cfg.Dir, // use LoaderConfig.Dir as --outputdir
}
ret = append(ret, m.logArgs(cfg)...)
if cfg.Threads > 0 {
ret = append(ret, "--threads", strconv.Itoa(cfg.Threads))
}
if cfg.ChunkFilesize > 0 {
ret = append(ret, "--chunk-filesize", strconv.FormatInt(cfg.ChunkFilesize, 10))
}
if cfg.SkipTzUTC {
ret = append(ret, "--skip-tz-utc")
}
extraArgs := strings.Fields(cfg.ExtraArgs)
if len(extraArgs) > 0 {
ret = append(ret, ParseArgLikeBash(extraArgs)...)
}
log.Infof("[mydumper] create mydumper using args %v", ret)
ret = append(ret, "--password", db.Password)
return ret
}
// logArgs constructs arguments for log from SubTaskConfig
func (m *Mydumper) logArgs(cfg *config.SubTaskConfig) []string {
args := make([]string, 0, 4)
if len(cfg.LogFile) > 0 {
// for writing mydumper output into stderr (fixme: won't work on Windows, if anyone cares)
args = append(args, "--logfile", "/dev/stderr")
}
switch strings.ToLower(cfg.LogLevel) {
case "fatal", "error":
args = append(args, "--verbose", "1")
case "warn", "warning":
args = append(args, "--verbose", "2")
case "info", "debug":
args = append(args, "--verbose", "3")
}
return args
}