-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathtraffic_switcher.go
1925 lines (1770 loc) · 70.2 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/sqlescape"
"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/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"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
const (
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
sqlDeleteWorkflow = "delete from _vt.vreplication where db_name = %s and workflow = %s"
)
// accessType specifies the type of access for a shard (allow/disallow writes).
type accessType int
const (
allowWrites = accessType(iota)
disallowWrites
// number of LOCK TABLES cycles to perform on the sources during SwitchWrites
lockTablesCycles = 2
// time to wait between LOCK TABLES cycles on the sources during SwitchWrites
lockTablesCycleDelay = time.Duration(100 * time.Millisecond)
// How long to wait when refreshing the state of each tablet in a shard. Note that these
// are refreshed in parallel, non-topo errors are ignored (in the error handling) and we
// may only do a partial refresh. Because in some cases it's unsafe to switch the traffic
// if some tablets do not refresh, we may need to look for partial results and produce
// an error (with the provided details of WHY) if we see them.
// Side note: the default lock/lease TTL in etcd is 60s so the default tablet refresh
// timeout of 60s can cause us to lose our keyspace lock before completing the
// operation too.
shardTabletRefreshTimeout = time.Duration(30 * time.Second)
)
// trafficSwitcher contains the metadata for switching read and write traffic
// for vreplication streams.
type trafficSwitcher struct {
migrationType binlogdatapb.MigrationType
isPartialMigration bool
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
keepRoutingRules bool
sourceKSSchema *vindexes.KeyspaceSchema
optCells string //cells option passed to MoveTables/Reshard
optTabletTypes string //tabletTypes option passed to MoveTables/Reshard
externalCluster string
externalTopo *topo.Server
sourceTimeZone string
targetTimeZone string
workflowType binlogdatapb.VReplicationWorkflowType
workflowSubType binlogdatapb.VReplicationWorkflowSubType
}
/*
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) ExternalTopo() *topo.Server { return ts.externalTopo }
func (ts *trafficSwitcher) MigrationType() binlogdatapb.MigrationType { return ts.migrationType }
func (ts *trafficSwitcher) IsPartialMigration() bool { return ts.isPartialMigration }
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) Sources() map[string]*workflow.MigrationSource { return ts.sources }
func (ts *trafficSwitcher) Tables() []string { return ts.tables }
func (ts *trafficSwitcher) TargetKeyspaceName() string { return ts.targetKeyspace }
func (ts *trafficSwitcher) Targets() map[string]*workflow.MigrationTarget { return ts.targets }
func (ts *trafficSwitcher) WorkflowName() string { return ts.workflow }
func (ts *trafficSwitcher) SourceTimeZone() string { return ts.sourceTimeZone }
func (ts *trafficSwitcher) TargetTimeZone() string { return ts.targetTimeZone }
func (ts *trafficSwitcher) ForAllSources(f func(source *workflow.MigrationSource) error) error {
var wg sync.WaitGroup
allErrors := &concurrency.AllErrorRecorder{}
for _, source := range ts.sources {
wg.Add(1)
go func(source *workflow.MigrationSource) {
defer wg.Done()
if err := f(source); err != nil {
allErrors.RecordError(err)
}
}(source)
}
wg.Wait()
return allErrors.AggrError(vterrors.Aggregate)
}
func (ts *trafficSwitcher) ForAllTargets(f func(source *workflow.MigrationTarget) error) error {
var wg sync.WaitGroup
allErrors := &concurrency.AllErrorRecorder{}
for _, target := range ts.targets {
wg.Add(1)
go func(target *workflow.MigrationTarget) {
defer wg.Done()
if err := f(target); err != nil {
allErrors.RecordError(err)
}
}(target)
}
wg.Wait()
return allErrors.AggrError(vterrors.Aggregate)
}
func (ts *trafficSwitcher) ForAllUIDs(f func(target *workflow.MigrationTarget, uid int32) error) error {
var wg sync.WaitGroup
allErrors := &concurrency.AllErrorRecorder{}
for _, target := range ts.Targets() {
for uid := range target.Sources {
wg.Add(1)
go func(target *workflow.MigrationTarget, uid int32) {
defer wg.Done()
if err := f(target, uid); err != nil {
allErrors.RecordError(err)
}
}(target, uid)
}
}
wg.Wait()
return allErrors.AggrError(vterrors.Aggregate)
}
/* end: implementation of workflow.ITrafficSwitcher */
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.NewServer(wr.ts, wr.tmc)
state := &workflow.State{
Workflow: workflowName,
SourceKeyspace: ts.SourceKeyspaceName(),
TargetKeyspace: targetKeyspace,
IsPartialMigration: ts.isPartialMigration,
}
var (
reverse bool
keyspace string
)
// 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 = state.SourceKeyspace
workflowName = workflow.ReverseWorkflowName(workflowName)
} else {
keyspace = targetKeyspace
}
if ts.MigrationType() == binlogdatapb.MigrationType_TABLES {
state.WorkflowType = workflow.TypeMoveTables
// We assume a consistent state, so only choose routing rule for one table.
if len(ts.Tables()) == 0 {
return nil, nil, fmt.Errorf("no tables in workflow %s.%s", keyspace, workflowName)
}
table := ts.Tables()[0]
if ts.isPartialMigration { // shard level traffic switching is all or nothing
shardRoutingRules, err := wr.ts.GetShardRoutingRules(ctx)
if err != nil {
return nil, nil, err
}
rules := shardRoutingRules.Rules
for _, rule := range rules {
if rule.ToKeyspace == ts.SourceKeyspaceName() {
state.ShardsNotYetSwitched = append(state.ShardsNotYetSwitched, rule.Shard)
} else {
state.ShardsAlreadySwitched = append(state.ShardsAlreadySwitched, rule.Shard)
}
}
} else {
state.RdonlyCellsSwitched, state.RdonlyCellsNotSwitched, err = ws.GetCellsWithTableReadsSwitched(ctx, keyspace, table, topodatapb.TabletType_RDONLY)
if err != nil {
return nil, nil, err
}
state.ReplicaCellsSwitched, state.ReplicaCellsNotSwitched, err = ws.GetCellsWithTableReadsSwitched(ctx, keyspace, table, topodatapb.TabletType_REPLICA)
if err != nil {
return nil, nil, err
}
globalRules, err := topotools.GetRoutingRules(ctx, ts.TopoServer())
if err != nil {
return nil, nil, err
}
for _, table := range ts.Tables() {
rr := globalRules[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) {
state.WritesSwitched = true
break
}
}
}
} else {
state.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]
}
state.RdonlyCellsSwitched, state.RdonlyCellsNotSwitched, err = ws.GetCellsWithShardReadsSwitched(ctx, keyspace, shard, topodatapb.TabletType_RDONLY)
if err != nil {
return nil, nil, err
}
state.ReplicaCellsSwitched, state.ReplicaCellsNotSwitched, err = ws.GetCellsWithShardReadsSwitched(ctx, keyspace, shard, topodatapb.TabletType_REPLICA)
if err != nil {
return nil, nil, err
}
if !shard.IsPrimaryServing {
state.WritesSwitched = true
}
}
return ts, state, 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("Switching reads: %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 read traffic 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 := topotools.DoCellsHaveRdonlyTablets(ctx, wr.ts, 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.Logger().Errorf("validate failed: %v", err)
return nil, err
}
// For reads, locking the source keyspace is sufficient.
ctx, unlock, lockErr := sw.lockKeyspace(ctx, ts.SourceKeyspaceName(), "SwitchReads")
if lockErr != nil {
ts.Logger().Errorf("LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer unlock(&err)
if ts.MigrationType() == binlogdatapb.MigrationType_TABLES {
if ts.isPartialMigration {
ts.Logger().Infof("Partial migration, skipping switchTableReads as traffic is all or nothing per shard and overridden for reads AND writes in the ShardRoutingRule created when switching writes.")
} else if err := sw.switchTableReads(ctx, cells, servedTypes, direction); err != nil {
ts.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 := sw.switchShardReads(ctx, cells, servedTypes, direction); err != nil {
ts.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 = "PRIMARY,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.PrimaryAlias.Cell)
}
tp, err := discovery.NewTabletPicker(ctx, wr.ts, cells, shard.PrimaryAlias.Cell, keyspace, shard.ShardName(), tabletTypes, discovery.TabletPickerOptions{})
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.Logger().Warningf("Writes have already been switched for workflow %s, nothing to do here", ts.WorkflowName())
return 0, sw.logs(), nil
}
ts.Logger().Infof("Built switching metadata: %+v", ts)
if err := ts.validate(ctx); err != nil {
ts.Logger().Errorf("validate failed: %v", err)
return 0, nil, err
}
if reverseReplication {
err := wr.areTabletsAvailableToStreamFrom(ctx, ts, ts.TargetKeyspaceName(), ts.TargetShards())
if err != nil {
return 0, nil, err
}
}
// Need to lock both source and target keyspaces.
tctx, sourceUnlock, lockErr := sw.lockKeyspace(ctx, ts.SourceKeyspaceName(), "SwitchWrites")
if lockErr != nil {
ts.Logger().Errorf("LockKeyspace failed: %v", lockErr)
return 0, nil, lockErr
}
ctx = tctx
defer sourceUnlock(&err)
if ts.TargetKeyspaceName() != ts.SourceKeyspaceName() {
tctx, targetUnlock, lockErr := sw.lockKeyspace(ctx, ts.TargetKeyspaceName(), "SwitchWrites")
if lockErr != nil {
ts.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.Logger().Errorf("checkJournals failed: %v", err)
return 0, nil, err
}
if !journalsExist {
ts.Logger().Infof("No previous journals were found. Proceeding normally.")
sm, err := workflow.BuildStreamMigrator(ctx, ts, cancel)
if err != nil {
ts.Logger().Errorf("buildStreamMigrater failed: %v", err)
return 0, nil, err
}
if cancel {
sw.cancelMigration(ctx, sm)
return 0, sw.logs(), nil
}
ts.Logger().Infof("Stopping streams")
sourceWorkflows, err = sw.stopStreams(ctx, sm)
if err != nil {
ts.Logger().Errorf("stopStreams failed: %v", err)
for key, streams := range sm.Streams() {
for _, stream := range streams {
ts.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.Logger().Infof("Stopping source writes")
if err := sw.stopSourceWrites(ctx); err != nil {
ts.Logger().Errorf("stopSourceWrites failed: %v", err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
if ts.MigrationType() == binlogdatapb.MigrationType_TABLES {
ts.Logger().Infof("Executing LOCK TABLES on source tables %d times", lockTablesCycles)
// Doing this twice with a pause in-between to catch any writes that may have raced in between
// the tablet's deny list check and the first mysqld side table lock.
for cnt := 1; cnt <= lockTablesCycles; cnt++ {
if err := ts.executeLockTablesOnSource(ctx); err != nil {
ts.Logger().Errorf("Failed to execute LOCK TABLES (attempt %d of %d) on sources: %v", cnt, lockTablesCycles, err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
// No need to UNLOCK the tables as the connection was closed once the locks were acquired
// and thus the locks released.
time.Sleep(lockTablesCycleDelay)
}
}
ts.Logger().Infof("Waiting for streams to catchup")
if err := sw.waitForCatchup(ctx, timeout); err != nil {
ts.Logger().Errorf("waitForCatchup failed: %v", err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
ts.Logger().Infof("Migrating streams")
if err := sw.migrateStreams(ctx, sm); err != nil {
ts.Logger().Errorf("migrateStreams failed: %v", err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
ts.Logger().Infof("Resetting sequences")
if err := sw.resetSequences(ctx); err != nil {
ts.Logger().Errorf("resetSequences failed: %v", err)
sw.cancelMigration(ctx, sm)
return 0, nil, err
}
ts.Logger().Infof("Creating reverse streams")
if err := sw.createReverseVReplication(ctx); err != nil {
ts.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.Logger().Errorf("%v", err)
return 0, nil, err
}
ts.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.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.Logger().Errorf("createJournals failed: %v", err)
return 0, nil, err
}
if err := sw.allowTargetWrites(ctx); err != nil {
ts.Logger().Errorf("allowTargetWrites failed: %v", err)
return 0, nil, err
}
if err := sw.changeRouting(ctx); err != nil {
ts.Logger().Errorf("changeRouting failed: %v", err)
return 0, nil, err
}
if err := sw.streamMigraterfinalize(ctx, ts, sourceWorkflows); err != nil {
ts.Logger().Errorf("finalize failed: %v", err)
return 0, nil, err
}
if reverseReplication {
if err := sw.startReverseVReplication(ctx); err != nil {
ts.Logger().Errorf("startReverseVReplication failed: %v", err)
return 0, nil, err
}
}
if err := sw.freezeTargetVReplication(ctx); err != nil {
ts.Logger().Errorf("deleteTargetVReplication failed: %v", err)
return 0, nil, err
}
return ts.id, sw.logs(), nil
}
// DropTargets cleans up target tables, shards and denied tables if a MoveTables/Reshard is cancelled
func (wr *Wrangler) DropTargets(ctx context.Context, targetKeyspace, workflow string, keepData, keepRoutingRules, dryRun bool) (*[]string, error) {
ts, err := wr.buildTrafficSwitcher(ctx, targetKeyspace, workflow)
if err != nil {
wr.Logger().Errorf("buildTrafficSwitcher failed: %v", err)
return nil, err
}
ts.keepRoutingRules = keepRoutingRules
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.SourceKeyspaceName(), "DropTargets")
if lockErr != nil {
ts.Logger().Errorf("Source LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer sourceUnlock(&err)
ctx = tctx
if ts.TargetKeyspaceName() != ts.SourceKeyspaceName() {
tctx, targetUnlock, lockErr := sw.lockKeyspace(ctx, ts.TargetKeyspaceName(), "DropTargets")
if lockErr != nil {
ts.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.dropSourceDeniedTables(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, keepRoutingRules, sw); err != nil {
return nil, err
}
if err := ts.TopoServer().RebuildSrvVSchema(ctx, nil); err != nil {
return nil, err
}
return sw.logs(), nil
}
func (wr *Wrangler) dropArtifacts(ctx context.Context, keepRoutingRules bool, sw iswitcher) error {
if err := sw.dropSourceReverseVReplicationStreams(ctx); err != nil {
return err
}
if err := sw.dropTargetVReplicationStreams(ctx); err != nil {
return err
}
if !keepRoutingRules {
if err := sw.deleteRoutingRules(ctx); err != nil {
return err
}
if err := sw.deleteShardRoutingRules(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, keepRoutingRules, 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.TargetKeyspaceName(), "completeMigrateWorkflow")
if lockErr != nil {
ts.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.TopoServer().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 denied tables after a MoveTables/Reshard is completed
func (wr *Wrangler) DropSources(ctx context.Context, targetKeyspace, workflowName string, removalType workflow.TableRemovalType, keepData, keepRoutingRules, 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.SourceKeyspaceName(), "DropSources")
if lockErr != nil {
ts.Logger().Errorf("Source LockKeyspace failed: %v", lockErr)
return nil, lockErr
}
defer sourceUnlock(&err)
ctx = tctx
if ts.TargetKeyspaceName() != ts.SourceKeyspaceName() {
tctx, targetUnlock, lockErr := sw.lockKeyspace(ctx, ts.TargetKeyspaceName(), "DropSources")
if lockErr != nil {
ts.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.dropSourceDeniedTables(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, keepRoutingRules, sw); err != nil {
return nil, err
}
if err := ts.TopoServer().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,
workflowType: tgtInfo.WorkflowType,
workflowSubType: tgtInfo.WorkflowSubType,
}
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.sourceTimeZone = bls.SourceTimeZone
ts.targetTimeZone = bls.TargetTimeZone
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.PrimaryAlias)
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
}
sourceShards, targetShards := ts.getSourceAndTargetShardsNames()
ts.isPartialMigration, err = ts.isPartialMoveTables(sourceShards, targetShards)
if err != nil {
return nil, err
}
if ts.isPartialMigration {
log.Infof("Migration is partial, for shards %+v", sourceShards)
}
return ts, nil
}
func (ts *trafficSwitcher) getSourceAndTargetShardsNames() ([]string, []string) {
var sourceShards, targetShards []string
for _, si := range ts.SourceShards() {
sourceShards = append(sourceShards, si.ShardName())
}
for _, si := range ts.TargetShards() {
targetShards = append(targetShards, si.ShardName())
}
return sourceShards, targetShards
}
// isPartialMoveTables returns true if whe workflow is MoveTables,
// has the same number of shards, is not covering the entire shard range, and has one-to-one shards in source and target
func (ts *trafficSwitcher) isPartialMoveTables(sourceShards, targetShards []string) (bool, error) {
if ts.MigrationType() != binlogdatapb.MigrationType_TABLES {
return false, nil
}
skr, tkr, err := getSourceAndTargetKeyRanges(sourceShards, targetShards)
if err != nil {
return false, err
}
if key.KeyRangeIsComplete(skr) || key.KeyRangeIsComplete(tkr) || len(sourceShards) != len(targetShards) {
return false, nil
}
return key.KeyRangeEqual(skr, tkr), nil
}
func getSourceAndTargetKeyRanges(sourceShards, targetShards []string) (*topodatapb.KeyRange, *topodatapb.KeyRange, error) {
if len(sourceShards) == 0 || len(targetShards) == 0 {
return nil, nil, fmt.Errorf("either source or target shards are missing")
}
getKeyRange := func(shard string) (*topodatapb.KeyRange, error) {
krs, err := key.ParseShardingSpec(shard)
if err != nil {
return nil, err
}
return krs[0], nil
}
// happily string sorting of shards also sorts them in the ascending order of key ranges in vitess
sort.Strings(sourceShards)
sort.Strings(targetShards)
getFullKeyRange := func(shards []string) (*topodatapb.KeyRange, error) {
// expect sorted shards
kr1, err := getKeyRange(sourceShards[0])
if err != nil {
return nil, err
}
kr2, err := getKeyRange(sourceShards[len(sourceShards)-1])
if err != nil {
return nil, err
}
return &topodatapb.KeyRange{
Start: kr1.Start,
End: kr2.End,
}, nil
}
skr, err := getFullKeyRange(sourceShards)
if err != nil {
return nil, nil, err