-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathmaterializer.go
1701 lines (1572 loc) · 57.1 KB
/
materializer.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"
"fmt"
"hash/fnv"
"math"
"sort"
"strings"
"sync"
"text/template"
"time"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/proto"
"vitess.io/vitess/go/json2"
"vitess.io/vitess/go/sqlescape"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/vt/concurrency"
"vitess.io/vitess/go/vt/discovery"
"vitess.io/vitess/go/vt/key"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/mysqlctl/tmutils"
"vitess.io/vitess/go/vt/schema"
"vitess.io/vitess/go/vt/schemadiff"
"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/schematools"
"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"
binlogdatapb "vitess.io/vitess/go/vt/proto/binlogdata"
querypb "vitess.io/vitess/go/vt/proto/query"
tabletmanagerdatapb "vitess.io/vitess/go/vt/proto/tabletmanagerdata"
vschemapb "vitess.io/vitess/go/vt/proto/vschema"
vtctldatapb "vitess.io/vitess/go/vt/proto/vtctldata"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
type materializer struct {
wr *Wrangler
ms *vtctldatapb.MaterializeSettings
targetVSchema *vindexes.KeyspaceSchema
sourceShards []*topo.ShardInfo
targetShards []*topo.ShardInfo
isPartial bool
primaryVindexesDiffer bool
}
const (
createDDLAsCopy = "copy"
createDDLAsCopyDropConstraint = "copy:drop_constraint"
createDDLAsCopyDropForeignKeys = "copy:drop_foreign_keys"
)
// addTablesToVSchema adds tables to an (unsharded) vschema if they are not already defined.
// If copyVSchema is true then we copy over the vschema table definitions from the source,
// otherwise we create empty ones.
// For a migrate workflow we do not copy the vschema since the source keyspace is just a
// proxy to import data into Vitess.
func (wr *Wrangler) addTablesToVSchema(ctx context.Context, sourceKeyspace string, targetVSchema *vschemapb.Keyspace, tables []string, copyVSchema bool) error {
if targetVSchema.Tables == nil {
targetVSchema.Tables = make(map[string]*vschemapb.Table)
}
if copyVSchema {
srcVSchema, err := wr.ts.GetVSchema(ctx, sourceKeyspace)
if err != nil {
return vterrors.Wrapf(err, "failed to get vschema for source keyspace %s", sourceKeyspace)
}
for _, table := range tables {
srcTable, sok := srcVSchema.Tables[table]
if _, tok := targetVSchema.Tables[table]; sok && !tok {
targetVSchema.Tables[table] = srcTable
// If going from sharded to unsharded, then we need to remove the
// column vindexes as they are not valid for unsharded tables.
if srcVSchema.Sharded {
targetVSchema.Tables[table].ColumnVindexes = nil
}
}
}
}
// Ensure that each table at least has an empty definition on the target.
for _, table := range tables {
if _, tok := targetVSchema.Tables[table]; !tok {
targetVSchema.Tables[table] = &vschemapb.Table{}
}
}
return nil
}
func shouldInclude(table string, excludes []string) bool {
// We filter out internal tables elsewhere when processing SchemaDefinition
// structures built from the GetSchema database related API calls. In this
// case, however, the table list comes from the user via the -tables flag
// so we need to filter out internal table names here in case a user has
// explicitly specified some.
// This could happen if there's some automated tooling that creates the list of
// tables to explicitly specify.
// But given that this should never be done in practice, we ignore the request.
if schema.IsInternalOperationTableName(table) {
return false
}
for _, t := range excludes {
if t == table {
return false
}
}
return true
}
// MoveTables initiates moving table(s) over to another keyspace
func (wr *Wrangler) MoveTables(ctx context.Context, workflow, sourceKeyspace, targetKeyspace, tableSpecs,
cell, tabletTypesStr string, allTables bool, excludeTables string, autoStart, stopAfterCopy bool,
externalCluster string, dropForeignKeys, deferSecondaryKeys bool, sourceTimeZone, onDDL string,
sourceShards []string, noRoutingRules bool, atomicCopy bool) (err error) {
//FIXME validate tableSpecs, allTables, excludeTables
var tables []string
var externalTopo *topo.Server
if externalCluster != "" { // when the source is an external mysql cluster mounted using the Mount command
externalTopo, err = wr.ts.OpenExternalVitessClusterServer(ctx, externalCluster)
if err != nil {
return err
}
wr.sourceTs = externalTopo
log.Infof("Successfully opened external topo: %+v", externalTopo)
}
var vschema *vschemapb.Keyspace
var origVSchema *vschemapb.Keyspace // If we need to rollback a failed create
vschema, err = wr.ts.GetVSchema(ctx, targetKeyspace)
if err != nil {
return err
}
if vschema == nil {
return fmt.Errorf("no vschema found for target keyspace %s", targetKeyspace)
}
if strings.HasPrefix(tableSpecs, "{") {
if vschema.Tables == nil {
vschema.Tables = make(map[string]*vschemapb.Table)
}
wrap := fmt.Sprintf(`{"tables": %s}`, tableSpecs)
ks := &vschemapb.Keyspace{}
if err := json2.Unmarshal([]byte(wrap), ks); err != nil {
return err
}
for table, vtab := range ks.Tables {
vschema.Tables[table] = vtab
tables = append(tables, table)
}
} else {
if len(strings.TrimSpace(tableSpecs)) > 0 {
tables = strings.Split(tableSpecs, ",")
}
ksTables, err := wr.getKeyspaceTables(ctx, sourceKeyspace, wr.sourceTs)
if err != nil {
return err
}
if len(tables) > 0 {
err = wr.validateSourceTablesExist(sourceKeyspace, ksTables, tables)
if err != nil {
return err
}
} else {
if allTables {
tables = ksTables
} else {
return fmt.Errorf("no tables to move")
}
}
var excludeTablesList []string
excludeTables = strings.TrimSpace(excludeTables)
if excludeTables != "" {
excludeTablesList = strings.Split(excludeTables, ",")
err = wr.validateSourceTablesExist(sourceKeyspace, ksTables, excludeTablesList)
if err != nil {
return err
}
}
var tables2 []string
for _, t := range tables {
if shouldInclude(t, excludeTablesList) {
tables2 = append(tables2, t)
}
}
tables = tables2
if len(tables) == 0 {
return fmt.Errorf("no tables to move")
}
log.Infof("Found tables to move: %s", strings.Join(tables, ","))
if !vschema.Sharded {
// Save the original in case we need to restore it for a late failure
// in the defer().
origVSchema = vschema.CloneVT()
if err := wr.addTablesToVSchema(ctx, sourceKeyspace, vschema, tables, externalTopo == nil); err != nil {
return err
}
}
}
tabletTypes, inorder, err := discovery.ParseTabletTypesAndOrder(tabletTypesStr)
if err != nil {
return err
}
tsp := tabletmanagerdatapb.TabletSelectionPreference_ANY
if inorder {
tsp = tabletmanagerdatapb.TabletSelectionPreference_INORDER
}
ms := &vtctldatapb.MaterializeSettings{
Workflow: workflow,
MaterializationIntent: vtctldatapb.MaterializationIntent_MOVETABLES,
SourceKeyspace: sourceKeyspace,
TargetKeyspace: targetKeyspace,
Cell: cell,
TabletTypes: topoproto.MakeStringTypeCSV(tabletTypes),
TabletSelectionPreference: tsp,
StopAfterCopy: stopAfterCopy,
ExternalCluster: externalCluster,
SourceShards: sourceShards,
OnDdl: onDDL,
DeferSecondaryKeys: deferSecondaryKeys,
AtomicCopy: atomicCopy,
}
if sourceTimeZone != "" {
ms.SourceTimeZone = sourceTimeZone
ms.TargetTimeZone = "UTC"
}
createDDLMode := createDDLAsCopy
if dropForeignKeys {
createDDLMode = createDDLAsCopyDropForeignKeys
}
for _, table := range tables {
buf := sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("select * from %v", sqlparser.NewIdentifierCS(table))
ms.TableSettings = append(ms.TableSettings, &vtctldatapb.TableMaterializeSettings{
TargetTable: table,
SourceExpression: buf.String(),
CreateDdl: createDDLMode,
})
}
mz, err := wr.prepareMaterializerStreams(ctx, ms)
if err != nil {
return err
}
// If we get an error after this point, where the vreplication streams/records
// have been created, then we clean up the workflow's artifacts.
defer func() {
if err != nil {
ts, cerr := wr.buildTrafficSwitcher(ctx, ms.TargetKeyspace, ms.Workflow)
if cerr != nil {
err = vterrors.Wrapf(err, "failed to cleanup workflow artifacts: %v", cerr)
}
if cerr := wr.dropArtifacts(ctx, false, &switcher{ts: ts, wr: wr}); cerr != nil {
err = vterrors.Wrapf(err, "failed to cleanup workflow artifacts: %v", cerr)
}
if origVSchema == nil { // There's no previous version to restore
return
}
if cerr := wr.ts.SaveVSchema(ctx, targetKeyspace, origVSchema); cerr != nil {
err = vterrors.Wrapf(err, "failed to restore original target vschema: %v", cerr)
}
}
}()
// Now that the streams have been successfully created, let's put the associated
// routing rules in place.
if externalTopo == nil {
if noRoutingRules {
log.Warningf("Found --no-routing-rules flag, not creating routing rules for workflow %s.%s", targetKeyspace, workflow)
} else {
// Save routing rules before vschema. If we save vschema first, and routing rules
// fails to save, we may generate duplicate table errors.
if mz.isPartial {
if err := wr.createDefaultShardRoutingRules(ctx, ms); err != nil {
return err
}
}
rules, err := topotools.GetRoutingRules(ctx, wr.ts)
if err != nil {
return err
}
for _, table := range tables {
toSource := []string{sourceKeyspace + "." + table}
rules[table] = toSource
rules[table+"@replica"] = toSource
rules[table+"@rdonly"] = toSource
rules[targetKeyspace+"."+table] = toSource
rules[targetKeyspace+"."+table+"@replica"] = toSource
rules[targetKeyspace+"."+table+"@rdonly"] = toSource
rules[targetKeyspace+"."+table] = toSource
rules[sourceKeyspace+"."+table+"@replica"] = toSource
rules[sourceKeyspace+"."+table+"@rdonly"] = toSource
}
if err := topotools.SaveRoutingRules(ctx, wr.ts, rules); err != nil {
return err
}
}
// We added to the vschema.
if err := wr.ts.SaveVSchema(ctx, targetKeyspace, vschema); err != nil {
return err
}
}
if err := wr.ts.RebuildSrvVSchema(ctx, nil); err != nil {
return err
}
if sourceTimeZone != "" {
if err := mz.checkTZConversion(ctx, sourceTimeZone); err != nil {
return err
}
}
tabletShards, err := wr.collectTargetStreams(ctx, mz)
if err != nil {
return err
}
migrationID, err := getMigrationID(targetKeyspace, tabletShards)
if err != nil {
return err
}
if externalCluster == "" {
exists, tablets, err := wr.checkIfPreviousJournalExists(ctx, mz, migrationID)
if err != nil {
return err
}
if exists {
wr.Logger().Errorf("Found a previous journal entry for %d", migrationID)
msg := fmt.Sprintf("found an entry from a previous run for migration id %d in _vt.resharding_journal of tablets %s,",
migrationID, strings.Join(tablets, ","))
msg += fmt.Sprintf("please review and delete it before proceeding and restart the workflow using the Workflow %s.%s start",
workflow, targetKeyspace)
return fmt.Errorf(msg)
}
}
if autoStart {
return mz.startStreams(ctx)
}
wr.Logger().Infof("Streams will not be started since --auto_start is set to false")
return nil
}
func (wr *Wrangler) validateSourceTablesExist(sourceKeyspace string, ksTables, tables []string) error {
// validate that tables provided are present in the source keyspace
var missingTables []string
for _, table := range tables {
if schema.IsInternalOperationTableName(table) {
continue
}
found := false
for _, ksTable := range ksTables {
if table == ksTable {
found = true
break
}
}
if !found {
missingTables = append(missingTables, table)
}
}
if len(missingTables) > 0 {
return fmt.Errorf("table(s) not found in source keyspace %s: %s", sourceKeyspace, strings.Join(missingTables, ","))
}
return nil
}
func (wr *Wrangler) getKeyspaceTables(ctx context.Context, ks string, ts *topo.Server) ([]string, error) {
shards, err := ts.GetServingShards(ctx, ks)
if err != nil {
return nil, err
}
if len(shards) == 0 {
return nil, fmt.Errorf("keyspace %s has no shards", ks)
}
primary := shards[0].PrimaryAlias
if primary == nil {
return nil, fmt.Errorf("shard does not have a primary: %v", shards[0].ShardName())
}
allTables := []string{"/.*/"}
ti, err := ts.GetTablet(ctx, primary)
if err != nil {
return nil, err
}
req := &tabletmanagerdatapb.GetSchemaRequest{Tables: allTables}
schema, err := wr.tmc.GetSchema(ctx, ti.Tablet, req)
if err != nil {
return nil, err
}
log.Infof("got table schemas from source primary %v.", primary)
var sourceTables []string
for _, td := range schema.TableDefinitions {
sourceTables = append(sourceTables, td.Name)
}
return sourceTables, nil
}
func (wr *Wrangler) checkIfPreviousJournalExists(ctx context.Context, mz *materializer, migrationID int64) (bool, []string, error) {
forAllSources := func(f func(*topo.ShardInfo) error) error {
var wg sync.WaitGroup
allErrors := &concurrency.AllErrorRecorder{}
for _, sourceShard := range mz.sourceShards {
wg.Add(1)
go func(sourceShard *topo.ShardInfo) {
defer wg.Done()
if err := f(sourceShard); err != nil {
allErrors.RecordError(err)
}
}(sourceShard)
}
wg.Wait()
return allErrors.AggrError(vterrors.Aggregate)
}
var (
mu sync.Mutex
exists bool
tablets []string
ws = workflow.NewServer(wr.env, wr.ts, wr.tmc)
)
err := forAllSources(func(si *topo.ShardInfo) error {
tablet, err := wr.ts.GetTablet(ctx, si.PrimaryAlias)
if err != nil {
return err
}
if tablet == nil {
return nil
}
_, exists, err = ws.CheckReshardingJournalExistsOnTablet(ctx, tablet.Tablet, migrationID)
if err != nil {
return err
}
if exists {
mu.Lock()
defer mu.Unlock()
tablets = append(tablets, tablet.AliasString())
}
return nil
})
return exists, tablets, err
}
// CreateLookupVindex creates a lookup vindex and sets up the backfill.
func (wr *Wrangler) CreateLookupVindex(ctx context.Context, keyspace string, specs *vschemapb.Keyspace, cell, tabletTypesStr string, continueAfterCopyWithOwner bool) error {
ms, sourceVSchema, targetVSchema, err := wr.prepareCreateLookup(ctx, keyspace, specs, continueAfterCopyWithOwner)
if err != nil {
return err
}
if err := wr.ts.SaveVSchema(ctx, ms.TargetKeyspace, targetVSchema); err != nil {
return err
}
ms.Cell = cell
tabletTypes, inorder, err := discovery.ParseTabletTypesAndOrder(tabletTypesStr)
if err != nil {
return err
}
tsp := tabletmanagerdatapb.TabletSelectionPreference_ANY
if inorder {
tsp = tabletmanagerdatapb.TabletSelectionPreference_INORDER
}
ms.TabletTypes = topoproto.MakeStringTypeCSV(tabletTypes)
ms.TabletSelectionPreference = tsp
if err := wr.Materialize(ctx, ms); err != nil {
return err
}
if err := wr.ts.SaveVSchema(ctx, keyspace, sourceVSchema); err != nil {
return err
}
return wr.ts.RebuildSrvVSchema(ctx, nil)
}
// prepareCreateLookup performs the preparatory steps for creating a lookup vindex.
func (wr *Wrangler) prepareCreateLookup(ctx context.Context, keyspace string, specs *vschemapb.Keyspace, continueAfterCopyWithOwner bool) (ms *vtctldatapb.MaterializeSettings, sourceVSchema, targetVSchema *vschemapb.Keyspace, err error) {
// Important variables are pulled out here.
var (
// lookup vindex info
vindexName string
vindex *vschemapb.Vindex
targetKeyspace string
targetTableName string
vindexFromCols []string
vindexToCol string
vindexIgnoreNulls bool
// source table info
sourceTableName string
// sourceTable is the supplied table info
sourceTable *vschemapb.Table
// sourceVSchemaTable is the table info present in the vschema
sourceVSchemaTable *vschemapb.Table
// sourceVindexColumns are computed from the input sourceTable
sourceVindexColumns []string
// target table info
createDDL string
materializeQuery string
)
// Validate input vindex
if len(specs.Vindexes) != 1 {
return nil, nil, nil, fmt.Errorf("only one vindex must be specified in the specs: %v", specs.Vindexes)
}
for name, vi := range specs.Vindexes {
vindexName = name
vindex = vi
}
if !strings.Contains(vindex.Type, "lookup") {
return nil, nil, nil, fmt.Errorf("vindex %s is not a lookup type", vindex.Type)
}
targetKeyspace, targetTableName, err = wr.env.Parser().ParseTable(vindex.Params["table"])
if err != nil || targetKeyspace == "" {
return nil, nil, nil, fmt.Errorf("vindex table name must be in the form <keyspace>.<table>. Got: %v", vindex.Params["table"])
}
vindexFromCols = strings.Split(vindex.Params["from"], ",")
if strings.Contains(vindex.Type, "unique") {
if len(vindexFromCols) != 1 {
return nil, nil, nil, fmt.Errorf("unique vindex 'from' should have only one column: %v", vindex)
}
} else {
if len(vindexFromCols) < 2 {
return nil, nil, nil, fmt.Errorf("non-unique vindex 'from' should have more than one column: %v", vindex)
}
}
vindexToCol = vindex.Params["to"]
// Make the vindex write_only. If one exists already in the vschema,
// it will need to match this vindex exactly, including the write_only setting.
vindex.Params["write_only"] = "true"
// See if we can create the vindex without errors.
if _, err := vindexes.CreateVindex(vindex.Type, vindexName, vindex.Params); err != nil {
return nil, nil, nil, err
}
if ignoreNullsStr, ok := vindex.Params["ignore_nulls"]; ok {
// This mirrors the behavior of vindexes.boolFromMap().
switch ignoreNullsStr {
case "true":
vindexIgnoreNulls = true
case "false":
vindexIgnoreNulls = false
default:
return nil, nil, nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "ignore_nulls value must be 'true' or 'false': '%s'",
ignoreNullsStr)
}
}
// Validate input table
if len(specs.Tables) != 1 {
return nil, nil, nil, fmt.Errorf("exactly one table must be specified in the specs: %v", specs.Tables)
}
// Loop executes once.
for k, ti := range specs.Tables {
if len(ti.ColumnVindexes) != 1 {
return nil, nil, nil, fmt.Errorf("exactly one ColumnVindex must be specified for the table: %v", specs.Tables)
}
sourceTableName = k
sourceTable = ti
}
// Validate input table and vindex consistency
if sourceTable.ColumnVindexes[0].Name != vindexName {
return nil, nil, nil, fmt.Errorf("ColumnVindex name must match vindex name: %s vs %s", sourceTable.ColumnVindexes[0].Name, vindexName)
}
if vindex.Owner != "" && vindex.Owner != sourceTableName {
return nil, nil, nil, fmt.Errorf("vindex owner must match table name: %v vs %v", vindex.Owner, sourceTableName)
}
if len(sourceTable.ColumnVindexes[0].Columns) != 0 {
sourceVindexColumns = sourceTable.ColumnVindexes[0].Columns
} else {
if sourceTable.ColumnVindexes[0].Column == "" {
return nil, nil, nil, fmt.Errorf("at least one column must be specified in ColumnVindexes: %v", sourceTable.ColumnVindexes)
}
sourceVindexColumns = []string{sourceTable.ColumnVindexes[0].Column}
}
if len(sourceVindexColumns) != len(vindexFromCols) {
return nil, nil, nil, fmt.Errorf("length of table columns differes from length of vindex columns: %v vs %v", sourceVindexColumns, vindexFromCols)
}
// Validate against source vschema
sourceVSchema, err = wr.ts.GetVSchema(ctx, keyspace)
if err != nil {
return nil, nil, nil, err
}
if sourceVSchema.Vindexes == nil {
sourceVSchema.Vindexes = make(map[string]*vschemapb.Vindex)
}
// If source and target keyspaces are same, Make vschemas point to the same object.
if keyspace == targetKeyspace {
targetVSchema = sourceVSchema
} else {
targetVSchema, err = wr.ts.GetVSchema(ctx, targetKeyspace)
if err != nil {
return nil, nil, nil, err
}
}
if targetVSchema.Vindexes == nil {
targetVSchema.Vindexes = make(map[string]*vschemapb.Vindex)
}
if targetVSchema.Tables == nil {
targetVSchema.Tables = make(map[string]*vschemapb.Table)
}
if existing, ok := sourceVSchema.Vindexes[vindexName]; ok {
if !proto.Equal(existing, vindex) {
return nil, nil, nil, fmt.Errorf("a conflicting vindex named %s already exists in the source vschema", vindexName)
}
}
sourceVSchemaTable = sourceVSchema.Tables[sourceTableName]
if sourceVSchemaTable == nil {
if !schema.IsInternalOperationTableName(sourceTableName) {
return nil, nil, nil, fmt.Errorf("source table %s not found in vschema", sourceTableName)
}
}
for _, colVindex := range sourceVSchemaTable.ColumnVindexes {
// For a conflict, the vindex name and column should match.
if colVindex.Name != vindexName {
continue
}
colName := colVindex.Column
if len(colVindex.Columns) != 0 {
colName = colVindex.Columns[0]
}
if colName == sourceVindexColumns[0] {
return nil, nil, nil, fmt.Errorf("ColumnVindex for table %v already exists: %v, please remove it and try again", sourceTableName, colName)
}
}
// Validate against source schema
sourceShards, err := wr.ts.GetServingShards(ctx, keyspace)
if err != nil {
return nil, nil, nil, err
}
onesource := sourceShards[0]
if onesource.PrimaryAlias == nil {
return nil, nil, nil, fmt.Errorf("source shard has no primary: %v", onesource.ShardName())
}
req := &tabletmanagerdatapb.GetSchemaRequest{Tables: []string{sourceTableName}}
tableSchema, err := schematools.GetSchema(ctx, wr.ts, wr.tmc, onesource.PrimaryAlias, req)
if err != nil {
return nil, nil, nil, err
}
if len(tableSchema.TableDefinitions) != 1 {
return nil, nil, nil, fmt.Errorf("unexpected number of tables returned from schema: %v", tableSchema.TableDefinitions)
}
// Generate "create table" statement
lines := strings.Split(tableSchema.TableDefinitions[0].Schema, "\n")
if len(lines) < 3 {
// Unreachable
return nil, nil, nil, fmt.Errorf("schema looks incorrect: %s, expecting at least four lines", tableSchema.TableDefinitions[0].Schema)
}
var modified []string
modified = append(modified, strings.Replace(lines[0], sourceTableName, targetTableName, 1))
for i := range sourceVindexColumns {
line, err := generateColDef(lines, sourceVindexColumns[i], vindexFromCols[i])
if err != nil {
return nil, nil, nil, err
}
modified = append(modified, line)
}
if vindex.Params["data_type"] == "" || strings.EqualFold(vindex.Type, "consistent_lookup_unique") || strings.EqualFold(vindex.Type, "consistent_lookup") {
modified = append(modified, fmt.Sprintf(" %s varbinary(128),", sqlescape.EscapeID(vindexToCol)))
} else {
modified = append(modified, fmt.Sprintf(" %s %s,", sqlescape.EscapeID(vindexToCol), sqlescape.EscapeID(vindex.Params["data_type"])))
}
buf := sqlparser.NewTrackedBuffer(nil)
fmt.Fprintf(buf, " PRIMARY KEY (")
prefix := ""
for _, col := range vindexFromCols {
fmt.Fprintf(buf, "%s%s", prefix, sqlescape.EscapeID(col))
prefix = ", "
}
fmt.Fprintf(buf, ")")
modified = append(modified, buf.String())
modified = append(modified, ")")
createDDL = strings.Join(modified, "\n")
// Generate vreplication query
buf = sqlparser.NewTrackedBuffer(nil)
buf.Myprintf("select ")
for i := range vindexFromCols {
buf.Myprintf("%s as %s, ", sqlparser.String(sqlparser.NewIdentifierCI(sourceVindexColumns[i])), sqlparser.String(sqlparser.NewIdentifierCI(vindexFromCols[i])))
}
if strings.EqualFold(vindexToCol, "keyspace_id") || strings.EqualFold(vindex.Type, "consistent_lookup_unique") || strings.EqualFold(vindex.Type, "consistent_lookup") {
buf.Myprintf("keyspace_id() as %s ", sqlparser.String(sqlparser.NewIdentifierCI(vindexToCol)))
} else {
buf.Myprintf("%s as %s ", sqlparser.String(sqlparser.NewIdentifierCI(vindexToCol)), sqlparser.String(sqlparser.NewIdentifierCI(vindexToCol)))
}
buf.Myprintf("from %s", sqlparser.String(sqlparser.NewIdentifierCS(sourceTableName)))
if vindexIgnoreNulls {
buf.Myprintf(" where ")
lastValIdx := len(vindexFromCols) - 1
for i := range vindexFromCols {
buf.Myprintf("%s is not null", sqlparser.String(sqlparser.NewIdentifierCI(vindexFromCols[i])))
if i != lastValIdx {
buf.Myprintf(" and ")
}
}
}
if vindex.Owner != "" {
// Only backfill
buf.Myprintf(" group by ")
for i := range vindexFromCols {
buf.Myprintf("%s, ", sqlparser.String(sqlparser.NewIdentifierCI(vindexFromCols[i])))
}
buf.Myprintf("%s", sqlparser.String(sqlparser.NewIdentifierCI(vindexToCol)))
}
materializeQuery = buf.String()
// Update targetVSchema
var targetTable *vschemapb.Table
if targetVSchema.Sharded {
// Choose a primary vindex type for target table based on source specs
var targetVindexType string
var targetVindex *vschemapb.Vindex
for _, field := range tableSchema.TableDefinitions[0].Fields {
if sourceVindexColumns[0] == field.Name {
targetVindexType, err = vindexes.ChooseVindexForType(field.Type)
if err != nil {
return nil, nil, nil, err
}
targetVindex = &vschemapb.Vindex{
Type: targetVindexType,
}
break
}
}
if targetVindex == nil {
// Unreachable. We validated column names when generating the DDL.
return nil, nil, nil, fmt.Errorf("column %s not found in schema %v", sourceVindexColumns[0], tableSchema.TableDefinitions[0])
}
if existing, ok := targetVSchema.Vindexes[targetVindexType]; ok {
if !proto.Equal(existing, targetVindex) {
return nil, nil, nil, fmt.Errorf("a conflicting vindex named %v already exists in the target vschema", targetVindexType)
}
} else {
targetVSchema.Vindexes[targetVindexType] = targetVindex
}
targetTable = &vschemapb.Table{
ColumnVindexes: []*vschemapb.ColumnVindex{{
Column: vindexFromCols[0],
Name: targetVindexType,
}},
}
} else {
targetTable = &vschemapb.Table{}
}
if existing, ok := targetVSchema.Tables[targetTableName]; ok {
if !proto.Equal(existing, targetTable) {
return nil, nil, nil, fmt.Errorf("a conflicting table named %v already exists in the target vschema", targetTableName)
}
} else {
targetVSchema.Tables[targetTableName] = targetTable
}
ms = &vtctldatapb.MaterializeSettings{
Workflow: targetTableName + "_vdx",
MaterializationIntent: vtctldatapb.MaterializationIntent_CREATELOOKUPINDEX,
SourceKeyspace: keyspace,
TargetKeyspace: targetKeyspace,
StopAfterCopy: vindex.Owner != "" && !continueAfterCopyWithOwner,
TableSettings: []*vtctldatapb.TableMaterializeSettings{{
TargetTable: targetTableName,
SourceExpression: materializeQuery,
CreateDdl: createDDL,
}},
}
// Update sourceVSchema
sourceVSchema.Vindexes[vindexName] = vindex
sourceVSchemaTable.ColumnVindexes = append(sourceVSchemaTable.ColumnVindexes, sourceTable.ColumnVindexes[0])
return ms, sourceVSchema, targetVSchema, nil
}
func generateColDef(lines []string, sourceVindexCol, vindexFromCol string) (string, error) {
source := sqlescape.EscapeID(sourceVindexCol)
target := sqlescape.EscapeID(vindexFromCol)
for _, line := range lines[1:] {
if strings.Contains(line, source) {
line = strings.Replace(line, source, target, 1)
line = strings.Replace(line, " AUTO_INCREMENT", "", 1)
line = strings.Replace(line, " DEFAULT NULL", "", 1)
return line, nil
}
}
return "", fmt.Errorf("column %s not found in schema %v", sourceVindexCol, lines)
}
// ExternalizeVindex externalizes a lookup vindex that's finished backfilling or has caught up.
func (wr *Wrangler) ExternalizeVindex(ctx context.Context, qualifiedVindexName string) error {
splits := strings.Split(qualifiedVindexName, ".")
if len(splits) != 2 {
return fmt.Errorf("vindex name should be of the form keyspace.vindex: %s", qualifiedVindexName)
}
sourceKeyspace, vindexName := splits[0], splits[1]
sourceVSchema, err := wr.ts.GetVSchema(ctx, sourceKeyspace)
if err != nil {
return err
}
sourceVindex := sourceVSchema.Vindexes[vindexName]
if sourceVindex == nil {
return fmt.Errorf("vindex %s not found in vschema", qualifiedVindexName)
}
targetKeyspace, targetTableName, err := wr.env.Parser().ParseTable(sourceVindex.Params["table"])
if err != nil || targetKeyspace == "" {
return fmt.Errorf("vindex table name must be in the form <keyspace>.<table>. Got: %v", sourceVindex.Params["table"])
}
workflow := targetTableName + "_vdx"
targetShards, err := wr.ts.GetServingShards(ctx, targetKeyspace)
if err != nil {
return err
}
// Create a parallelizer function.
forAllTargets := func(f func(*topo.ShardInfo) error) error {
var wg sync.WaitGroup
allErrors := &concurrency.AllErrorRecorder{}
for _, targetShard := range targetShards {
wg.Add(1)
go func(targetShard *topo.ShardInfo) {
defer wg.Done()
if err := f(targetShard); err != nil {
allErrors.RecordError(err)
}
}(targetShard)
}
wg.Wait()
return allErrors.AggrError(vterrors.Aggregate)
}
err = forAllTargets(func(targetShard *topo.ShardInfo) error {
targetPrimary, err := wr.ts.GetTablet(ctx, targetShard.PrimaryAlias)
if err != nil {
return err
}
p3qr, err := wr.tmc.VReplicationExec(ctx, targetPrimary.Tablet, fmt.Sprintf("select id, state, message, source from _vt.vreplication where workflow=%s and db_name=%s", encodeString(workflow), encodeString(targetPrimary.DbName())))
if err != nil {
return err
}
qr := sqltypes.Proto3ToResult(p3qr)
for _, row := range qr.Rows {
id, err := row[0].ToCastInt64()
if err != nil {
return err
}
state := binlogdatapb.VReplicationWorkflowState(binlogdatapb.VReplicationWorkflowState_value[row[1].ToString()])
message := row[2].ToString()
var bls binlogdatapb.BinlogSource
sourceBytes, err := row[3].ToBytes()
if err != nil {
return err
}
if err := prototext.Unmarshal(sourceBytes, &bls); err != nil {
return err
}
if sourceVindex.Owner == "" || !bls.StopAfterCopy {
// If there's no owner or we've requested that the workflow NOT be stopped
// after the copy phase completes, then all streams need to be running.
if state != binlogdatapb.VReplicationWorkflowState_Running {
return fmt.Errorf("stream %d for %v.%v is not in Running state: %v", id, targetShard.Keyspace(), targetShard.ShardName(), state)
}
} else {
// If there is an owner, all streams need to be stopped after copy.
if state != binlogdatapb.VReplicationWorkflowState_Stopped || !strings.Contains(message, "Stopped after copy") {
return fmt.Errorf("stream %d for %v.%v is not in Stopped after copy state: %v, %v", id, targetShard.Keyspace(), targetShard.ShardName(), state, message)
}
}
}
return nil
})
if err != nil {
return err
}
if sourceVindex.Owner != "" {
// If there is an owner, we have to delete the streams.
err := forAllTargets(func(targetShard *topo.ShardInfo) error {
targetPrimary, err := wr.ts.GetTablet(ctx, targetShard.PrimaryAlias)
if err != nil {
return err
}
query := fmt.Sprintf("delete from _vt.vreplication where db_name=%s and workflow=%s", encodeString(targetPrimary.DbName()), encodeString(workflow))
_, err = wr.tmc.VReplicationExec(ctx, targetPrimary.Tablet, query)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
}
// Remove the write_only param and save the source vschema.
delete(sourceVindex.Params, "write_only")
if err := wr.ts.SaveVSchema(ctx, sourceKeyspace, sourceVSchema); err != nil {
return err
}
return wr.ts.RebuildSrvVSchema(ctx, nil)
}
func (wr *Wrangler) collectTargetStreams(ctx context.Context, mz *materializer) ([]string, error) {
var shardTablets []string
var mu sync.Mutex
err := mz.forAllTargets(func(target *topo.ShardInfo) error {
var qrproto *querypb.QueryResult
var id int64
var err error
targetPrimary, err := mz.wr.ts.GetTablet(ctx, target.PrimaryAlias)
if err != nil {
return vterrors.Wrapf(err, "GetTablet(%v) failed", target.PrimaryAlias)
}
query := fmt.Sprintf("select id from _vt.vreplication where db_name=%s and workflow=%s", encodeString(targetPrimary.DbName()), encodeString(mz.ms.Workflow))
if qrproto, err = mz.wr.tmc.VReplicationExec(ctx, targetPrimary.Tablet, query); err != nil {
return vterrors.Wrapf(err, "VReplicationExec(%v, %s)", targetPrimary.Tablet, query)
}
qr := sqltypes.Proto3ToResult(qrproto)
for i := 0; i < len(qr.Rows); i++ {
id, err = qr.Rows[i][0].ToCastInt64()
if err != nil {
return err
}
mu.Lock()
shardTablets = append(shardTablets, fmt.Sprintf("%s:%d", target.ShardName(), id))
mu.Unlock()
}
return nil
})
if err != nil {
return nil, err
}
return shardTablets, nil
}
// getMigrationID produces a reproducible hash based on the input parameters.
func getMigrationID(targetKeyspace string, shardTablets []string) (int64, error) {
sort.Strings(shardTablets)
hasher := fnv.New64()
hasher.Write([]byte(targetKeyspace))
for _, str := range shardTablets {
hasher.Write([]byte(str))
}
// Convert to int64 after dropping the highest bit.
return int64(hasher.Sum64() & math.MaxInt64), nil
}
// createDefaultShardRoutingRules creates a reverse routing rule for
// each shard in a new partial keyspace migration workflow that does
// not already have an existing routing rule in place.
func (wr *Wrangler) createDefaultShardRoutingRules(ctx context.Context, ms *vtctldatapb.MaterializeSettings) error {
srr, err := topotools.GetShardRoutingRules(ctx, wr.ts)
if err != nil {
return err
}
allShards, err := wr.sourceTs.GetServingShards(ctx, ms.SourceKeyspace)
if err != nil {
return err
}
changed := false
for _, si := range allShards {
fromSource := fmt.Sprintf("%s.%s", ms.SourceKeyspace, si.ShardName())
fromTarget := fmt.Sprintf("%s.%s", ms.TargetKeyspace, si.ShardName())
if srr[fromSource] == "" && srr[fromTarget] == "" {