/
traffic_switcher.go
1649 lines (1517 loc) · 58.6 KB
/
traffic_switcher.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
/*
Copyright 2019 The Vitess Authors.
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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package wrangler
import (
"context"
"errors"
"fmt"
"reflect"
"sort"
"strings"
"sync"
"time"
"vitess.io/vitess/go/vt/discovery"
"vitess.io/vitess/go/json2"
"vitess.io/vitess/go/vt/binlog/binlogplayer"
"vitess.io/vitess/go/vt/concurrency"
"vitess.io/vitess/go/vt/key"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/logutil"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/topo/topoproto"
"vitess.io/vitess/go/vt/topotools"
"vitess.io/vitess/go/vt/vtctl/workflow"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vtgate/vindexes"
"vitess.io/vitess/go/vt/vttablet/tabletmanager/vreplication"
"vitess.io/vitess/go/vt/vttablet/tmclient"
binlogdatapb "vitess.io/vitess/go/vt/proto/binlogdata"
querypb "vitess.io/vitess/go/vt/proto/query"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
vschemapb "vitess.io/vitess/go/vt/proto/vschema"
)
const (
frozenStr = "FROZEN"
errorNoStreams = "no streams found in keyspace %s for: %s"
// use pt-osc's naming convention, this format also ensures vstreamer ignores such tables
renameTableTemplate = "_%.59s_old" // limit table name to 64 characters
)
// accessType specifies the type of access for a shard (allow/disallow writes).
type accessType int
const (
allowWrites = accessType(iota)
disallowWrites
)
// trafficSwitcher contains the metadata for switching read and write traffic
// for vreplication streams.
type trafficSwitcher struct {
migrationType binlogdatapb.MigrationType
wr *Wrangler
workflow string
// if frozen is true, the rest of the fields are not set.
frozen bool
reverseWorkflow string
id int64
sources map[string]*workflow.MigrationSource
targets map[string]*workflow.MigrationTarget
sourceKeyspace string
targetKeyspace string
tables []string
sourceKSSchema *vindexes.KeyspaceSchema
optCells string //cells option passed to MoveTables/Reshard
optTabletTypes string //tabletTypes option passed to MoveTables/Reshard
externalCluster string
externalTopo *topo.Server
}
/*
begin: implementation of workflow.ITrafficSwitcher
(NOTE:@ajm188) Please see comments on that interface type for why this exists.
This is temporary to allow workflow.StreamMigrator to use this trafficSwitcher
code and should be removed in the very near-term when we move trafficSwitcher to
package workflow as well.
*/
var _ workflow.ITrafficSwitcher = (*trafficSwitcher)(nil)
func (ts *trafficSwitcher) TopoServer() *topo.Server { return ts.wr.ts }
func (ts *trafficSwitcher) TabletManagerClient() tmclient.TabletManagerClient { return ts.wr.tmc }
func (ts *trafficSwitcher) Logger() logutil.Logger { return ts.wr.logger }
func (ts *trafficSwitcher) VReplicationExec(ctx context.Context, alias *topodatapb.TabletAlias, query string) (*querypb.QueryResult, error) {
return ts.wr.VReplicationExec(ctx, alias, query)
}
func (ts *trafficSwitcher) MigrationType() binlogdatapb.MigrationType { return ts.migrationType }
func (ts *trafficSwitcher) ReverseWorkflowName() string { return ts.reverseWorkflow }
func (ts *trafficSwitcher) SourceKeyspaceName() string { return ts.sourceKSSchema.Keyspace.Name }
func (ts *trafficSwitcher) SourceKeyspaceSchema() *vindexes.KeyspaceSchema { return ts.sourceKSSchema }
func (ts *trafficSwitcher) WorkflowName() string { return ts.workflow }
func (ts *trafficSwitcher) ForAllSources(f func(source *workflow.MigrationSource) error) error {
return ts.forAllSources(f)
}
func (ts *trafficSwitcher) ForAllTargets(f func(source *workflow.MigrationTarget) error) error {
return ts.forAllTargets(f)
}
/* end: implementation of workflow.ITrafficSwitcher */
// For a Reshard, to check whether we have switched reads for a tablet type, we check if any one of the source shards has
// the query service disabled in its tablet control record
func (wr *Wrangler) getCellsWithShardReadsSwitched(ctx context.Context, targetKeyspace string, si *topo.ShardInfo, tabletTypeStr string) (
cellsSwitched, cellsNotSwitched []string, err error) {
tabletType, err := topoproto.ParseTabletType(tabletTypeStr)
if err != nil {
return nil, nil, err
}
s := workflow.NewServer(wr.ts, wr.tmc)
return s.GetCellsWithShardReadsSwitched(ctx, targetKeyspace, si, tabletType)
}
// For MoveTables, to check whether we have switched reads for a tablet type, we check whether the routing rule
// for the tablet_type is pointing to the target keyspace
func (wr *Wrangler) getCellsWithTableReadsSwitched(ctx context.Context, targetKeyspace, table, tabletTypeStr string) (
cellsSwitched, cellsNotSwitched []string, err error) {
tabletType, err := topoproto.ParseTabletType(tabletTypeStr)
if err != nil {
return nil, nil, err
}
s := workflow.NewServer(wr.ts, wr.tmc)
return s.GetCellsWithTableReadsSwitched(ctx, targetKeyspace, table, tabletType)
}
func (wr *Wrangler) getWorkflowState(ctx context.Context, targetKeyspace, workflowName string) (*trafficSwitcher, *workflow.State, error) {
ts, err := wr.buildTrafficSwitcher(ctx, targetKeyspace, workflowName)
if ts == nil || err != nil {
if errors.Is(err, workflow.ErrNoStreams) || err.Error() == fmt.Sprintf(errorNoStreams, targetKeyspace, workflowName) {
return nil, nil, nil
}
wr.Logger().Errorf("buildTrafficSwitcher failed: %v", err)
return nil, nil, err
}
ws := &workflow.State{Workflow: workflowName, TargetKeyspace: targetKeyspace}
ws.SourceKeyspace = ts.sourceKeyspace
var cellsSwitched, cellsNotSwitched []string
var keyspace string
var reverse bool
// we reverse writes by using the source_keyspace.workflowname_reverse workflow spec, so we need to use the
// source of the reverse workflow, which is the target of the workflow initiated by the user for checking routing rules
// Similarly we use a target shard of the reverse workflow as the original source to check if writes have been switched
if strings.HasSuffix(workflowName, "_reverse") {
reverse = true
keyspace = ws.SourceKeyspace
workflowName = workflow.ReverseWorkflowName(workflowName)
} else {
keyspace = targetKeyspace
}
if ts.migrationType == binlogdatapb.MigrationType_TABLES {
ws.WorkflowType = workflow.TypeMoveTables
// we assume a consistent state, so only choose routing rule for one table for replica/rdonly
if len(ts.tables) == 0 {
return nil, nil, fmt.Errorf("no tables in workflow %s.%s", keyspace, workflowName)
}
table := ts.tables[0]
cellsSwitched, cellsNotSwitched, err = wr.getCellsWithTableReadsSwitched(ctx, keyspace, table, "rdonly")
if err != nil {
return nil, nil, err
}
ws.RdonlyCellsNotSwitched, ws.RdonlyCellsSwitched = cellsNotSwitched, cellsSwitched
cellsSwitched, cellsNotSwitched, err = wr.getCellsWithTableReadsSwitched(ctx, keyspace, table, "replica")
if err != nil {
return nil, nil, err
}
ws.ReplicaCellsNotSwitched, ws.ReplicaCellsSwitched = cellsNotSwitched, cellsSwitched
rules, err := topotools.GetRoutingRules(ctx, ts.wr.ts)
if err != nil {
return nil, nil, err
}
for _, table := range ts.tables {
rr := rules[table]
// if a rule exists for the table and points to the target keyspace, writes have been switched
if len(rr) > 0 && rr[0] == fmt.Sprintf("%s.%s", keyspace, table) {
ws.WritesSwitched = true
}
}
} else {
ws.WorkflowType = workflow.TypeReshard
// we assume a consistent state, so only choose one shard
var shard *topo.ShardInfo
if reverse {
shard = ts.targetShards()[0]
} else {
shard = ts.sourceShards()[0]
}
cellsSwitched, cellsNotSwitched, err = wr.getCellsWithShardReadsSwitched(ctx, keyspace, shard, "rdonly")
if err != nil {
return nil, nil, err
}
ws.RdonlyCellsNotSwitched, ws.RdonlyCellsSwitched = cellsNotSwitched, cellsSwitched
cellsSwitched, cellsNotSwitched, err = wr.getCellsWithShardReadsSwitched(ctx, keyspace, shard, "replica")
if err != nil {
return nil, nil, err
}
ws.ReplicaCellsNotSwitched, ws.ReplicaCellsSwitched = cellsNotSwitched, cellsSwitched
if !shard.IsMasterServing {
ws.WritesSwitched = true
}
}
return ts, ws, nil
}
func (wr *Wrangler) doCellsHaveRdonlyTablets(ctx context.Context, cells []string) (bool, error) {
areAnyRdonly := func(tablets []*topo.TabletInfo) bool {
for _, tablet := range tablets {
if tablet.Type == topodatapb.TabletType_RDONLY {
return true
}
}
return false
}
if len(cells) == 0 {
tablets, err := topotools.GetAllTabletsAcrossCells(ctx, wr.ts)
if err != nil {
return false, err
}
if areAnyRdonly(tablets) {
return true, nil
}
} else {
for _, cell := range cells {
tablets, err := topotools.GetAllTablets(ctx, wr.ts, cell)
if err != nil {
return false, err
}
if areAnyRdonly(tablets) {
return true, nil
}
}
}
return false, nil
}
// SwitchReads is a generic way of switching read traffic for a resharding workflow.
func (wr *Wrangler) SwitchReads(ctx context.Context, targetKeyspace, workflowName string, servedTypes []topodatapb.TabletType,
cells []string, direction workflow.TrafficSwitchDirection, dryRun bool) (*[]string, error) {
ts, ws, err := wr.getWorkflowState(ctx, targetKeyspace, workflowName)
if err != nil {
wr.Logger().Errorf("getWorkflowState failed: %v", err)
return nil, err
}
if ts == nil {
errorMsg := fmt.Sprintf("workflow %s not found in keyspace %s", workflowName, targetKeyspace)
wr.Logger().Errorf(errorMsg)
return nil, fmt.Errorf(errorMsg)
}
log.Infof("SwitchReads: %s.%s tt %+v, cells %+v, workflow state: %+v", targetKeyspace, workflowName, servedTypes, cells, ws)
var switchReplicas, switchRdonly bool
for _, servedType := range servedTypes {
if servedType != topodatapb.TabletType_REPLICA && servedType != topodatapb.TabletType_RDONLY {
return nil, fmt.Errorf("tablet type must be REPLICA or RDONLY: %v", servedType)
}
if direction == workflow.DirectionBackward && servedType == topodatapb.TabletType_REPLICA && len(ws.ReplicaCellsSwitched) == 0 {
return nil, fmt.Errorf("requesting reversal of SwitchReads for REPLICAs but REPLICA reads have not been switched")
}
if direction == workflow.DirectionBackward && servedType == topodatapb.TabletType_RDONLY && len(ws.RdonlyCellsSwitched) == 0 {
return nil, fmt.Errorf("requesting reversal of SwitchReads for RDONLYs but RDONLY reads have not been switched")
}
switch servedType {
case topodatapb.TabletType_REPLICA:
switchReplicas = true
case topodatapb.TabletType_RDONLY:
switchRdonly = true
}
}
// if there are no rdonly tablets in the cells ask to switch rdonly tablets as well so that routing rules
// are updated for rdonly as well. Otherwise vitess will not know that the workflow has completed and will
// incorrectly report that not all reads have been switched. User currently is forced to switch non-existent rdonly tablets
if switchReplicas && !switchRdonly {
var err error
rdonlyTabletsExist, err := wr.doCellsHaveRdonlyTablets(ctx, cells)
if err != nil {
return nil, err
}
if !rdonlyTabletsExist {
servedTypes = append(servedTypes, topodatapb.TabletType_RDONLY)
}
}
// If journals exist notify user and fail
journalsExist, _, err := ts.checkJournals(ctx)
if err != nil {
wr.Logger().Errorf("checkJournals failed: %v", err)
return nil, err
}
if journalsExist {
log.Infof("Found a previous journal entry for %d", ts.id)
}
var sw iswitcher
if dryRun {
sw = &switcherDryRun{ts: ts, drLog: NewLogRecorder()}
} else {
sw = &switcher{ts: ts, wr: wr}
}
if err := ts.validate(ctx); err != nil {
ts.wr.Logger().Errorf("validate failed: %v", err)
return nil, err
}
// For reads, locking the source keyspace is sufficient.
ctx, unlock, lockErr := sw.lockKeyspace(ctx, ts.sourceKeyspace, "SwitchReads")
if lockErr != nil {
ts.wr.Logger().Errorf("LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer unlock(&err)
if ts.migrationType == binlogdatapb.MigrationType_TABLES {
if err := sw.switchTableReads(ctx, cells, servedTypes, direction); err != nil {
ts.wr.Logger().Errorf("switchTableReads failed: %v", err)
return nil, err
}
return sw.logs(), nil
}
wr.Logger().Infof("About to switchShardReads: %+v, %+v, %+v", cells, servedTypes, direction)
if err := ts.switchShardReads(ctx, cells, servedTypes, direction); err != nil {
ts.wr.Logger().Errorf("switchShardReads failed: %v", err)
return nil, err
}
wr.Logger().Infof("switchShardReads Completed: %+v, %+v, %+v", cells, servedTypes, direction)
if err := wr.ts.ValidateSrvKeyspace(ctx, targetKeyspace, strings.Join(cells, ",")); err != nil {
err2 := vterrors.Wrapf(err, "After switching shard reads, found SrvKeyspace for %s is corrupt in cell %s",
targetKeyspace, strings.Join(cells, ","))
log.Errorf("%w", err2)
return nil, err2
}
return sw.logs(), nil
}
func (wr *Wrangler) areTabletsAvailableToStreamFrom(ctx context.Context, ts *trafficSwitcher, keyspace string, shards []*topo.ShardInfo) error {
var cells []string
tabletTypes := ts.optTabletTypes
if ts.optCells != "" {
cells = strings.Split(ts.optCells, ",")
}
// FIXME: currently there is a default setting in the tablet that is used if user does not specify a tablet type,
// we use the value specified in the tablet flag `-vreplication_tablet_type`
// but ideally we should populate the vreplication table with a default value when we setup the workflow
if tabletTypes == "" {
tabletTypes = "MASTER,REPLICA"
}
var wg sync.WaitGroup
allErrors := &concurrency.AllErrorRecorder{}
for _, shard := range shards {
wg.Add(1)
go func(cells []string, keyspace string, shard *topo.ShardInfo) {
defer wg.Done()
if cells == nil {
cells = append(cells, shard.MasterAlias.Cell)
}
tp, err := discovery.NewTabletPicker(wr.ts, cells, keyspace, shard.ShardName(), tabletTypes)
if err != nil {
allErrors.RecordError(err)
return
}
tablets := tp.GetMatchingTablets(ctx)
if len(tablets) == 0 {
allErrors.RecordError(fmt.Errorf("no tablet found to source data in keyspace %s, shard %s", keyspace, shard.ShardName()))
return
}
}(cells, keyspace, shard)
}
wg.Wait()
if allErrors.HasErrors() {
log.Errorf("%s", allErrors.Error())
return allErrors.Error()
}
return nil
}
// SwitchWrites is a generic way of migrating write traffic for a resharding workflow.
func (wr *Wrangler) SwitchWrites(ctx context.Context, targetKeyspace, workflowName string, timeout time.Duration,
cancel, reverse, reverseReplication bool, dryRun bool) (journalID int64, dryRunResults *[]string, err error) {
ts, ws, err := wr.getWorkflowState(ctx, targetKeyspace, workflowName)
_ = ws
if err != nil {
wr.Logger().Errorf("getWorkflowState failed: %v", err)
return 0, nil, err
}
if ts == nil {
errorMsg := fmt.Sprintf("workflow %s not found in keyspace %s", workflowName, targetKeyspace)
wr.Logger().Errorf(errorMsg)
return 0, nil, fmt.Errorf(errorMsg)
}
var sw iswitcher
if dryRun {
sw = &switcherDryRun{ts: ts, drLog: NewLogRecorder()}
} else {
sw = &switcher{ts: ts, wr: wr}
}
if ts.frozen {
ts.wr.Logger().Warningf("Writes have already been switched for workflow %s, nothing to do here", ts.workflow)
return 0, sw.logs(), nil
}
ts.wr.Logger().Infof("Built switching metadata: %+v", ts)
if err := ts.validate(ctx); err != nil {
ts.wr.Logger().Errorf("validate failed: %v", err)
return 0, nil, err
}
if reverseReplication {
err := wr.areTabletsAvailableToStreamFrom(ctx, ts, ts.targetKeyspace, ts.targetShards())
if err != nil {
return 0, nil, err
}
}
// Need to lock both source and target keyspaces.
tctx, sourceUnlock, lockErr := sw.lockKeyspace(ctx, ts.sourceKeyspace, "SwitchWrites")
if lockErr != nil {
ts.wr.Logger().Errorf("LockKeyspace failed: %v", lockErr)
return 0, nil, lockErr
}
ctx = tctx
defer sourceUnlock(&err)
if ts.targetKeyspace != ts.sourceKeyspace {
tctx, targetUnlock, lockErr := sw.lockKeyspace(ctx, ts.targetKeyspace, "SwitchWrites")
if lockErr != nil {
ts.wr.Logger().Errorf("LockKeyspace failed: %v", lockErr)
return 0, nil, lockErr
}
ctx = tctx
defer targetUnlock(&err)
}
// If no journals exist, sourceWorkflows will be initialized by sm.MigrateStreams.
journalsExist, sourceWorkflows, err := ts.checkJournals(ctx)
if err != nil {
ts.wr.Logger().Errorf("checkJournals failed: %v", err)
return 0, nil, err
}
if !journalsExist {
ts.wr.Logger().Infof("No previous journals were found. Proceeding normally.")
sm, err := workflow.BuildStreamMigrator(ctx, ts, cancel)
if err != nil {
ts.wr.Logger().Errorf("buildStreamMigrater failed: %v", err)
return 0, nil, err
}
if cancel {
sw.cancelMigration(ctx, sm)
return 0, sw.logs(), nil
}
ts.wr.Logger().Infof("Stopping streams")
sourceWorkflows, err = sw.stopStreams(ctx, sm)
if err != nil {
ts.wr.Logger().Errorf("stopStreams failed: %v", err)
for key, streams := range sm.Streams() {
for _, stream := range streams {
ts.wr.Logger().Errorf("stream in stopStreams: key %s shard %s stream %+v", key, stream.BinlogSource.Shard, stream.BinlogSource)
}
}
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
ts.wr.Logger().Infof("Stopping source writes")
if err := sw.stopSourceWrites(ctx); err != nil {
ts.wr.Logger().Errorf("stopSourceWrites failed: %v", err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
ts.wr.Logger().Infof("Waiting for streams to catchup")
if err := sw.waitForCatchup(ctx, timeout); err != nil {
ts.wr.Logger().Errorf("waitForCatchup failed: %v", err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
ts.wr.Logger().Infof("Migrating streams")
if err := sw.migrateStreams(ctx, sm); err != nil {
ts.wr.Logger().Errorf("migrateStreams failed: %v", err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
ts.wr.Logger().Infof("Creating reverse streams")
if err := sw.createReverseVReplication(ctx); err != nil {
ts.wr.Logger().Errorf("createReverseVReplication failed: %v", err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
} else {
if cancel {
err := fmt.Errorf("traffic switching has reached the point of no return, cannot cancel")
ts.wr.Logger().Errorf("%v", err)
return 0, nil, err
}
ts.wr.Logger().Infof("Journals were found. Completing the left over steps.")
// Need to gather positions in case all journals were not created.
if err := ts.gatherPositions(ctx); err != nil {
ts.wr.Logger().Errorf("gatherPositions failed: %v", err)
return 0, nil, err
}
}
// This is the point of no return. Once a journal is created,
// traffic can be redirected to target shards.
if err := sw.createJournals(ctx, sourceWorkflows); err != nil {
ts.wr.Logger().Errorf("createJournals failed: %v", err)
return 0, nil, err
}
if err := sw.allowTargetWrites(ctx); err != nil {
ts.wr.Logger().Errorf("allowTargetWrites failed: %v", err)
return 0, nil, err
}
if err := sw.changeRouting(ctx); err != nil {
ts.wr.Logger().Errorf("changeRouting failed: %v", err)
return 0, nil, err
}
if err := sw.streamMigraterfinalize(ctx, ts, sourceWorkflows); err != nil {
ts.wr.Logger().Errorf("finalize failed: %v", err)
return 0, nil, err
}
if reverseReplication {
if err := sw.startReverseVReplication(ctx); err != nil {
ts.wr.Logger().Errorf("startReverseVReplication failed: %v", err)
return 0, nil, err
}
}
if err := sw.freezeTargetVReplication(ctx); err != nil {
ts.wr.Logger().Errorf("deleteTargetVReplication failed: %v", err)
return 0, nil, err
}
return ts.id, sw.logs(), nil
}
// DropTargets cleans up target tables, shards and blacklisted tables if a MoveTables/Reshard is cancelled
func (wr *Wrangler) DropTargets(ctx context.Context, targetKeyspace, workflow string, keepData, dryRun bool) (*[]string, error) {
ts, err := wr.buildTrafficSwitcher(ctx, targetKeyspace, workflow)
if err != nil {
wr.Logger().Errorf("buildTrafficSwitcher failed: %v", err)
return nil, err
}
var sw iswitcher
if dryRun {
sw = &switcherDryRun{ts: ts, drLog: NewLogRecorder()}
} else {
sw = &switcher{ts: ts, wr: wr}
}
var tctx context.Context
tctx, sourceUnlock, lockErr := sw.lockKeyspace(ctx, ts.sourceKeyspace, "DropTargets")
if lockErr != nil {
ts.wr.Logger().Errorf("Source LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer sourceUnlock(&err)
ctx = tctx
if ts.targetKeyspace != ts.sourceKeyspace {
tctx, targetUnlock, lockErr := sw.lockKeyspace(ctx, ts.targetKeyspace, "DropTargets")
if lockErr != nil {
ts.wr.Logger().Errorf("Target LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer targetUnlock(&err)
ctx = tctx
}
if !keepData {
switch ts.migrationType {
case binlogdatapb.MigrationType_TABLES:
log.Infof("Deleting target tables")
if err := sw.removeTargetTables(ctx); err != nil {
return nil, err
}
if err := sw.dropSourceBlacklistedTables(ctx); err != nil {
return nil, err
}
case binlogdatapb.MigrationType_SHARDS:
log.Infof("Removing target shards")
if err := sw.dropTargetShards(ctx); err != nil {
return nil, err
}
}
}
if err := wr.dropArtifacts(ctx, sw); err != nil {
return nil, err
}
if err := ts.wr.ts.RebuildSrvVSchema(ctx, nil); err != nil {
return nil, err
}
return sw.logs(), nil
}
func (wr *Wrangler) dropArtifacts(ctx context.Context, sw iswitcher) error {
if err := sw.dropSourceReverseVReplicationStreams(ctx); err != nil {
return err
}
if err := sw.dropTargetVReplicationStreams(ctx); err != nil {
return err
}
if err := sw.deleteRoutingRules(ctx); err != nil {
return err
}
return nil
}
// finalizeMigrateWorkflow deletes the streams for the Migrate workflow.
// We only cleanup the target for external sources
func (wr *Wrangler) finalizeMigrateWorkflow(ctx context.Context, targetKeyspace, workflow, tableSpecs string,
cancel, keepData, dryRun bool) (*[]string, error) {
ts, err := wr.buildTrafficSwitcher(ctx, targetKeyspace, workflow)
if err != nil {
wr.Logger().Errorf("buildTrafficSwitcher failed: %v", err)
return nil, err
}
var sw iswitcher
if dryRun {
sw = &switcherDryRun{ts: ts, drLog: NewLogRecorder()}
} else {
sw = &switcher{ts: ts, wr: wr}
}
var tctx context.Context
tctx, targetUnlock, lockErr := sw.lockKeyspace(ctx, ts.targetKeyspace, "completeMigrateWorkflow")
if lockErr != nil {
ts.wr.Logger().Errorf("Target LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer targetUnlock(&err)
ctx = tctx
if err := sw.dropTargetVReplicationStreams(ctx); err != nil {
return nil, err
}
if !cancel {
sw.addParticipatingTablesToKeyspace(ctx, targetKeyspace, tableSpecs)
if err := ts.wr.ts.RebuildSrvVSchema(ctx, nil); err != nil {
return nil, err
}
}
log.Infof("cancel is %t, keepData %t", cancel, keepData)
if cancel && !keepData {
if err := sw.removeTargetTables(ctx); err != nil {
return nil, err
}
}
return sw.logs(), nil
}
// DropSources cleans up source tables, shards and blacklisted tables after a MoveTables/Reshard is completed
func (wr *Wrangler) DropSources(ctx context.Context, targetKeyspace, workflowName string, removalType workflow.TableRemovalType, keepData, force, dryRun bool) (*[]string, error) {
ts, err := wr.buildTrafficSwitcher(ctx, targetKeyspace, workflowName)
if err != nil {
wr.Logger().Errorf("buildTrafficSwitcher failed: %v", err)
return nil, err
}
var sw iswitcher
if dryRun {
sw = &switcherDryRun{ts: ts, drLog: NewLogRecorder()}
} else {
sw = &switcher{ts: ts, wr: wr}
}
var tctx context.Context
tctx, sourceUnlock, lockErr := sw.lockKeyspace(ctx, ts.sourceKeyspace, "DropSources")
if lockErr != nil {
ts.wr.Logger().Errorf("Source LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer sourceUnlock(&err)
ctx = tctx
if ts.targetKeyspace != ts.sourceKeyspace {
tctx, targetUnlock, lockErr := sw.lockKeyspace(ctx, ts.targetKeyspace, "DropSources")
if lockErr != nil {
ts.wr.Logger().Errorf("Target LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer targetUnlock(&err)
ctx = tctx
}
if !force {
if err := sw.validateWorkflowHasCompleted(ctx); err != nil {
wr.Logger().Errorf("Workflow has not completed, cannot DropSources: %v", err)
return nil, err
}
}
if !keepData {
switch ts.migrationType {
case binlogdatapb.MigrationType_TABLES:
log.Infof("Deleting tables")
if err := sw.removeSourceTables(ctx, removalType); err != nil {
return nil, err
}
if err := sw.dropSourceBlacklistedTables(ctx); err != nil {
return nil, err
}
case binlogdatapb.MigrationType_SHARDS:
log.Infof("Removing shards")
if err := sw.dropSourceShards(ctx); err != nil {
return nil, err
}
}
}
if err := wr.dropArtifacts(ctx, sw); err != nil {
return nil, err
}
if err := ts.wr.ts.RebuildSrvVSchema(ctx, nil); err != nil {
return nil, err
}
return sw.logs(), nil
}
func (wr *Wrangler) buildTrafficSwitcher(ctx context.Context, targetKeyspace, workflowName string) (*trafficSwitcher, error) {
tgtInfo, err := workflow.BuildTargets(ctx, wr.ts, wr.tmc, targetKeyspace, workflowName)
if err != nil {
log.Infof("Error building targets: %s", err)
return nil, err
}
targets, frozen, optCells, optTabletTypes := tgtInfo.Targets, tgtInfo.Frozen, tgtInfo.OptCells, tgtInfo.OptTabletTypes
ts := &trafficSwitcher{
wr: wr,
workflow: workflowName,
reverseWorkflow: workflow.ReverseWorkflowName(workflowName),
id: workflow.HashStreams(targetKeyspace, targets),
targets: targets,
sources: make(map[string]*workflow.MigrationSource),
targetKeyspace: targetKeyspace,
frozen: frozen,
optCells: optCells,
optTabletTypes: optTabletTypes,
}
log.Infof("Migration ID for workflow %s: %d", workflowName, ts.id)
sourceTopo := wr.ts
// Build the sources
for _, target := range targets {
for _, bls := range target.Sources {
if ts.sourceKeyspace == "" {
ts.sourceKeyspace = bls.Keyspace
ts.externalCluster = bls.ExternalCluster
if ts.externalCluster != "" {
externalTopo, err := wr.ts.OpenExternalVitessClusterServer(ctx, ts.externalCluster)
if err != nil {
return nil, err
}
sourceTopo = externalTopo
ts.externalTopo = externalTopo
}
} else if ts.sourceKeyspace != bls.Keyspace {
return nil, fmt.Errorf("source keyspaces are mismatched across streams: %v vs %v", ts.sourceKeyspace, bls.Keyspace)
}
if ts.tables == nil {
for _, rule := range bls.Filter.Rules {
ts.tables = append(ts.tables, rule.Match)
}
sort.Strings(ts.tables)
} else {
var tables []string
for _, rule := range bls.Filter.Rules {
tables = append(tables, rule.Match)
}
sort.Strings(tables)
if !reflect.DeepEqual(ts.tables, tables) {
return nil, fmt.Errorf("table lists are mismatched across streams: %v vs %v", ts.tables, tables)
}
}
if _, ok := ts.sources[bls.Shard]; ok {
continue
}
sourcesi, err := sourceTopo.GetShard(ctx, bls.Keyspace, bls.Shard)
if err != nil {
return nil, err
}
sourcePrimary, err := sourceTopo.GetTablet(ctx, sourcesi.MasterAlias)
if err != nil {
return nil, err
}
ts.sources[bls.Shard] = workflow.NewMigrationSource(sourcesi, sourcePrimary)
}
}
if ts.sourceKeyspace != ts.targetKeyspace || ts.externalCluster != "" {
ts.migrationType = binlogdatapb.MigrationType_TABLES
} else {
// TODO(sougou): for shard migration, validate that source and target combined
// keyranges match.
ts.migrationType = binlogdatapb.MigrationType_SHARDS
for sourceShard := range ts.sources {
if _, ok := ts.targets[sourceShard]; ok {
// If shards are overlapping, then this is a table migration.
ts.migrationType = binlogdatapb.MigrationType_TABLES
break
}
}
}
vs, err := sourceTopo.GetVSchema(ctx, ts.sourceKeyspace)
if err != nil {
return nil, err
}
ts.sourceKSSchema, err = vindexes.BuildKeyspaceSchema(vs, ts.sourceKeyspace)
if err != nil {
return nil, err
}
return ts, nil
}
func (ts *trafficSwitcher) validate(ctx context.Context) error {
if ts.migrationType == binlogdatapb.MigrationType_TABLES {
sourceTopo := ts.wr.ts
if ts.externalTopo != nil {
sourceTopo = ts.externalTopo
}
// All shards must be present.
if err := ts.compareShards(ctx, ts.sourceKeyspace, ts.sourceShards(), sourceTopo); err != nil {
return err
}
if err := ts.compareShards(ctx, ts.targetKeyspace, ts.targetShards(), ts.wr.ts); err != nil {
return err
}
// Wildcard table names not allowed.
for _, table := range ts.tables {
if strings.HasPrefix(table, "/") {
return fmt.Errorf("cannot migrate streams with wild card table names: %v", table)
}
}
}
return nil
}
func (ts *trafficSwitcher) compareShards(ctx context.Context, keyspace string, sis []*topo.ShardInfo, topo *topo.Server) error {
var shards []string
for _, si := range sis {
shards = append(shards, si.ShardName())
}
topoShards, err := topo.GetShardNames(ctx, keyspace)
if err != nil {
return err
}
sort.Strings(topoShards)
sort.Strings(shards)
if !reflect.DeepEqual(topoShards, shards) {
return fmt.Errorf("mismatched shards for keyspace %s: topo: %v vs switch command: %v", keyspace, topoShards, shards)
}
return nil
}
func (ts *trafficSwitcher) switchTableReads(ctx context.Context, cells []string, servedTypes []topodatapb.TabletType, direction workflow.TrafficSwitchDirection) error {
log.Infof("switchTableReads: servedTypes: %+v, direction %t", servedTypes, direction)
rules, err := topotools.GetRoutingRules(ctx, ts.wr.ts)
if err != nil {
return err
}
// We assume that the following rules were setup when the targets were created:
// table -> sourceKeyspace.table
// targetKeyspace.table -> sourceKeyspace.table
// For forward migration, we add tablet type specific rules to redirect traffic to the target.
// For backward, we redirect to source
for _, servedType := range servedTypes {
tt := strings.ToLower(servedType.String())
for _, table := range ts.tables {
if direction == workflow.DirectionForward {
log.Infof("Route direction forward")
toTarget := []string{ts.targetKeyspace + "." + table}
rules[table+"@"+tt] = toTarget
rules[ts.targetKeyspace+"."+table+"@"+tt] = toTarget
rules[ts.sourceKeyspace+"."+table+"@"+tt] = toTarget
} else {
log.Infof("Route direction backwards")
toSource := []string{ts.sourceKeyspace + "." + table}
rules[table+"@"+tt] = toSource
rules[ts.targetKeyspace+"."+table+"@"+tt] = toSource
rules[ts.sourceKeyspace+"."+table+"@"+tt] = toSource
}
}
}
if err := topotools.SaveRoutingRules(ctx, ts.wr.ts, rules); err != nil {
return err
}
return ts.wr.ts.RebuildSrvVSchema(ctx, cells)
}
func (ts *trafficSwitcher) switchShardReads(ctx context.Context, cells []string, servedTypes []topodatapb.TabletType, direction workflow.TrafficSwitchDirection) error {
var fromShards, toShards []*topo.ShardInfo
if direction == workflow.DirectionForward {
fromShards, toShards = ts.sourceShards(), ts.targetShards()
} else {
fromShards, toShards = ts.targetShards(), ts.sourceShards()
}
if err := ts.wr.ts.ValidateSrvKeyspace(ctx, ts.targetKeyspace, strings.Join(cells, ",")); err != nil {
err2 := vterrors.Wrapf(err, "Before switching shard reads, found SrvKeyspace for %s is corrupt in cell %s",
ts.targetKeyspace, strings.Join(cells, ","))
log.Errorf("%w", err2)
return err2
}
for _, servedType := range servedTypes {
if err := ts.wr.updateShardRecords(ctx, ts.sourceKeyspace, fromShards, cells, servedType, true /* isFrom */, false /* clearSourceShards */); err != nil {
return err
}
if err := ts.wr.updateShardRecords(ctx, ts.sourceKeyspace, toShards, cells, servedType, false, false); err != nil {
return err
}
err := ts.wr.ts.MigrateServedType(ctx, ts.sourceKeyspace, toShards, fromShards, servedType, cells)
if err != nil {
return err
}
}
if err := ts.wr.ts.ValidateSrvKeyspace(ctx, ts.targetKeyspace, strings.Join(cells, ",")); err != nil {
err2 := vterrors.Wrapf(err, "After switching shard reads, found SrvKeyspace for %s is corrupt in cell %s",
ts.targetKeyspace, strings.Join(cells, ","))
log.Errorf("%w", err2)
return err2
}
return nil
}
// checkJournals returns true if at least one journal has been created.
// If so, it also returns the list of sourceWorkflows that need to be switched.
func (ts *trafficSwitcher) checkJournals(ctx context.Context) (journalsExist bool, sourceWorkflows []string, err error) {
var (
ws = workflow.NewServer(ts.wr.ts, ts.wr.tmc)
mu sync.Mutex
)
err = ts.forAllSources(func(source *workflow.MigrationSource) error {
mu.Lock()
defer mu.Unlock()
journal, exists, err := ws.CheckReshardingJournalExistsOnTablet(ctx, source.GetPrimary().Tablet, ts.id)
if err != nil {
return err
}
if exists {
if journal.Id != 0 {
sourceWorkflows = journal.SourceWorkflows
}
source.Journaled = true
journalsExist = true
}
return nil
})
return journalsExist, sourceWorkflows, err
}
func (ts *trafficSwitcher) stopSourceWrites(ctx context.Context) error {
var err error
if ts.migrationType == binlogdatapb.MigrationType_TABLES {
err = ts.changeTableSourceWrites(ctx, disallowWrites)
} else {
err = ts.changeShardsAccess(ctx, ts.sourceKeyspace, ts.sourceShards(), disallowWrites)
}
if err != nil {
log.Warningf("Error: %s", err)
return err
}
return ts.forAllSources(func(source *workflow.MigrationSource) error {
var err error
source.Position, err = ts.wr.tmc.MasterPosition(ctx, source.GetPrimary().Tablet)
ts.wr.Logger().Infof("Stopped Source Writes. Position for source %v:%v: %v",
ts.sourceKeyspace, source.GetShard().ShardName(), source.Position)
if err != nil {
log.Warningf("Error: %s", err)