-
Notifications
You must be signed in to change notification settings - Fork 72
/
ferry.go
1202 lines (998 loc) · 35.3 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
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ghostferry
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
sql "github.com/Shopify/ghostferry/sqlwrapper"
_ "net/http/pprof"
siddontangmysql "github.com/go-mysql-org/go-mysql/mysql"
"github.com/go-sql-driver/mysql"
siddontanglog "github.com/siddontang/go-log/log"
"github.com/sirupsen/logrus"
)
var (
zeroPosition siddontangmysql.Position
VersionString string = "?.?.?+??????????????+???????"
WebUiBasedir string = ""
)
const (
StateStarting = "starting"
StateCopying = "copying"
StateWaitingForCutover = "wait-for-cutover"
StateVerifyBeforeCutover = "verify-before-cutover"
StateCutover = "cutover"
StateDone = "done"
)
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
ControlServer *ControlServer
BinlogStreamer *BinlogStreamer
BinlogWriter *BinlogWriter
targetVerifierWg *sync.WaitGroup
TargetVerifier *TargetVerifier
DataIterator *DataIterator
BatchWriter *BatchWriter
StateTracker *StateTracker
ErrorHandler ErrorHandler
Throttler Throttler
WaitUntilReplicaIsCaughtUpToMaster *WaitUntilReplicaIsCaughtUpToMaster
// This can be specified by the caller. If specified, do not specify
// VerifierType in Config (or as an empty string) or an error will be
// returned in Initialize.
//
// If VerifierType is specified and this is nil on Ferry initialization, a
// Verifier will be created by Initialize. If an IterativeVerifier is to be
// created, IterativeVerifierConfig will be used to create the verifier.
Verifier Verifier
inlineVerifier *InlineVerifier
Tables TableSchemaCache
StartTime time.Time
DoneTime time.Time
OverallState atomic.Value
logger *logrus.Entry
rowCopyCompleteCh chan struct{}
}
func (f *Ferry) NewDataIterator() *DataIterator {
f.ensureInitialized()
dataIterator := &DataIterator{
DB: f.SourceDB,
Concurrency: f.Config.DataIterationConcurrency,
SelectFingerprint: f.Config.VerifierType == VerifierTypeInline,
ErrorHandler: f.ErrorHandler,
CursorConfig: &CursorConfig{
DB: f.SourceDB,
Throttler: f.Throttler,
BatchSize: &f.Config.UpdatableConfig.DataIterationBatchSize,
BatchSizePerTableOverride: f.Config.DataIterationBatchSizePerTableOverride,
ReadRetries: f.Config.DBReadRetries,
},
StateTracker: f.StateTracker,
}
if f.CopyFilter != nil {
dataIterator.CursorConfig.BuildSelect = f.CopyFilter.BuildSelect
}
return dataIterator
}
func (f *Ferry) NewDataIteratorWithoutStateTracker() *DataIterator {
dataIterator := f.NewDataIterator()
dataIterator.StateTracker = nil
return dataIterator
}
func (f *Ferry) NewSourceBinlogStreamer() *BinlogStreamer {
return f.newBinlogStreamer(f.SourceDB, f.Config.Source, nil, nil, "source_binlog_streamer")
}
func (f *Ferry) NewTargetBinlogStreamer() (*BinlogStreamer, error) {
schemaRewrites, err := TargetToSourceRewrites(f.Config.DatabaseRewrites)
if err != nil {
return nil, err
}
tableRewrites, err := TargetToSourceRewrites(f.Config.TableRewrites)
if err != nil {
return nil, err
}
return f.newBinlogStreamer(f.TargetDB, f.Config.Target, schemaRewrites, tableRewrites, "target_binlog_streamer"), nil
}
func (f *Ferry) newBinlogStreamer(db *sql.DB, dbConf *DatabaseConfig, schemaRewrites, tableRewrites map[string]string, logTag string) *BinlogStreamer {
f.ensureInitialized()
return &BinlogStreamer{
DB: db,
DBConfig: dbConf,
MyServerId: f.Config.MyServerId,
ErrorHandler: f.ErrorHandler,
Filter: f.CopyFilter,
TableSchema: f.Tables,
LogTag: logTag,
DatabaseRewrites: schemaRewrites,
TableRewrites: tableRewrites,
}
}
func (f *Ferry) NewBinlogWriter() *BinlogWriter {
f.ensureInitialized()
return &BinlogWriter{
DB: f.TargetDB,
DatabaseRewrites: f.Config.DatabaseRewrites,
TableRewrites: f.Config.TableRewrites,
Throttler: f.Throttler,
BatchSize: f.Config.BinlogEventBatchSize,
WriteRetries: f.Config.DBWriteRetries,
ErrorHandler: f.ErrorHandler,
StateTracker: f.StateTracker,
}
}
func (f *Ferry) NewBinlogWriterWithoutStateTracker() *BinlogWriter {
binlogWriter := f.NewBinlogWriter()
binlogWriter.StateTracker = nil
return binlogWriter
}
func (f *Ferry) NewBatchWriter() *BatchWriter {
f.ensureInitialized()
batchWriter := &BatchWriter{
DB: f.TargetDB,
StateTracker: f.StateTracker,
DatabaseRewrites: f.Config.DatabaseRewrites,
TableRewrites: f.Config.TableRewrites,
WriteRetries: f.Config.DBWriteRetries,
enableRowBatchSize: f.Config.EnableRowBatchSize,
}
batchWriter.Initialize()
return batchWriter
}
func (f *Ferry) NewBatchWriterWithoutStateTracker() *BatchWriter {
batchWriter := f.NewBatchWriter()
batchWriter.StateTracker = nil
return batchWriter
}
func (f *Ferry) NewChecksumTableVerifier() *ChecksumTableVerifier {
f.ensureInitialized()
return &ChecksumTableVerifier{
SourceDB: f.SourceDB,
TargetDB: f.TargetDB,
DatabaseRewrites: f.Config.DatabaseRewrites,
TableRewrites: f.Config.TableRewrites,
Tables: f.Tables.AsSlice(),
}
}
func (f *Ferry) NewInlineVerifier() *InlineVerifier {
f.ensureInitialized()
var binlogVerifyStore *BinlogVerifyStore
if f.StateToResumeFrom != nil && f.StateToResumeFrom.BinlogVerifyStore != nil {
binlogVerifyStore = NewBinlogVerifyStoreFromSerialized(f.StateToResumeFrom.BinlogVerifyStore)
} else {
binlogVerifyStore = NewBinlogVerifyStore()
}
return &InlineVerifier{
SourceDB: f.SourceDB,
TargetDB: f.TargetDB,
DatabaseRewrites: f.Config.DatabaseRewrites,
TableRewrites: f.Config.TableRewrites,
TableSchemaCache: f.Tables,
BatchSize: f.Config.BinlogEventBatchSize,
VerifyBinlogEventsInterval: f.Config.InlineVerifierConfig.verifyBinlogEventsInterval,
MaxExpectedDowntime: f.Config.InlineVerifierConfig.maxExpectedDowntime,
StateTracker: f.StateTracker,
ErrorHandler: f.ErrorHandler,
reverifyStore: binlogVerifyStore,
sourceStmtCache: NewStmtCache(),
targetStmtCache: NewStmtCache(),
logger: logrus.WithField("tag", "inline-verifier"),
}
}
func (f *Ferry) NewControlServer() (*ControlServer, error) {
f.ensureInitialized()
controlServer := &ControlServer{
Config: f.Config.ControlServerConfig,
F: f,
Verifier: f.Verifier,
}
err := controlServer.Initialize()
if err != nil {
return nil, err
}
return controlServer, nil
}
func (f *Ferry) NewInlineVerifierWithoutStateTracker() *InlineVerifier {
v := f.NewInlineVerifier()
v.StateTracker = nil
return v
}
func (f *Ferry) NewIterativeVerifier() (*IterativeVerifier, error) {
f.ensureInitialized()
var err error
config := f.Config.IterativeVerifierConfig
var maxExpectedDowntime time.Duration
if config.MaxExpectedDowntime != "" {
maxExpectedDowntime, err = time.ParseDuration(config.MaxExpectedDowntime)
if err != nil {
return nil, fmt.Errorf("invalid MaxExpectedDowntime: %v. this error should have been caught via .Validate()", err)
}
}
var compressionVerifier *CompressionVerifier
if config.TableColumnCompression != nil {
compressionVerifier, err = NewCompressionVerifier(config.TableColumnCompression)
if err != nil {
return nil, err
}
}
ignoredColumns := make(map[string]map[string]struct{})
for table, columns := range config.IgnoredColumns {
ignoredColumns[table] = make(map[string]struct{})
for _, column := range columns {
ignoredColumns[table][column] = struct{}{}
}
}
v := &IterativeVerifier{
CursorConfig: &CursorConfig{
DB: f.SourceDB,
BatchSize: &f.Config.UpdatableConfig.DataIterationBatchSize,
BatchSizePerTableOverride: f.Config.DataIterationBatchSizePerTableOverride,
ReadRetries: f.Config.DBReadRetries,
},
BinlogStreamer: f.BinlogStreamer,
SourceDB: f.SourceDB,
TargetDB: f.TargetDB,
CompressionVerifier: compressionVerifier,
Tables: f.Tables.AsSlice(),
TableSchemaCache: f.Tables,
IgnoredTables: config.IgnoredTables,
IgnoredColumns: ignoredColumns,
DatabaseRewrites: f.Config.DatabaseRewrites,
TableRewrites: f.Config.TableRewrites,
Concurrency: config.Concurrency,
MaxExpectedDowntime: maxExpectedDowntime,
}
if f.CopyFilter != nil {
v.CursorConfig.BuildSelect = f.CopyFilter.BuildSelect
}
return v, v.Initialize()
}
// 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.Store(StateStarting)
f.logger = logrus.WithField("tag", "ferry")
f.rowCopyCompleteCh = make(chan struct{})
f.logger.Infof("hello world from %s", VersionString)
// Kind of a hack for now. The ErrorHandler is originally intended to be
// passed in by the application. This here should only set a default value in
// case one is not passed in. However, ghostferry-sharding currently depend
// on ferry.ErrorHandler being not-nil, as the sanity checks performed at the
// beginning of this method will get its errors reported by the ErrorHandler.
// Since f88c58523988b9fc98f14c6a69c138279f257fe6 we no longer initialize the
// ErrorHandler outside of Ferry, meaning that we need to initialize this as
// early as possible.
if f.ErrorHandler == nil {
f.ErrorHandler = &PanicErrorHandler{
Ferry: f,
ErrorCallback: f.Config.ErrorCallback,
DumpStateToStdoutOnError: f.Config.DumpStateToStdoutOnError,
}
}
// Suppress go-mysql-org/go-mysql logging as we already log the equivalents.
// It also by defaults logs to stdout, which is different from Ghostferry
// logging, which all goes to stderr. stdout in Ghostferry is reserved for
// dumping states due to an abort.
siddontanglog.SetDefaultLogger(siddontanglog.NewDefault(&siddontanglog.NullHandler{}))
// Connect to the source and target databases and check the validity
// of the connections
f.SourceDB, err = f.Source.SqlDB(f.logger.WithField("dbname", "source"))
if err != nil {
f.logger.WithError(err).Error("failed to connect to source database")
return err
}
err = f.checkConnection("source", f.SourceDB)
if err != nil {
f.logger.WithError(err).Error("source connection checking failed")
return err
}
err = f.checkConnectionForBinlogFormat(f.SourceDB)
if err != nil {
f.logger.WithError(err).Error("binlog format for source db is not compatible")
return err
}
f.TargetDB, err = f.Target.SqlDB(f.logger.WithField("dbname", "target"))
if err != nil {
f.logger.WithError(err).Error("failed to connect to target database")
return err
}
err = f.checkConnection("target", f.TargetDB)
if err != nil {
f.logger.WithError(err).Error("target connection checking failed")
return err
}
if !f.Config.AllowSuperUserOnReadOnly {
isReplica, err := CheckDbIsAReplica(f.TargetDB)
if err != nil {
f.logger.WithError(err).Error("cannot check if target db is writable")
return err
}
if isReplica {
return fmt.Errorf("@@read_only must be OFF on target db")
}
}
// Check if we're running from a replica or not and sanity check
// the configurations given to Ghostferry as well as the configurations
// of the MySQL databases.
if f.WaitUntilReplicaIsCaughtUpToMaster != nil {
f.WaitUntilReplicaIsCaughtUpToMaster.ReplicaDB = f.SourceDB
if f.WaitUntilReplicaIsCaughtUpToMaster.MasterDB == nil {
err = errors.New("must specify a MasterDB")
f.logger.WithError(err).Error("must specify a MasterDB")
return err
}
err = f.checkConnection("source_master", f.WaitUntilReplicaIsCaughtUpToMaster.MasterDB)
if err != nil {
f.logger.WithError(err).Error("source master connection checking failed")
return err
}
// Ensures the query to check for position is executable.
_, err = f.WaitUntilReplicaIsCaughtUpToMaster.IsCaughtUp(zeroPosition, 1)
if err != nil {
f.logger.WithError(err).Error("cannot check replicated master position on the source database")
return err
}
isReplica, err := CheckDbIsAReplica(f.WaitUntilReplicaIsCaughtUpToMaster.MasterDB)
if err != nil {
f.logger.WithError(err).Error("cannot check if master is a read replica")
return err
}
if isReplica {
err = errors.New("source master is a read replica, not a master writer")
f.logger.WithError(err).Error("source master is a read replica")
return err
}
} else {
isReplica, err := CheckDbIsAReplica(f.SourceDB)
if err != nil {
f.logger.WithError(err).Error("cannot check if source is a replica")
return err
}
if isReplica {
err = errors.New("source is a read replica. running Ghostferry with a source replica is unsafe unless WaitUntilReplicaIsCaughtUpToMaster is used")
f.logger.WithError(err).Error("source is a read replica")
return err
}
}
// Initializing the necessary components of Ghostferry.
if f.Throttler == nil {
f.Throttler = &PauserThrottler{}
}
if f.StateToResumeFrom == nil {
f.StateTracker = NewStateTracker(f.DataIterationConcurrency * 10)
} else {
f.logger.WithFields(logrus.Fields{
"LastWrittenBinlogPosition": f.StateToResumeFrom.LastWrittenBinlogPosition,
"LastStoredBinlogPositionForInlineVerifier": f.StateToResumeFrom.LastStoredBinlogPositionForInlineVerifier,
"LastStoredBinlogPositionForTargetVerifier": f.StateToResumeFrom.LastStoredBinlogPositionForTargetVerifier,
}).Info("resuming from state")
f.StateTracker = NewStateTrackerFromSerializedState(f.DataIterationConcurrency*10, f.StateToResumeFrom)
}
// 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 PaginationKey of each table as well as finding
// which value in the binlog event correspond to which field in the
// table.
//
// If this is a resuming run and the last known table schema cache is not given
// we'll regenerate it from the source database, assuming it has not been
// changed.
if f.StateToResumeFrom == nil || f.StateToResumeFrom.LastKnownTableSchemaCache == nil {
metrics.Measure("LoadTables", nil, 1.0, func() {
f.Tables, err = LoadTables(f.SourceDB, f.TableFilter, f.CompressedColumnsForVerification, f.IgnoredColumnsForVerification, f.ForceIndexForVerification, f.CascadingPaginationColumnConfig)
})
if err != nil {
return err
}
} else {
f.Tables = f.StateToResumeFrom.LastKnownTableSchemaCache
}
if !f.Config.SkipForeignKeyConstraintsCheck {
err = f.checkSourceForeignKeyConstraints()
if err != nil {
f.logger.WithError(err).Error("foreign key constraints detected on the source database. Enable SkipForeignKeyConstraintsCheck to ignore this check and allow foreign keys")
return err
}
}
if f.Config.DataIterationBatchSizePerTableOverride != nil {
err = f.Config.DataIterationBatchSizePerTableOverride.UpdateBatchSizes(f.SourceDB, f.Tables)
if err != nil {
f.logger.WithError(err).Warn("Failed to update batch sizes for all tables")
}
}
// The iterative verifier needs the binlog streamer so this has to be first.
// Eventually this can be moved below the verifier initialization.
f.BinlogStreamer = f.NewSourceBinlogStreamer()
if !f.Config.SkipTargetVerification {
targetBinlogStreamer, err := f.NewTargetBinlogStreamer()
if err != nil {
return err
}
targetVerifier, err := NewTargetVerifier(f.TargetDB, f.StateTracker, targetBinlogStreamer)
if err != nil {
return err
}
f.TargetVerifier = targetVerifier
}
f.BinlogWriter = f.NewBinlogWriter()
f.DataIterator = f.NewDataIterator()
f.BatchWriter = f.NewBatchWriter()
if f.Config.VerifierType != "" {
if f.Verifier != nil {
return errors.New("VerifierType specified and Verifier is given. these are mutually exclusive options")
}
switch f.Config.VerifierType {
case VerifierTypeIterative:
f.Verifier, err = f.NewIterativeVerifier()
if err != nil {
return err
}
case VerifierTypeChecksumTable:
f.Verifier = f.NewChecksumTableVerifier()
case VerifierTypeInline:
// TODO: eventually we should have the inlineVerifier as an "always on"
// component. That will allow us to clean this up.
f.inlineVerifier = f.NewInlineVerifier()
f.Verifier = f.inlineVerifier
f.BatchWriter.InlineVerifier = f.inlineVerifier
case VerifierTypeNoVerification:
// skip
default:
return fmt.Errorf("'%s' is not a known VerifierType", f.Config.VerifierType)
}
}
if f.Config.ControlServerConfig.Enabled {
f.ControlServer, err = f.NewControlServer()
if err != nil {
return err
}
}
f.logger.Info("ferry initialized")
return nil
}
// Attach event listeners for Ghostferry components and connect the binlog
// streamer to the source shard
//
// Note: Binlog streaming doesn't start until Run. Here we simply connect to
// MySQL.
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.BinlogWriter.BufferBinlogEvents)
f.DataIterator.AddBatchListener(f.BatchWriter.WriteRowBatch)
if f.inlineVerifier != nil {
f.BinlogStreamer.AddEventListener(f.inlineVerifier.binlogEventListener)
}
// 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.
var sourcePos siddontangmysql.Position
var targetPos siddontangmysql.Position
var err error
if f.StateToResumeFrom != nil {
sourcePos, err = f.BinlogStreamer.ConnectBinlogStreamerToMysqlFrom(f.StateToResumeFrom.MinSourceBinlogPosition())
} else {
sourcePos, err = f.BinlogStreamer.ConnectBinlogStreamerToMysql()
}
if err != nil {
return err
}
if !f.Config.SkipTargetVerification {
if f.StateToResumeFrom != nil && f.StateToResumeFrom.LastStoredBinlogPositionForTargetVerifier != zeroPosition {
targetPos, err = f.TargetVerifier.BinlogStreamer.ConnectBinlogStreamerToMysqlFrom(f.StateToResumeFrom.LastStoredBinlogPositionForTargetVerifier)
} else {
targetPos, err = f.TargetVerifier.BinlogStreamer.ConnectBinlogStreamerToMysql()
}
}
if err != nil {
return err
}
// If we don't set this now, there is a race condition where Ghostferry
// is terminated with some rows copied but no binlog events are written.
// This guarentees that we are able to restart from a valid location.
f.StateTracker.UpdateLastResumableSourceBinlogPosition(sourcePos)
if f.inlineVerifier != nil {
f.StateTracker.UpdateLastResumableSourceBinlogPositionForInlineVerifier(sourcePos)
}
if !f.Config.SkipTargetVerification {
f.StateTracker.UpdateLastResumableBinlogPositionForTargetVerifier(targetPos)
}
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.Store(StateCopying)
if f.Config.EnablePProf {
go func() {
err := http.ListenAndServe("localhost:6060", nil)
if err != nil {
f.logger.WithError(err).Warn("pprof server finished")
}
}()
}
ctx, shutdown := context.WithCancel(context.Background())
handleError := func(name string, err error) {
if err != nil && err != context.Canceled {
f.ErrorHandler.Fatal(name, err)
}
}
supportingServicesWg := &sync.WaitGroup{}
supportingServicesWg.Add(1)
go func() {
defer supportingServicesWg.Done()
handleError("throttler", f.Throttler.Run(ctx))
}()
if f.Config.ControlServerConfig.Enabled {
go f.ControlServer.Run()
}
if f.Config.ProgressCallback.URI != "" {
supportingServicesWg.Add(1)
go func() {
defer supportingServicesWg.Done()
frequency := time.Duration(f.Config.ProgressReportFrequency) * time.Millisecond
for {
select {
case <-ctx.Done():
return
case <-time.After(frequency):
f.ReportProgress()
}
}
}()
}
if f.Config.StateCallback.URI != "" {
supportingServicesWg.Add(1)
go func() {
defer supportingServicesWg.Done()
frequency := time.Duration(f.Config.StateReportFrequency) * time.Millisecond
for {
select {
case <-ctx.Done():
return
case <-time.After(frequency):
f.ReportState()
}
}
}()
}
if f.DumpStateOnSignal {
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
s := <-c
if ctx.Err() == nil {
// Ghostferry is still running
if f.OverallState.Load() != StateCutover {
// Save state dump and exit if not during the cutover stage
f.ErrorHandler.Fatal("user_interrupt", fmt.Errorf("signal received: %v", s.String()))
} else {
// Log and ignore the signal during cutover
f.logger.Warnf("Received signal: %s during cutover. "+
"Refusing to interrupt and will attempt to complete the run.", s.String())
}
} else {
// shutdown() has been called and Ghostferry is done.
os.Exit(0)
}
}()
}
inlineVerifierWg := &sync.WaitGroup{}
inlineVerifierContext, stopInlineVerifier := context.WithCancel(ctx)
if f.inlineVerifier != nil {
inlineVerifierWg.Add(1)
go func() {
defer inlineVerifierWg.Done()
f.inlineVerifier.PeriodicallyVerifyBinlogEvents(inlineVerifierContext)
}()
}
binlogWg := &sync.WaitGroup{}
binlogWg.Add(1)
go func() {
defer binlogWg.Done()
f.BinlogWriter.Run()
}()
binlogWg.Add(1)
go func() {
defer binlogWg.Done()
f.BinlogStreamer.Run()
f.BinlogWriter.Stop()
}()
if !f.Config.SkipTargetVerification {
f.targetVerifierWg = &sync.WaitGroup{}
f.targetVerifierWg.Add(1)
go func() {
defer f.targetVerifierWg.Done()
f.TargetVerifier.BinlogStreamer.Run()
}()
}
dataIteratorWg := &sync.WaitGroup{}
dataIteratorWg.Add(1)
go func() {
defer dataIteratorWg.Done()
f.DataIterator.Run(f.Tables.AsSlice())
}()
dataIteratorWg.Wait()
f.logger.Info("data copy is complete, waiting for cutover")
f.OverallState.Store(StateWaitingForCutover)
f.waitUntilAutomaticCutoverIsTrue()
if f.inlineVerifier != nil {
// Stops the periodic verification of binlogs in the inline verifier
// This should be okay as we enqueue the binlog events into the verifier,
// which will be verified both in VerifyBeforeCutover and
// VerifyDuringCutover.
stopInlineVerifier()
inlineVerifierWg.Wait()
}
if f.Verifier != nil {
f.logger.Info("calling VerifyBeforeCutover")
f.OverallState.Store(StateVerifyBeforeCutover)
metrics.Measure("VerifyBeforeCutover", nil, 1.0, func() {
err := f.Verifier.VerifyBeforeCutover()
if err != nil {
f.logger.WithError(err).Error("VerifyBeforeCutover failed")
f.ErrorHandler.Fatal("verifier", err)
}
})
}
// Cutover is a cooperative activity between the Ghostferry library and
// applications built on Ghostferry:
//
// 1. At this point (before stopping the binlog streaming), the application
// should prepare to cutover, such as setting the source database to
// READONLY.
// 2. Once that is complete, trigger the cutover by requesting the
// BinlogStreamer to stop (WaitUntilBinlogStreamerCatchesUp and
// FlushBinlogAndStopStreaming).
// 3. Once the binlog stops, this Run function will return and the cutover
// will be completed. Application and human operators can perform
// additional operations, such as additional verification, and repointing
// any consumers of the source database to use the target database.
//
// During cutover, if verifiers are enabled, VerifyDuringCutover should be
// called. This can be performed as a part of the ControlServer, if that
// component is used.
f.logger.Info("entering cutover phase, notifying caller that row copy is complete")
f.OverallState.Store(StateCutover)
if f.Config.ProgressCallback.URI != "" {
f.ReportProgress()
}
f.notifyRowCopyComplete()
binlogWg.Wait()
f.logger.Info("ghostferry run is complete, shutting down auxiliary services")
f.OverallState.Store(StateDone)
f.DoneTime = time.Now()
shutdown()
supportingServicesWg.Wait()
if f.Config.ProgressCallback.URI != "" {
f.ReportProgress()
}
}
func (f *Ferry) RunStandaloneDataCopy(tables []*TableSchema) error {
if len(tables) == 0 {
return nil
}
dataIterator := f.NewDataIteratorWithoutStateTracker()
batchWriter := f.NewBatchWriterWithoutStateTracker()
// Always use the InlineVerifier to verify the copied data here.
dataIterator.SelectFingerprint = true
batchWriter.InlineVerifier = f.NewInlineVerifierWithoutStateTracker()
batchWriter.EnforceInlineVerification = true // Don't have the Binlog component at this stage, so no reverify
// BUG: if the PanicErrorHandler fires while running the standalone copy, we
// will get an error dump even though we should not get one, which could be
// misleading.
dataIterator.AddBatchListener(batchWriter.WriteRowBatch)
f.logger.WithField("tables", tables).Info("starting delta table copy in cutover")
dataIterator.Run(tables)
return nil
}
// 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() ||
(!f.Config.SkipTargetVerification && !f.TargetVerifier.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() {
if f.WaitUntilReplicaIsCaughtUpToMaster != nil {
isReplica, err := CheckDbIsAReplica(f.WaitUntilReplicaIsCaughtUpToMaster.MasterDB)
if err != nil {
f.ErrorHandler.Fatal("wait_replica", err)
}
if isReplica {
err = errors.New("source master is no longer a master writer")
msg := "aborting the ferry since the source master is no longer the master writer " +
"this means that the perceived master can be lagging compared to the actual master " +
"and lead to missed writes. aborting ferry"
f.logger.Error(msg)
f.ErrorHandler.Fatal("wait_replica", err)
}
err = f.WaitUntilReplicaIsCaughtUpToMaster.Wait()
if err != nil {
f.ErrorHandler.Fatal("wait_replica", err)
}
}
f.BinlogStreamer.FlushAndStop()
}
func (f *Ferry) StopTargetVerifier() {
if !f.Config.SkipTargetVerification {
f.TargetVerifier.BinlogStreamer.FlushAndStop()
f.targetVerifierWg.Wait()
}
}
func (f *Ferry) StartCutover() time.Time {
var (
err error
cutoverStart time.Time
)
err = WithRetries(f.Config.MaxCutoverRetries, time.Duration(f.Config.CutoverRetryWaitSeconds)*time.Second, f.logger, "get cutover lock", func() (err error) {
metrics.Measure("CutoverLock", nil, 1.0, func() {
cutoverStart = time.Now()
err = f.Config.CutoverLock.Post(&http.Client{})
})
return err
})
if err != nil {
f.logger.WithField("error", err).Errorf("locking failed, aborting run")
f.ErrorHandler.Fatal("cutover", err)
}
return cutoverStart
}
func (f *Ferry) EndCutover(cutoverStart time.Time) {
var err error
metrics.Measure("CutoverUnlock", nil, 1.0, func() {
err = f.Config.CutoverUnlock.Post(&http.Client{})
})
if err != nil {
f.logger.WithField("error", err).Errorf("unlocking failed, aborting run")
f.ErrorHandler.Fatal("cutover", err)
}
metrics.Timer("CutoverTime", time.Since(cutoverStart), nil, 1.0)
}
func (f *Ferry) SerializeStateToJSON() (string, error) {
if f.StateTracker == nil {
err := errors.New("no valid StateTracker")
return "", err
}
var binlogVerifyStore *BinlogVerifyStore = nil
if f.inlineVerifier != nil {
binlogVerifyStore = f.inlineVerifier.reverifyStore
}
serializedState := f.StateTracker.Serialize(f.Tables, binlogVerifyStore)
if f.Config.DoNotIncludeSchemaCacheInStateDump {
serializedState.LastKnownTableSchemaCache = nil
}
stateBytes, err := json.MarshalIndent(serializedState, "", " ")
return string(stateBytes), err
}
func (f *Ferry) Progress() *Progress {
s := &Progress{
CurrentState: f.OverallState.Load().(string),
CustomPayload: f.Config.ProgressCallback.Payload,
VerifierType: f.VerifierType,
}
s.Throttled = f.Throttler.Throttled()
now := time.Now()
// Binlog Progress
s.LastSuccessfulBinlogPos = f.BinlogStreamer.lastStreamedBinlogPosition
s.BinlogStreamerLag = now.Sub(f.BinlogStreamer.lastProcessedEventTime).Seconds()
s.BinlogWriterLag = now.Sub(f.BinlogWriter.lastProcessedEventTime).Seconds()
s.FinalBinlogPos = f.BinlogStreamer.stopAtBinlogPosition
if f.TargetVerifier != nil {
s.TargetBinlogStreamerLag = now.Sub(f.TargetVerifier.BinlogStreamer.lastProcessedEventTime).Seconds()
}
// Table Progress
serializedState := f.StateTracker.Serialize(nil, nil)
// Note the below will not necessarily be synchronized with serializedState.
// This is fine as we don't need to be super precise with performance data.
rowStatsWrittenPerTable := f.StateTracker.RowStatsWrittenPerTable()
s.Tables = make(map[string]TableProgress)
targetPaginationKeys := make(map[string]uint64)
f.DataIterator.targetPaginationKeys.Range(func(k, v interface{}) bool {
targetPaginationKeys[k.(string)] = v.(uint64)
return true
})