-
Notifications
You must be signed in to change notification settings - Fork 65
/
ferry.go
375 lines (306 loc) · 9.52 KB
/
ferry.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
package ghostferry
import (
"context"
"database/sql"
"fmt"
"strings"
"sync"
"time"
"github.com/go-sql-driver/mysql"
"github.com/siddontang/go-mysql/schema"
"github.com/sirupsen/logrus"
)
var (
VersionString string = "?.?.?+??????????????+???????"
WebUiBasedir string = ""
)
const (
StateStarting = "starting"
StateCopying = "copying"
StateWaitingForCutover = "wait-for-cutover"
StateCutover = "cutover"
StateDone = "done"
)
func quoteField(field string) string {
return fmt.Sprintf("`%s`", field)
}
func MaskedDSN(c *mysql.Config) string {
oldPass := c.Passwd
c.Passwd = "<masked>"
defer func() {
c.Passwd = oldPass
}()
return c.FormatDSN()
}
type Ferry struct {
*Config
SourceDB *sql.DB
TargetDB *sql.DB
BinlogStreamer *BinlogStreamer
DataIterator *DataIterator
ErrorHandler ErrorHandler
Throttler Throttler
Verifier Verifier
Tables TableSchemaCache
StartTime time.Time
DoneTime time.Time
OverallState string
logger *logrus.Entry
coreServicesWg *sync.WaitGroup
supportingServicesWg *sync.WaitGroup
rowCopyCompleteCh chan struct{}
}
// Initialize all the components of Ghostferry and connect to the Database
func (f *Ferry) Initialize() (err error) {
f.StartTime = time.Now().Truncate(time.Second)
f.OverallState = StateStarting
f.coreServicesWg = &sync.WaitGroup{}
f.supportingServicesWg = &sync.WaitGroup{}
f.logger = logrus.WithField("tag", "ferry")
f.rowCopyCompleteCh = make(chan struct{})
f.logger.Infof("hello world from %s", VersionString)
// Connect to the database
sourceConfig, err := f.Source.MySQLConfig()
if err != nil {
f.logger.WithError(err).Error("failed to build config for source database")
return err
}
sourceDSN := sourceConfig.FormatDSN()
maskedSourceDSN := MaskedDSN(sourceConfig)
f.logger.WithField("dsn", maskedSourceDSN).Info("connecting to the source database")
f.SourceDB, err = sql.Open("mysql", sourceDSN)
if err != nil {
f.logger.WithError(err).Error("failed to connect to source database")
return err
}
err = checkConnection(f.logger, maskedSourceDSN, f.SourceDB)
if err != nil {
f.logger.WithError(err).Error("source connection checking failed")
return err
}
err = checkConnectionForBinlogFormat(f.SourceDB)
if err != nil {
f.logger.WithError(err).Error("binlog format for source db is not compatible")
return err
}
targetConfig, err := f.Target.MySQLConfig()
if err != nil {
f.logger.WithError(err).Error("failed to build config for target database")
return err
}
targetDSN := targetConfig.FormatDSN()
maskedTargetDSN := MaskedDSN(targetConfig)
f.logger.WithField("dsn", maskedTargetDSN).Info("connecting to the target database")
f.TargetDB, err = sql.Open("mysql", targetDSN)
if err != nil {
f.logger.WithError(err).Error("failed to connect to target database")
return err
}
err = checkConnection(f.logger, maskedTargetDSN, f.TargetDB)
if err != nil {
f.logger.WithError(err).Error("target connection checking failed")
return err
}
// Initialize the ErrorHandler
if f.ErrorHandler == nil {
f.ErrorHandler = &PanicErrorHandler{
Ferry: f,
}
}
if f.Throttler == nil {
f.Throttler = &PauserThrottler{}
}
// Initialize binlog streamer
f.BinlogStreamer = &BinlogStreamer{
Db: f.SourceDB,
Config: f.Config,
ErrorHandler: f.ErrorHandler,
Throttler: f.Throttler,
Filter: f.CopyFilter,
}
err = f.BinlogStreamer.Initialize()
if err != nil {
return err
}
// Initialize the DataIterator
f.DataIterator = &DataIterator{
Db: f.SourceDB,
Config: f.Config,
ErrorHandler: f.ErrorHandler,
Throttler: f.Throttler,
Filter: f.CopyFilter,
}
err = f.DataIterator.Initialize()
if err != nil {
return err
}
f.logger.Info("ferry initialized")
return nil
}
// Determine the binlog coordinates, table mapping for the pending
// Ghostferry run.
func (f *Ferry) Start() error {
// Event listeners for the BinlogStreamer and DataIterator are called
// in the order they are registered.
// The builtin event listeners are to write the events to the target
// database.
// Registering the builtin event listeners in Start allows the consumer
// of the library to register event listeners that gets called before
// and after the data gets written to the target database.
f.BinlogStreamer.AddEventListener(f.writeEventsToTargetWithRetries)
f.DataIterator.AddEventListener(f.writeEventsToTargetWithRetries)
f.DataIterator.AddDoneListener(f.onFinishedIterations)
// The starting binlog coordinates must be determined first. If it is
// determined after the DataIterator starts, the DataIterator might
// miss some records that are inserted between the time the
// DataIterator determines the range of IDs to copy and the time that
// the starting binlog coordinates are determined.
err := f.BinlogStreamer.ConnectBinlogStreamerToMysql()
if err != nil {
return err
}
// Loads the schema of the tables that are applicable.
// We need to do this at the beginning of the run as this is required
// in order to determine the PrimaryKey of each table as well as finding
// which value in the binlog event correspond to which field in the
// table.
metrics.Measure("LoadTables", nil, 1.0, func() {
f.Tables, err = LoadTables(f.SourceDB, f.TableFilter)
})
if err != nil {
return err
}
// TODO(pushrax): handle changes to schema during copying and clean this up.
f.BinlogStreamer.TableSchema = f.Tables
f.DataIterator.Tables = f.Tables.AsSlice()
return nil
}
// Spawns the background tasks that actually perform the run.
// Wait for the background tasks to finish.
func (f *Ferry) Run() {
f.logger.Info("starting ferry run")
f.OverallState = StateCopying
ctx, shutdown := context.WithCancel(context.Background())
handleError := func(name string, err error) {
if err != nil && err != context.Canceled {
f.ErrorHandler.Fatal(name, err)
}
}
f.supportingServicesWg.Add(1)
go func() {
defer f.supportingServicesWg.Done()
handleError("throttler", f.Throttler.Run(ctx))
}()
f.coreServicesWg.Add(2)
go f.BinlogStreamer.Run(f.coreServicesWg)
go f.DataIterator.Run(f.coreServicesWg)
f.coreServicesWg.Wait()
f.OverallState = StateDone
f.DoneTime = time.Now()
shutdown()
f.supportingServicesWg.Wait()
}
// Call this method and perform the cutover after this method returns.
func (f *Ferry) WaitUntilRowCopyIsComplete() {
<-f.rowCopyCompleteCh
}
func (f *Ferry) WaitUntilBinlogStreamerCatchesUp() {
for !f.BinlogStreamer.IsAlmostCaughtUp() {
time.Sleep(500 * time.Millisecond)
}
}
// After you stop writing to the source and made sure that all inflight
// transactions to the source are completed, call this method to ensure
// that the binlog streaming has caught up and stop the binlog streaming.
//
// This method will actually not shutdown the BinlogStreamer immediately.
// You will know that the BinlogStreamer finished when .Run() returns.
func (f *Ferry) FlushBinlogAndStopStreaming() {
f.BinlogStreamer.FlushAndStop()
}
func (f *Ferry) onFinishedIterations() error {
f.logger.Info("finished iterations")
f.OverallState = StateWaitingForCutover
for !f.AutomaticCutover {
time.Sleep(1 * time.Second)
f.logger.Debug("waiting for AutomaticCutover to become true before signaling for row copy complete")
}
f.logger.Info("entering cutover phase")
f.OverallState = StateCutover
// TODO: make it so that this is non-blocking
f.rowCopyCompleteCh <- struct{}{}
return nil
}
func (f *Ferry) writeEventsToTargetWithRetries(events []DMLEvent) error {
return WithRetries(f.MaxWriteRetriesOnTargetDBError, 0, f.logger, "write event to target", func() error {
return f.writeEventsToTarget(events)
})
}
func (f *Ferry) writeEventsToTarget(events []DMLEvent) error {
tx, err := f.TargetDB.Begin()
if err != nil {
return err
}
rollback := func(err error) error {
tx.Rollback()
return err
}
sessionQuery := `
SET SESSION time_zone = '+00:00',
sql_mode = CONCAT(@@session.sql_mode, ',STRICT_ALL_TABLES')
`
_, err = tx.Exec(sessionQuery)
if err != nil {
err = fmt.Errorf("during setting session: %v", err)
return rollback(err)
}
for _, ev := range events {
eventDatabaseName := ev.Database()
if targetDatabaseName, exists := f.Config.DatabaseTargets[eventDatabaseName]; exists {
eventDatabaseName = targetDatabaseName
}
sql, args, err := ev.AsSQLQuery(&schema.Table{Schema: eventDatabaseName, Name: ev.Table()})
if err != nil {
err = fmt.Errorf("during generating sql query: %v", err)
return rollback(err)
}
_, err = tx.Exec(sql, args...)
if err != nil {
err = fmt.Errorf("during exec query (%s %v): %v", sql, args, err)
return rollback(err)
}
}
return tx.Commit()
}
func checkConnection(logger *logrus.Entry, dsn string, db *sql.DB) error {
row := db.QueryRow("SHOW STATUS LIKE 'Ssl_cipher'")
var name, cipher string
err := row.Scan(&name, &cipher)
if err != nil {
return err
}
hasSSL := cipher != ""
logger.WithFields(logrus.Fields{
"hasSSL": hasSSL,
"ssl_cipher": cipher,
"dsn": dsn,
}).Infof("connected to %s", dsn)
return nil
}
func checkConnectionForBinlogFormat(db *sql.DB) error {
var name, value string
row := db.QueryRow("SHOW VARIABLES LIKE 'binlog_format'")
err := row.Scan(&name, &value)
if err != nil {
return err
}
if strings.ToUpper(value) != "ROW" {
return fmt.Errorf("binlog_format must be ROW, not %s", value)
}
row = db.QueryRow("SHOW VARIABLES LIKE 'binlog_row_image'")
err = row.Scan(&name, &value)
if strings.ToUpper(value) != "FULL" {
return fmt.Errorf("binlog_row_image must be FULL, not %s", value)
}
return nil
}