-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
keyspace.go
1433 lines (1292 loc) · 52.4 KB
/
keyspace.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 (
"bytes"
"flag"
"fmt"
"strings"
"sync"
"time"
"context"
"vitess.io/vitess/go/event"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/vt/binlog/binlogplayer"
"vitess.io/vitess/go/vt/concurrency"
"vitess.io/vitess/go/vt/discovery"
"vitess.io/vitess/go/vt/key"
binlogdatapb "vitess.io/vitess/go/vt/proto/binlogdata"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/topo/topoproto"
"vitess.io/vitess/go/vt/topotools"
"vitess.io/vitess/go/vt/topotools/events"
"vitess.io/vitess/go/vt/vterrors"
)
const (
// DefaultFilteredReplicationWaitTime is the default value for argument filteredReplicationWaitTime.
DefaultFilteredReplicationWaitTime = 30 * time.Second
)
// TODO(b/26388813): Remove these flags once vtctl WaitForDrain is integrated in the vtctl MigrateServed* commands.
var (
waitForDrainSleepRdonly = flag.Duration("wait_for_drain_sleep_rdonly", 5*time.Second, "time to wait before shutting the query service on old RDONLY tablets during MigrateServedTypes")
waitForDrainSleepReplica = flag.Duration("wait_for_drain_sleep_replica", 15*time.Second, "time to wait before shutting the query service on old REPLICA tablets during MigrateServedTypes")
)
// keyspace related methods for Wrangler
// SetKeyspaceShardingInfo locks a keyspace and sets its ShardingColumnName
// and ShardingColumnType
func (wr *Wrangler) SetKeyspaceShardingInfo(ctx context.Context, keyspace, shardingColumnName string, shardingColumnType topodatapb.KeyspaceIdType, force bool) (err error) {
// Lock the keyspace
ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "SetKeyspaceShardingInfo")
if lockErr != nil {
return lockErr
}
defer unlock(&err)
// and change it
ki, err := wr.ts.GetKeyspace(ctx, keyspace)
if err != nil {
return err
}
if ki.ShardingColumnName != "" && ki.ShardingColumnName != shardingColumnName {
if force {
wr.Logger().Warningf("Forcing keyspace ShardingColumnName change from %v to %v", ki.ShardingColumnName, shardingColumnName)
} else {
return fmt.Errorf("cannot change ShardingColumnName from %v to %v (use -force to override)", ki.ShardingColumnName, shardingColumnName)
}
}
if ki.ShardingColumnType != topodatapb.KeyspaceIdType_UNSET && ki.ShardingColumnType != shardingColumnType {
if force {
wr.Logger().Warningf("Forcing keyspace ShardingColumnType change from %v to %v", ki.ShardingColumnType, shardingColumnType)
} else {
return fmt.Errorf("cannot change ShardingColumnType from %v to %v (use -force to override)", ki.ShardingColumnType, shardingColumnType)
}
}
ki.ShardingColumnName = shardingColumnName
ki.ShardingColumnType = shardingColumnType
return wr.ts.UpdateKeyspace(ctx, ki)
}
// validateNewWorkflow ensures that the specified workflow doesn't already exist
// in the keyspace.
func (wr *Wrangler) validateNewWorkflow(ctx context.Context, keyspace, workflow string) error {
allshards, err := wr.ts.FindAllShardsInKeyspace(ctx, keyspace)
if err != nil {
return err
}
var wg sync.WaitGroup
allErrors := &concurrency.AllErrorRecorder{}
for _, si := range allshards {
if si.PrimaryAlias == nil {
allErrors.RecordError(fmt.Errorf("shard has no primary: %v", si.ShardName()))
continue
}
wg.Add(1)
go func(si *topo.ShardInfo) {
defer wg.Done()
primary, err := wr.ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
allErrors.RecordError(vterrors.Wrap(err, "validateWorkflowName.GetTablet"))
return
}
validations := []struct {
query string
msg string
}{{
fmt.Sprintf("select 1 from _vt.vreplication where db_name=%s and workflow=%s", encodeString(primary.DbName()), encodeString(workflow)),
fmt.Sprintf("workflow %s already exists in keyspace %s on tablet %d", workflow, keyspace, primary.Alias.Uid),
}, {
fmt.Sprintf("select 1 from _vt.vreplication where db_name=%s and message='FROZEN'", encodeString(primary.DbName())),
fmt.Sprintf("found previous frozen workflow on tablet %d, please review and delete it first before creating a new workflow",
primary.Alias.Uid),
}}
for _, validation := range validations {
p3qr, err := wr.tmc.VReplicationExec(ctx, primary.Tablet, validation.query)
if err != nil {
allErrors.RecordError(vterrors.Wrap(err, "validateWorkflowName.VReplicationExec"))
return
}
if p3qr != nil && len(p3qr.Rows) != 0 {
allErrors.RecordError(vterrors.Wrap(fmt.Errorf(validation.msg), "validateWorkflowName.VReplicationExec"))
return
}
}
}(si)
}
wg.Wait()
return allErrors.AggrError(vterrors.Aggregate)
}
// SplitClone initiates a SplitClone workflow.
func (wr *Wrangler) SplitClone(ctx context.Context, keyspace string, from, to []string) error {
var fromShards, toShards []*topo.ShardInfo
for _, shard := range from {
si, err := wr.ts.GetShard(ctx, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShard(%s) failed", shard)
}
fromShards = append(fromShards, si)
}
for _, shard := range to {
si, err := wr.ts.GetShard(ctx, keyspace, shard)
if err != nil {
return vterrors.Wrapf(err, "GetShard(%s) failed", shard)
}
toShards = append(toShards, si)
}
// TODO(sougou): validate from and to shards.
for _, dest := range toShards {
primary, err := wr.ts.GetTablet(ctx, dest.PrimaryAlias)
if err != nil {
return vterrors.Wrapf(err, "GetTablet(%v) failed", dest.PrimaryAlias)
}
var ids []uint64
for _, source := range fromShards {
filter := &binlogdatapb.Filter{
Rules: []*binlogdatapb.Rule{{
Match: "/.*",
Filter: key.KeyRangeString(dest.KeyRange),
}},
}
bls := &binlogdatapb.BinlogSource{
Keyspace: keyspace,
Shard: source.ShardName(),
Filter: filter,
}
cmd := binlogplayer.CreateVReplicationState("VSplitClone", bls, "", binlogplayer.BlpStopped, primary.DbName())
qr, err := wr.TabletManagerClient().VReplicationExec(ctx, primary.Tablet, cmd)
if err != nil {
return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.PrimaryAlias, cmd)
}
if err := wr.SourceShardAdd(ctx, keyspace, dest.ShardName(), uint32(qr.InsertId), keyspace, source.ShardName(), source.Shard.KeyRange, nil); err != nil {
return vterrors.Wrapf(err, "SourceShardAdd(%s, %s) failed", dest.ShardName(), source.ShardName())
}
ids = append(ids, qr.InsertId)
}
// Start vreplication only if all metadata was successfully created.
for _, id := range ids {
cmd := fmt.Sprintf("update _vt.vreplication set state='%s' where id=%d", binlogplayer.VReplicationInit, id)
if _, err = wr.TabletManagerClient().VReplicationExec(ctx, primary.Tablet, cmd); err != nil {
return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.PrimaryAlias, cmd)
}
}
}
return wr.refreshPrimaryTablets(ctx, toShards)
}
// VerticalSplitClone initiates a VerticalSplitClone workflow.
func (wr *Wrangler) VerticalSplitClone(ctx context.Context, fromKeyspace, toKeyspace string, tables []string) error {
source, err := wr.ts.GetOnlyShard(ctx, fromKeyspace)
if err != nil {
return vterrors.Wrapf(err, "GetOnlyShard(%s) failed", fromKeyspace)
}
dest, err := wr.ts.GetOnlyShard(ctx, toKeyspace)
if err != nil {
return vterrors.Wrapf(err, "GetOnlyShard(%s) failed", toKeyspace)
}
// TODO(sougou): validate from and to shards.
primary, err := wr.ts.GetTablet(ctx, dest.PrimaryAlias)
if err != nil {
return vterrors.Wrapf(err, "GetTablet(%v) failed", dest.PrimaryAlias)
}
filter := &binlogdatapb.Filter{}
for _, table := range tables {
filter.Rules = append(filter.Rules, &binlogdatapb.Rule{
Match: table,
})
}
bls := &binlogdatapb.BinlogSource{
Keyspace: fromKeyspace,
Shard: source.ShardName(),
Filter: filter,
}
cmd := binlogplayer.CreateVReplicationState("VSplitClone", bls, "", binlogplayer.BlpStopped, primary.DbName())
qr, err := wr.TabletManagerClient().VReplicationExec(ctx, primary.Tablet, cmd)
if err != nil {
return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.PrimaryAlias, cmd)
}
if err := wr.SourceShardAdd(ctx, toKeyspace, dest.ShardName(), uint32(qr.InsertId), fromKeyspace, source.ShardName(), nil, tables); err != nil {
return vterrors.Wrapf(err, "SourceShardAdd(%s, %s) failed", dest.ShardName(), source.ShardName())
}
// Start vreplication only if metadata was successfully created.
cmd = fmt.Sprintf("update _vt.vreplication set state='%s' where id=%d", binlogplayer.VReplicationInit, qr.InsertId)
if _, err = wr.TabletManagerClient().VReplicationExec(ctx, primary.Tablet, cmd); err != nil {
return vterrors.Wrapf(err, "VReplicationExec(%v, %s) failed", dest.PrimaryAlias, cmd)
}
return wr.refreshPrimaryTablets(ctx, []*topo.ShardInfo{dest})
}
// ShowResharding shows all resharding related metadata for the keyspace/shard.
func (wr *Wrangler) ShowResharding(ctx context.Context, keyspace, shard string) (err error) {
ki, err := wr.ts.GetKeyspace(ctx, keyspace)
if err != nil {
return err
}
if len(ki.ServedFroms) == 0 {
return wr.showHorizontalResharding(ctx, keyspace, shard)
}
return wr.showVerticalResharding(ctx, keyspace, shard)
}
func (wr *Wrangler) showHorizontalResharding(ctx context.Context, keyspace, shard string) error {
osList, err := topotools.FindOverlappingShards(ctx, wr.ts, keyspace)
if err != nil {
return fmt.Errorf("FindOverlappingShards failed: %v", err)
}
os := topotools.OverlappingShardsForShard(osList, shard)
if os == nil {
wr.Logger().Printf("No resharding in progress\n")
return nil
}
sourceShards, destinationShards, err := wr.findSourceDest(ctx, os)
if err != nil {
return err
}
wr.Logger().Printf("Horizontal Resharding for %v:\n", keyspace)
wr.Logger().Printf(" Sources:\n")
if err := wr.printShards(ctx, sourceShards); err != nil {
return err
}
wr.Logger().Printf(" Destinations:\n")
return wr.printShards(ctx, destinationShards)
}
func (wr *Wrangler) printShards(ctx context.Context, si []*topo.ShardInfo) error {
for _, si := range si {
wr.Logger().Printf(" Shard: %v\n", si.ShardName())
if len(si.SourceShards) != 0 {
wr.Logger().Printf(" Source Shards: %v\n", si.SourceShards)
}
ti, err := wr.ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
return err
}
qr, err := wr.tmc.VReplicationExec(ctx, ti.Tablet, fmt.Sprintf("select * from _vt.vreplication where db_name=%v", encodeString(ti.DbName())))
if err != nil {
return err
}
res := sqltypes.Proto3ToResult(qr)
if len(res.Rows) != 0 {
wr.Logger().Printf(" VReplication:\n")
for _, row := range res.Rows {
wr.Logger().Printf(" %v\n", row)
}
}
wr.Logger().Printf(" Is Primary Serving: %v\n", si.IsPrimaryServing)
if len(si.TabletControls) != 0 {
wr.Logger().Printf(" Tablet Controls: %v\n", si.TabletControls)
}
}
return nil
}
// CancelResharding cancels any resharding in progress on the specified keyspace/shard.
// This works for horizontal as well as vertical resharding.
func (wr *Wrangler) CancelResharding(ctx context.Context, keyspace, shard string) (err error) {
ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, "CancelResharding")
if lockErr != nil {
return lockErr
}
defer unlock(&err)
ki, err := wr.ts.GetKeyspace(ctx, keyspace)
if err != nil {
return err
}
if len(ki.ServedFroms) == 0 {
return wr.cancelHorizontalResharding(ctx, keyspace, shard)
}
return wr.cancelVerticalResharding(ctx, keyspace, shard)
}
func (wr *Wrangler) cancelHorizontalResharding(ctx context.Context, keyspace, shard string) error {
wr.Logger().Infof("Finding the overlapping shards in keyspace %v", keyspace)
osList, err := topotools.FindOverlappingShards(ctx, wr.ts, keyspace)
if err != nil {
return fmt.Errorf("FindOverlappingShards failed: %v", err)
}
// find our shard in there
os := topotools.OverlappingShardsForShard(osList, shard)
if os == nil {
return fmt.Errorf("shard %v is not involved in any overlapping shards", shard)
}
_, destinationShards, err := wr.findSourceDest(ctx, os)
if err != nil {
return err
}
// get srvKeyspaces in all cells to check if they are already serving this shard
srvKeyspaces, err := wr.ts.GetSrvKeyspaceAllCells(ctx, keyspace)
if err != nil {
return err
}
for _, si := range destinationShards {
for _, srvKeyspace := range srvKeyspaces {
if topo.ShardIsServing(srvKeyspace, si.Shard) {
return fmt.Errorf("some served types have migrated for %v/%v, please undo them before canceling", keyspace, shard)
}
}
}
for i, si := range destinationShards {
ti, err := wr.ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
return err
}
for _, sourceShard := range si.SourceShards {
if _, err := wr.tmc.VReplicationExec(ctx, ti.Tablet, binlogplayer.DeleteVReplication(sourceShard.Uid)); err != nil {
return err
}
}
updatedShard, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error {
si.TabletControls = nil
si.SourceShards = nil
return nil
})
if err != nil {
return err
}
destinationShards[i] = updatedShard
if err := wr.RefreshTabletsByShard(ctx, si, nil); err != nil {
return err
}
}
return nil
}
// MigrateServedTypes is used during Reshard operations to migrate a
// served type from a list of shards to another.
func (wr *Wrangler) MigrateServedTypes(ctx context.Context, keyspace, shard string, cells []string, servedType topodatapb.TabletType, reverse, skipReFreshState bool, filteredReplicationWaitTime time.Duration, reverseReplication bool) (err error) {
// check input parameters
if servedType == topodatapb.TabletType_PRIMARY {
// we cannot migrate a primary back, since when primary migration
// is done, the source shards are dead
if reverse {
return fmt.Errorf("cannot migrate primary back to %v/%v", keyspace, shard)
}
// we cannot skip refresh state for a primary
if skipReFreshState {
return fmt.Errorf("cannot skip refresh state for primary migration on %v/%v", keyspace, shard)
}
if cells != nil {
return fmt.Errorf("cannot specify cells for primary migration on %v/%v", keyspace, shard)
}
}
// lock the keyspace
ctx, unlock, lockErr := wr.ts.LockKeyspace(ctx, keyspace, fmt.Sprintf("MigrateServedTypes(%v)", servedType))
if lockErr != nil {
return lockErr
}
defer unlock(&err)
// find overlapping shards in this keyspace
wr.Logger().Infof("Finding the overlapping shards in keyspace %v", keyspace)
osList, err := topotools.FindOverlappingShards(ctx, wr.ts, keyspace)
if err != nil {
return fmt.Errorf("FindOverlappingShards failed: %v", err)
}
// find our shard in there
os := topotools.OverlappingShardsForShard(osList, shard)
if os == nil {
return fmt.Errorf("shard %v is not involved in any overlapping shards", shard)
}
sourceShards, destinationShards, err := wr.findSourceDest(ctx, os)
if err != nil {
return err
}
// execute the migration
if servedType == topodatapb.TabletType_PRIMARY {
if err = wr.masterMigrateServedType(ctx, keyspace, sourceShards, destinationShards, filteredReplicationWaitTime, reverseReplication); err != nil {
return err
}
} else {
if err = wr.replicaMigrateServedType(ctx, keyspace, sourceShards, destinationShards, cells, servedType, reverse); err != nil {
return err
}
}
// Primary migrate performs its own refresh.
// Otherwise, honor skipRefreshState if requested.
if servedType == topodatapb.TabletType_PRIMARY || skipReFreshState {
return nil
}
// refresh
// TODO(b/26388813): Integrate vtctl WaitForDrain here instead of just sleeping.
// Anything that's not a replica will use the RDONLY sleep time.
// Primary Migrate performs its own refresh but we will refresh all non primary
// tablets after each migration
waitForDrainSleep := *waitForDrainSleepRdonly
if servedType == topodatapb.TabletType_REPLICA {
waitForDrainSleep = *waitForDrainSleepReplica
}
wr.Logger().Infof("WaitForDrain: Sleeping for %.0f seconds before shutting down query service on old tablets...", waitForDrainSleep.Seconds())
time.Sleep(waitForDrainSleep)
wr.Logger().Infof("WaitForDrain: Sleeping finished. Shutting down queryservice on old tablets now.")
rec := concurrency.AllErrorRecorder{}
refreshShards := sourceShards
if reverse {
// For a backwards migration, we should refresh (disable) destination shards instead.
refreshShards = destinationShards
}
for _, si := range refreshShards {
rec.RecordError(wr.RefreshTabletsByShard(ctx, si, cells))
}
return rec.Error()
}
// findSourceDest derives the source and destination from the overlapping shards.
// Whichever side has SourceShards is a destination.
func (wr *Wrangler) findSourceDest(ctx context.Context, os *topotools.OverlappingShards) (sourceShards, destinationShards []*topo.ShardInfo, err error) {
// It's possible that both source and destination have source shards because of reversible replication.
// If so, the Frozen flag in the tablet control record dictates the direction.
// So, check that first.
for _, left := range os.Left {
tc := left.GetTabletControl(topodatapb.TabletType_PRIMARY)
if tc == nil {
continue
}
if tc.Frozen {
return os.Left, os.Right, nil
}
}
for _, right := range os.Right {
tc := right.GetTabletControl(topodatapb.TabletType_PRIMARY)
if tc == nil {
continue
}
if tc.Frozen {
return os.Right, os.Left, nil
}
}
for _, left := range os.Left {
if len(left.SourceShards) != 0 {
return os.Right, os.Left, nil
}
}
for _, right := range os.Right {
if len(right.SourceShards) != 0 {
return os.Left, os.Right, nil
}
}
return nil, nil, fmt.Errorf("neither Shard '%v' nor Shard '%v' have a 'SourceShards' entry. Did you successfully run vtworker SplitClone before? Or did you already migrate the MASTER type?", os.Left[0].ShardName(), os.Right[0].ShardName())
}
func (wr *Wrangler) getPrimaryPositions(ctx context.Context, shards []*topo.ShardInfo) (map[*topo.ShardInfo]string, error) {
mu := sync.Mutex{}
result := make(map[*topo.ShardInfo]string)
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, si := range shards {
wg.Add(1)
go func(si *topo.ShardInfo) {
defer wg.Done()
wr.Logger().Infof("Gathering primary position for %v", topoproto.TabletAliasString(si.PrimaryAlias))
ti, err := wr.ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
rec.RecordError(err)
return
}
pos, err := wr.tmc.MasterPosition(ctx, ti.Tablet)
if err != nil {
rec.RecordError(err)
return
}
wr.Logger().Infof("Got primary position for %v", topoproto.TabletAliasString(si.PrimaryAlias))
mu.Lock()
result[si] = pos
mu.Unlock()
}(si)
}
wg.Wait()
return result, rec.Error()
}
func (wr *Wrangler) waitForFilteredReplication(ctx context.Context, sourcePositions map[*topo.ShardInfo]string, destinationShards []*topo.ShardInfo, waitTime time.Duration) error {
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, si := range destinationShards {
wg.Add(1)
go func(si *topo.ShardInfo) {
defer wg.Done()
ctx, cancel := context.WithTimeout(ctx, waitTime)
defer cancel()
var pos string
for _, sourceShard := range si.SourceShards {
// find the position it should be at
for s, sp := range sourcePositions {
if s.Keyspace() == sourceShard.Keyspace && s.ShardName() == sourceShard.Shard {
pos = sp
break
}
}
// and wait for it
wr.Logger().Infof("Waiting for %v to catch up", topoproto.TabletAliasString(si.PrimaryAlias))
ti, err := wr.ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
rec.RecordError(err)
return
}
if err := wr.tmc.VReplicationWaitForPos(ctx, ti.Tablet, int(sourceShard.Uid), pos); err != nil {
if strings.Contains(err.Error(), "not found") {
wr.Logger().Infof("%v stream %d was not found. Skipping wait.", topoproto.TabletAliasString(si.PrimaryAlias), sourceShard.Uid)
} else {
rec.RecordError(err)
}
} else {
wr.Logger().Infof("%v caught up", topoproto.TabletAliasString(si.PrimaryAlias))
}
}
}(si)
}
wg.Wait()
return rec.Error()
}
// refreshPrimaryTablets will just RPC-ping all the primary tablets with RefreshState
func (wr *Wrangler) refreshPrimaryTablets(ctx context.Context, shards []*topo.ShardInfo) error {
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, si := range shards {
wg.Add(1)
go func(si *topo.ShardInfo) {
defer wg.Done()
wr.Logger().Infof("RefreshState primary %v", topoproto.TabletAliasString(si.PrimaryAlias))
ti, err := wr.ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
rec.RecordError(err)
return
}
if err := wr.tmc.RefreshState(ctx, ti.Tablet); err != nil {
rec.RecordError(err)
} else {
wr.Logger().Infof("%v responded", topoproto.TabletAliasString(si.PrimaryAlias))
}
}(si)
}
wg.Wait()
return rec.Error()
}
// replicaMigrateServedType operates with the keyspace locked
func (wr *Wrangler) replicaMigrateServedType(ctx context.Context, keyspace string, sourceShards, destinationShards []*topo.ShardInfo, cells []string, servedType topodatapb.TabletType, reverse bool) (err error) {
ev := &events.MigrateServedTypes{
KeyspaceName: keyspace,
SourceShards: sourceShards,
DestinationShards: destinationShards,
ServedType: servedType,
Reverse: reverse,
}
event.DispatchUpdate(ev, "start")
defer func() {
if err != nil {
event.DispatchUpdate(ev, "failed: "+err.Error())
}
}()
fromShards, toShards := sourceShards, destinationShards
if reverse {
fromShards, toShards = toShards, fromShards
}
// Check and update all source shard records.
// Enable query service if needed
event.DispatchUpdate(ev, "updating shards to migrate from")
if err = wr.updateShardRecords(ctx, keyspace, fromShards, cells, servedType, true /* isFrom */, false /* clearSourceShards */); err != nil {
return err
}
// Do the same for destination shards
event.DispatchUpdate(ev, "updating shards to migrate to")
if err = wr.updateShardRecords(ctx, keyspace, toShards, cells, servedType, false, false); err != nil {
return err
}
// Now update serving keyspace
if err = wr.ts.MigrateServedType(ctx, keyspace, toShards, fromShards, servedType, cells); err != nil {
return err
}
event.DispatchUpdate(ev, "finished")
return nil
}
// masterMigrateServedType operates with the keyspace locked
func (wr *Wrangler) masterMigrateServedType(ctx context.Context, keyspace string, sourceShards, destinationShards []*topo.ShardInfo, filteredReplicationWaitTime time.Duration, reverseReplication bool) (err error) {
// Ensure other served types have migrated.
srvKeyspaces, err := wr.ts.GetSrvKeyspaceAllCells(ctx, keyspace)
if err != nil {
return err
}
si := sourceShards[0]
for _, srvKeyspace := range srvKeyspaces {
var shardServedTypes []string
for _, partition := range srvKeyspace.GetPartitions() {
if partition.GetServedType() != topodatapb.TabletType_PRIMARY {
for _, shardReference := range partition.GetShardReferences() {
if key.KeyRangeEqual(shardReference.GetKeyRange(), si.GetKeyRange()) {
shardServedTypes = append(shardServedTypes, partition.GetServedType().String())
}
}
}
}
if len(shardServedTypes) > 0 {
return fmt.Errorf("cannot migrate MASTER away from %v/%v until everything else is migrated. Make sure that the following types are migrated first: %v", si.Keyspace(), si.ShardName(), strings.Join(shardServedTypes, ", "))
}
}
ev := &events.MigrateServedTypes{
KeyspaceName: keyspace,
SourceShards: sourceShards,
DestinationShards: destinationShards,
ServedType: topodatapb.TabletType_PRIMARY,
}
event.DispatchUpdate(ev, "start")
defer func() {
if err != nil {
event.DispatchUpdate(ev, "failed: "+err.Error())
}
}()
// Phase 1
// - check topology service can successfully refresh both source and target primary
// - switch the source shards to read-only by disabling query service
// - gather all replication points
// - wait for filtered replication to catch up
// - mark source shards as frozen
event.DispatchUpdate(ev, "disabling query service on all source primary tablets")
// making sure the refreshPrimaryTablets on both source and target are working before turning off query service on source
if err := wr.refreshPrimaryTablets(ctx, sourceShards); err != nil {
wr.cancelPrimaryMigrateServedTypes(ctx, keyspace, sourceShards)
return err
}
if err := wr.refreshPrimaryTablets(ctx, destinationShards); err != nil {
wr.cancelPrimaryMigrateServedTypes(ctx, keyspace, sourceShards)
return err
}
if err := wr.updateShardRecords(ctx, keyspace, sourceShards, nil, topodatapb.TabletType_PRIMARY, true, false); err != nil {
wr.cancelPrimaryMigrateServedTypes(ctx, keyspace, sourceShards)
return err
}
if err := wr.refreshPrimaryTablets(ctx, sourceShards); err != nil {
wr.cancelPrimaryMigrateServedTypes(ctx, keyspace, sourceShards)
return err
}
event.DispatchUpdate(ev, "getting positions of source primary tablets")
primaryPositions, err := wr.getPrimaryPositions(ctx, sourceShards)
if err != nil {
wr.cancelPrimaryMigrateServedTypes(ctx, keyspace, sourceShards)
return err
}
event.DispatchUpdate(ev, "waiting for destination primary tablets to catch up")
if err := wr.waitForFilteredReplication(ctx, primaryPositions, destinationShards, filteredReplicationWaitTime); err != nil {
wr.cancelPrimaryMigrateServedTypes(ctx, keyspace, sourceShards)
return err
}
// We've reached the point of no return. Freeze the tablet control records in the source primary tablets.
if err := wr.updateFrozenFlag(ctx, sourceShards, true); err != nil {
wr.cancelPrimaryMigrateServedTypes(ctx, keyspace, sourceShards)
return err
}
// Phase 2
// Always setup reverse replication. We'll start it later if reverseReplication was specified.
// This will allow someone to reverse the replication later if they change their mind.
if err := wr.setupReverseReplication(ctx, sourceShards, destinationShards); err != nil {
// It's safe to unfreeze if reverse replication setup fails.
wr.cancelPrimaryMigrateServedTypes(ctx, keyspace, sourceShards)
unfreezeErr := wr.updateFrozenFlag(ctx, sourceShards, false)
if unfreezeErr != nil {
wr.Logger().Errorf("Problem recovering for failed reverse replication: %v", unfreezeErr)
}
return err
}
// Destination shards need different handling than what updateShardRecords does.
event.DispatchUpdate(ev, "updating destination shards")
// Enable query service
err = wr.ts.UpdateDisableQueryService(ctx, keyspace, destinationShards, topodatapb.TabletType_PRIMARY, nil, false)
if err != nil {
return err
}
for i, si := range destinationShards {
ti, err := wr.ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
return err
}
// Stop VReplication streams.
for _, sourceShard := range si.SourceShards {
if _, err := wr.tmc.VReplicationExec(ctx, ti.Tablet, binlogplayer.DeleteVReplication(sourceShard.Uid)); err != nil {
return err
}
}
// Similar to updateShardRecords, but we also remove SourceShards.
destinationShards[i], err = wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error {
si.SourceShards = nil
si.IsPrimaryServing = true
return nil
})
if err != nil {
return err
}
}
event.DispatchUpdate(ev, "setting destination primary tablets read-write")
if err := wr.refreshPrimaryTablets(ctx, destinationShards); err != nil {
return err
}
// Update srvKeyspace now
if err = wr.ts.MigrateServedType(ctx, keyspace, destinationShards, sourceShards, topodatapb.TabletType_PRIMARY, nil); err != nil {
return err
}
// Make sure that from now on source shards have IsPrimaryServing set to false
for _, si := range sourceShards {
_, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error {
si.IsPrimaryServing = false
return nil
})
if err != nil {
return err
}
}
if reverseReplication {
if err := wr.startReverseReplication(ctx, sourceShards); err != nil {
return err
}
// We also have to remove the frozen flag as final step.
if err := wr.updateFrozenFlag(ctx, sourceShards, false); err != nil {
return err
}
}
for _, si := range destinationShards {
if err := wr.RefreshTabletsByShard(ctx, si, nil); err != nil {
return err
}
}
event.DispatchUpdate(ev, "finished")
return nil
}
func (wr *Wrangler) cancelPrimaryMigrateServedTypes(ctx context.Context, keyspace string, sourceShards []*topo.ShardInfo) {
wr.Logger().Infof("source shards cancelPrimaryMigrateServedTypes: %v", sourceShards)
if err := wr.updateShardRecords(ctx, keyspace, sourceShards, nil, topodatapb.TabletType_PRIMARY, false, true); err != nil {
wr.Logger().Errorf2(err, "failed to re-enable source primary tablets")
return
}
if err := wr.refreshPrimaryTablets(ctx, sourceShards); err != nil {
wr.Logger().Errorf2(err, "failed to refresh source primary tablets")
}
}
func (wr *Wrangler) setupReverseReplication(ctx context.Context, sourceShards, destinationShards []*topo.ShardInfo) error {
// Retrieve primary positions of all destinations.
primaryPositions := make([]string, len(destinationShards))
for i, dest := range destinationShards {
ti, err := wr.ts.GetTablet(ctx, dest.PrimaryAlias)
if err != nil {
return err
}
wr.Logger().Infof("Gathering primary position for %v", topoproto.TabletAliasString(dest.PrimaryAlias))
primaryPositions[i], err = wr.tmc.MasterPosition(ctx, ti.Tablet)
if err != nil {
return err
}
}
// Create reverse replication for each source.
for i, sourceShard := range sourceShards {
ti, err := wr.ts.GetTablet(ctx, sourceShard.PrimaryAlias)
if err != nil {
return err
}
dbName := ti.DbName()
if len(sourceShard.SourceShards) != 0 {
continue
}
// Handle the case where the source is "unsharded".
kr := sourceShard.KeyRange
if kr == nil {
kr = &topodatapb.KeyRange{}
}
// Create replications streams first using the retrieved primary positions.
uids := make([]uint32, len(destinationShards))
for j, dest := range destinationShards {
bls := &binlogdatapb.BinlogSource{
Keyspace: dest.Keyspace(),
Shard: dest.ShardName(),
KeyRange: kr,
}
qr, err := wr.VReplicationExec(ctx, sourceShard.PrimaryAlias, binlogplayer.CreateVReplicationState("ReversedResharding", bls, primaryPositions[j], binlogplayer.BlpStopped, dbName))
if err != nil {
return err
}
uids[j] = uint32(qr.InsertId)
wr.Logger().Infof("Created reverse replication for tablet %v/%v: %v, db: %v, pos: %v, uid: %v", sourceShard.Keyspace(), sourceShard.ShardName(), bls, dbName, primaryPositions[j], uids[j])
}
// Source shards have to be atomically added to ensure idempotence.
// If this fails, there's no harm because the unstarted vreplication streams will just be abandoned.
sourceShards[i], err = wr.ts.UpdateShardFields(ctx, sourceShard.Keyspace(), sourceShard.ShardName(), func(si *topo.ShardInfo) error {
for j, dest := range destinationShards {
si.SourceShards = append(si.SourceShards, &topodatapb.Shard_SourceShard{
Uid: uids[j],
Keyspace: dest.Keyspace(),
Shard: dest.ShardName(),
KeyRange: dest.KeyRange,
})
}
return nil
})
if err != nil {
wr.Logger().Errorf("Unstarted vreplication streams for %v/%v need to be deleted: %v", sourceShard.Keyspace(), sourceShard.ShardName(), uids)
return fmt.Errorf("failed to setup reverse replication: %v, unstarted vreplication streams for %v/%v need to be deleted: %v", err, sourceShard.Keyspace(), sourceShard.ShardName(), uids)
}
}
return nil
}
func (wr *Wrangler) startReverseReplication(ctx context.Context, sourceShards []*topo.ShardInfo) error {
for _, sourceShard := range sourceShards {
for _, dest := range sourceShard.SourceShards {
wr.Logger().Infof("Starting reverse replication for tablet %v/%v, uid: %v", sourceShard.Keyspace(), sourceShard.ShardName(), dest.Uid)
_, err := wr.VReplicationExec(ctx, sourceShard.PrimaryAlias, binlogplayer.StartVReplication(dest.Uid))
if err != nil {
return err
}
}
}
return nil
}
// updateShardRecords updates the shard records based on 'from' or 'to' direction.
func (wr *Wrangler) updateShardRecords(ctx context.Context, keyspace string, shards []*topo.ShardInfo, cells []string, servedType topodatapb.TabletType, isFrom bool, clearSourceShards bool) (err error) {
return topotools.UpdateShardRecords(ctx, wr.ts, wr.tmc, keyspace, shards, cells, servedType, isFrom, clearSourceShards, wr.Logger())
}
// updateFrozenFlag sets or unsets the Frozen flag for primary migration. This is performed
// for all primary tablet control records.
func (wr *Wrangler) updateFrozenFlag(ctx context.Context, shards []*topo.ShardInfo, value bool) (err error) {
for i, si := range shards {
updatedShard, err := wr.ts.UpdateShardFields(ctx, si.Keyspace(), si.ShardName(), func(si *topo.ShardInfo) error {
tc := si.GetTabletControl(topodatapb.TabletType_PRIMARY)
if tc != nil {
tc.Frozen = value
return nil
}
// This shard does not have a tablet control record, adding one to set frozen flag
tc = &topodatapb.Shard_TabletControl{
TabletType: topodatapb.TabletType_PRIMARY,
Frozen: value,
}
si.TabletControls = append(si.TabletControls, tc)
return nil
})
if err != nil {
return err
}
shards[i] = updatedShard
}
return nil
}
// WaitForDrain blocks until the selected tablets (cells/keyspace/shard/tablet_type)
// have reported a QPS rate of 0.0.
// NOTE: This is just an observation of one point in time and no guarantee that
// the tablet was actually drained. At later times, a QPS rate > 0.0 could still
// be observed.
func (wr *Wrangler) WaitForDrain(ctx context.Context, cells []string, keyspace, shard string, servedType topodatapb.TabletType,
retryDelay, healthCheckTopologyRefresh, healthcheckRetryDelay, healthCheckTimeout, initialWait time.Duration) error {
var err error
if len(cells) == 0 {
// Retrieve list of cells for the shard from the topology.
cells, err = wr.ts.GetCellInfoNames(ctx)
if err != nil {
return fmt.Errorf("failed to retrieve list of all cells. GetCellInfoNames() failed: %v", err)
}
}
// Check all cells in parallel.
wg := sync.WaitGroup{}
rec := concurrency.AllErrorRecorder{}
for _, cell := range cells {
wg.Add(1)
go func(cell string) {
defer wg.Done()
rec.RecordError(wr.waitForDrainInCell(ctx, cell, keyspace, shard, servedType,
retryDelay, healthCheckTopologyRefresh, healthcheckRetryDelay, healthCheckTimeout, initialWait))
}(cell)
}
wg.Wait()
return rec.Error()
}
func (wr *Wrangler) waitForDrainInCell(ctx context.Context, cell, keyspace, shard string, servedType topodatapb.TabletType,
retryDelay, healthCheckTopologyRefresh, healthcheckRetryDelay, healthCheckTimeout, initialWait time.Duration) error {
// Create the healthheck module, with a cache.
hc := discovery.NewLegacyHealthCheck(healthcheckRetryDelay, healthCheckTimeout)
defer hc.Close()
tsc := discovery.NewLegacyTabletStatsCache(hc, wr.TopoServer(), cell)
// Create a tablet watcher.
watcher := discovery.NewLegacyShardReplicationWatcher(ctx, wr.TopoServer(), hc, cell, keyspace, shard, healthCheckTopologyRefresh, discovery.DefaultTopoReadConcurrency)
defer watcher.Stop()
// Wait for at least one tablet.
if err := tsc.WaitForTablets(ctx, keyspace, shard, servedType); err != nil {
return fmt.Errorf("%v: error waiting for initial %v tablets for %v/%v: %v", cell, servedType, keyspace, shard, err)
}
wr.Logger().Infof("%v: Waiting for %.1f seconds to make sure that the discovery module retrieves healthcheck information from all tablets.",