-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathonlineddl_scheduler_test.go
More file actions
3864 lines (3571 loc) · 181 KB
/
onlineddl_scheduler_test.go
File metadata and controls
3864 lines (3571 loc) · 181 KB
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 2021 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 scheduler
import (
"context"
"flag"
"fmt"
"math/rand/v2"
"os"
"path"
"strconv"
"strings"
"sync"
"testing"
"time"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/mysql/capabilities"
"vitess.io/vitess/go/textutil"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/schema"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vttablet/tabletserver/throttle/throttlerapp"
"vitess.io/vitess/go/test/endtoend/cluster"
"vitess.io/vitess/go/test/endtoend/onlineddl"
"vitess.io/vitess/go/test/endtoend/throttler"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
anyErrorIndicator = "<any-error-of-any-kind>"
// Migration metric names as exposed via /debug/vars
metricStartedMigrations = "StartedMigrations"
metricSuccessfulMigrations = "SuccessfulMigrations"
metricFailedMigrations = "FailedMigrations"
)
type testOnlineDDLStatementParams struct {
ddlStatement string
ddlStrategy string
executeStrategy string
expectHint string
expectError string
skipWait bool
migrationContext string
}
type testRevertMigrationParams struct {
revertUUID string
executeStrategy string
ddlStrategy string
migrationContext string
expectError string
skipWait bool
}
var (
clusterInstance *cluster.LocalProcessCluster
primaryTablet *cluster.Vttablet
shards []cluster.Shard
vtParams mysql.ConnParams
normalWaitTime = 20 * time.Second
extendedWaitTime = 60 * time.Second
ensureStateNotChangedTime = 5 * time.Second
hostname = "localhost"
keyspaceName = "ks"
cell = "zone1"
schemaChangeDirectory = ""
overrideVtctlParams *cluster.ApplySchemaParams
)
type WriteMetrics struct {
mu sync.Mutex
insertsAttempts, insertsFailures, insertsNoops, inserts int64
updatesAttempts, updatesFailures, updatesNoops, updates int64
deletesAttempts, deletesFailures, deletesNoops, deletes int64
}
func (w *WriteMetrics) Clear() {
w.mu.Lock()
defer w.mu.Unlock()
w.inserts = 0
w.updates = 0
w.deletes = 0
w.insertsAttempts = 0
w.insertsFailures = 0
w.insertsNoops = 0
w.updatesAttempts = 0
w.updatesFailures = 0
w.updatesNoops = 0
w.deletesAttempts = 0
w.deletesFailures = 0
w.deletesNoops = 0
}
func (w *WriteMetrics) String() string {
return fmt.Sprintf(`WriteMetrics: inserts-deletes=%d, updates-deletes=%d,
insertsAttempts=%d, insertsFailures=%d, insertsNoops=%d, inserts=%d,
updatesAttempts=%d, updatesFailures=%d, updatesNoops=%d, updates=%d,
deletesAttempts=%d, deletesFailures=%d, deletesNoops=%d, deletes=%d,
`,
w.inserts-w.deletes, w.updates-w.deletes,
w.insertsAttempts, w.insertsFailures, w.insertsNoops, w.inserts,
w.updatesAttempts, w.updatesFailures, w.updatesNoops, w.updates,
w.deletesAttempts, w.deletesFailures, w.deletesNoops, w.deletes,
)
}
func parseTableName(t *testing.T, sql string) (tableName string) {
// ddlStatement could possibly be composed of multiple DDL statements
parser := sqlparser.NewTestParser()
stmts, err := parser.ParseMultiple(sql)
require.NoError(t, err)
for _, stmt := range stmts {
ddlStmt, ok := stmt.(sqlparser.DDLStatement)
require.True(t, ok)
tableName = ddlStmt.GetTable().Name.String()
if tableName == "" {
tbls := ddlStmt.AffectedTables()
require.NotEmpty(t, tbls)
tableName = tbls[0].Name.String()
}
require.NotEmptyf(t, tableName, "could not parse table name from SQL: %s", sqlparser.String(ddlStmt))
}
require.NotEmptyf(t, tableName, "could not parse table name from SQL: %s", sql)
return tableName
}
// testOnlineDDLStatement runs an online DDL, ALTER statement
func TestParseTableName(t *testing.T) {
sqls := []string{
`ALTER TABLE t1_test ENGINE=InnoDB`,
`ALTER TABLE t1_test ENGINE=InnoDB;`,
`DROP TABLE IF EXISTS t1_test`,
`
ALTER TABLE stress_test ENGINE=InnoDB;
ALTER TABLE stress_test ENGINE=InnoDB;
ALTER TABLE stress_test ENGINE=InnoDB;
`,
}
for _, sql := range sqls {
t.Run(sql, func(t *testing.T) {
parseTableName(t, sql)
})
}
}
func waitForReadyToComplete(t *testing.T, uuid string, expected bool) {
ctx, cancel := context.WithTimeout(t.Context(), normalWaitTime)
defer cancel()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
rs := onlineddl.ReadMigrations(t, &vtParams, uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
readyToComplete := row.AsInt64("ready_to_complete", 0)
if expected == (readyToComplete > 0) {
// all good. This is what we waited for
if expected {
// if migration is ready to complete, the nthe timestamp should be non-null
assert.False(t, row["ready_to_complete_timestamp"].IsNull())
} else {
assert.True(t, row["ready_to_complete_timestamp"].IsNull())
}
return
}
}
select {
case <-ticker.C:
case <-ctx.Done():
}
require.NoError(t, ctx.Err(), "waiting for ready_to_complete=%t for %v", expected, uuid)
}
}
func waitForMessage(t *testing.T, uuid string, messageSubstring string) {
ctx, cancel := context.WithTimeout(t.Context(), normalWaitTime)
defer cancel()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var lastMessage string
for {
rs := onlineddl.ReadMigrations(t, &vtParams, uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
lastMessage = row.AsString("message", "")
if strings.Contains(lastMessage, messageSubstring) {
return
}
}
select {
case <-ticker.C:
case <-ctx.Done():
{
resp, err := throttler.CheckThrottler(&clusterInstance.VtctldClientProcess, primaryTablet, throttlerapp.TestingName, nil)
assert.NoError(t, err)
fmt.Println("Throttler check response: ", resp)
output, err := throttler.GetThrottlerStatusRaw(&clusterInstance.VtctldClientProcess, primaryTablet)
assert.NoError(t, err)
fmt.Println("Throttler status response: ", output)
}
require.Failf(t, "timeout waiting for message", "expected: %s. Last seen: %s", messageSubstring, lastMessage)
return
}
}
}
func TestMain(m *testing.M) {
flag.Parse()
exitcode, err := func() (int, error) {
clusterInstance = cluster.NewCluster(cell, hostname)
schemaChangeDirectory = path.Join("/tmp", fmt.Sprintf("schema_change_dir_%d", clusterInstance.GetAndReserveTabletUID()))
defer os.RemoveAll(schemaChangeDirectory)
defer clusterInstance.Teardown()
if _, err := os.Stat(schemaChangeDirectory); os.IsNotExist(err) {
_ = os.Mkdir(schemaChangeDirectory, 0o700)
}
clusterInstance.VtctldExtraArgs = []string{
"--schema-change-dir", schemaChangeDirectory,
"--schema-change-controller", "local",
"--schema-change-check-interval", "1s",
}
clusterInstance.VtTabletExtraArgs = []string{
"--heartbeat-interval", "250ms",
"--heartbeat-on-demand-duration", "5s",
"--migration-check-interval", "2s",
"--watch-replication-stream",
}
clusterInstance.VtGateExtraArgs = []string{}
if err := clusterInstance.StartTopo(); err != nil {
return 1, err
}
// Start keyspace
keyspace := &cluster.Keyspace{
Name: keyspaceName,
}
// No need for replicas in this stress test
if err := clusterInstance.StartKeyspace(*keyspace, []string{"1"}, 0, false, clusterInstance.Cell); err != nil {
return 1, err
}
vtgateInstance := clusterInstance.NewVtgateInstance()
// Start vtgate
if err := vtgateInstance.Setup(); err != nil {
return 1, err
}
// ensure it is torn down during cluster TearDown
clusterInstance.VtgateProcess = *vtgateInstance
vtParams = mysql.ConnParams{
Host: clusterInstance.Hostname,
Port: clusterInstance.VtgateMySQLPort,
}
primaryTablet = clusterInstance.Keyspaces[0].Shards[0].PrimaryTablet()
return m.Run(), nil
}()
if err != nil {
fmt.Printf("%v\n", err)
os.Exit(1)
} else {
os.Exit(exitcode)
}
}
func TestSchedulerSchemaChanges(t *testing.T) {
throttler.EnableLagThrottlerAndWaitForStatus(t, clusterInstance)
t.Run("scheduler", testScheduler)
t.Run("singleton", testSingleton)
t.Run("declarative", testDeclarative)
t.Run("foreign-keys", testForeignKeys)
t.Run("summary: validate sequential migration IDs", func(t *testing.T) {
onlineddl.ValidateSequentialMigrationIDs(t, &vtParams, shards)
})
t.Run("summary: validate completed_timestamp", func(t *testing.T) {
onlineddl.ValidateCompletedTimestamp(t, &vtParams)
})
}
func testScheduler(t *testing.T) {
shards = clusterInstance.Keyspaces[0].Shards
require.Equal(t, 1, len(shards))
ddlStrategy := "vitess"
createParams := func(ddlStatement string, ddlStrategy string, executeStrategy string, expectHint string, expectError string, skipWait bool) *testOnlineDDLStatementParams {
return &testOnlineDDLStatementParams{
ddlStatement: ddlStatement,
ddlStrategy: ddlStrategy,
executeStrategy: executeStrategy,
expectHint: expectHint,
expectError: expectError,
skipWait: skipWait,
}
}
createRevertParams := func(revertUUID string, ddlStrategy string, executeStrategy string, expectError string, skipWait bool) *testRevertMigrationParams {
return &testRevertMigrationParams{
revertUUID: revertUUID,
executeStrategy: executeStrategy,
ddlStrategy: ddlStrategy,
expectError: expectError,
skipWait: skipWait,
}
}
mysqlVersion := onlineddl.GetMySQLVersion(t, primaryTablet)
require.NotEmpty(t, mysqlVersion)
capableOf := mysql.ServerVersionCapableOf(mysqlVersion)
var (
t1uuid string
t2uuid string
t1Name = "t1_test"
t2Name = "t2_test"
createT1Statement = `
CREATE TABLE t1_test (
id bigint(20) not null,
hint_col varchar(64) not null default 'just-created',
PRIMARY KEY (id)
) ENGINE=InnoDB
`
createT2Statement = `
CREATE TABLE t2_test (
id bigint(20) not null,
hint_col varchar(64) not null default 'just-created',
PRIMARY KEY (id)
) ENGINE=InnoDB
`
createT1IfNotExistsStatement = `
CREATE TABLE IF NOT EXISTS t1_test (
id bigint(20) not null,
hint_col varchar(64) not null default 'should_not_appear',
PRIMARY KEY (id)
) ENGINE=InnoDB
`
trivialAlterT1Statement = `
ALTER TABLE t1_test ENGINE=InnoDB;
`
trivialAlterT2Statement = `
ALTER TABLE t2_test ENGINE=InnoDB;
`
instantAlterT1Statement = `
ALTER TABLE t1_test ADD COLUMN i0 INT NOT NULL DEFAULT 0
`
instantUndoAlterT1Statement = `
ALTER TABLE t1_test DROP COLUMN i0
`
dropT1Statement = `
DROP TABLE IF EXISTS t1_test
`
dropT3Statement = `
DROP TABLE IF EXISTS t3_test
`
dropT4Statement = `
DROP TABLE IF EXISTS t4_test
`
alterExtraColumn = `
ALTER TABLE t1_test ADD COLUMN extra_column int NOT NULL DEFAULT 0
`
createViewDependsOnExtraColumn = `
CREATE VIEW t1_test_view AS SELECT id, extra_column FROM t1_test
`
alterNonexistent = `
ALTER TABLE nonexistent FORCE
`
populateT1Statement = `
insert ignore into t1_test values (1, 'new_row')
`
)
testReadTimestamp := func(t *testing.T, uuid string, timestampColumn string) (timestamp string) {
rs := onlineddl.ReadMigrations(t, &vtParams, uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
timestamp = row.AsString(timestampColumn, "")
assert.NotEmpty(t, timestamp)
}
return timestamp
}
testTableSequentialTimes := func(t *testing.T, uuid1, uuid2 string) {
// expect uuid2 to start after uuid1 completes
t.Run("Compare t1, t2 sequential times", func(t *testing.T) {
endTime1 := testReadTimestamp(t, uuid1, "completed_timestamp")
startTime2 := testReadTimestamp(t, uuid2, "started_timestamp")
assert.GreaterOrEqual(t, startTime2, endTime1)
})
}
testTableCompletionTimes := func(t *testing.T, uuid1, uuid2 string) {
// expect uuid1 to complete before uuid2
t.Run("Compare t1, t2 completion times", func(t *testing.T) {
endTime1 := testReadTimestamp(t, uuid1, "completed_timestamp")
endTime2 := testReadTimestamp(t, uuid2, "completed_timestamp")
assert.GreaterOrEqual(t, endTime2, endTime1)
})
}
testTableCompletionAndStartTimes := func(t *testing.T, uuid1, uuid2 string) {
// expect uuid1 to complete before uuid2
t.Run("Compare t1, t2 completion times", func(t *testing.T) {
endTime1 := testReadTimestamp(t, uuid1, "completed_timestamp")
startedTime2 := testReadTimestamp(t, uuid2, "started_timestamp")
assert.GreaterOrEqual(t, startedTime2, endTime1)
})
}
testAllowConcurrent := func(t *testing.T, name string, uuid string, expect int64) {
t.Run("verify allow_concurrent: "+name, func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
allowConcurrent := row.AsInt64("allow_concurrent", 0)
assert.Equal(t, expect, allowConcurrent)
}
})
}
var originalLockWaitTimeout int64
t.Run("set low lock_wait_timeout", func(t *testing.T) {
rs, err := primaryTablet.VttabletProcess.QueryTablet("select @@lock_wait_timeout as lock_wait_timeout", keyspaceName, false)
require.NoError(t, err)
row := rs.Named().Row()
require.NotNil(t, row)
originalLockWaitTimeout = row.AsInt64("lock_wait_timeout", 0)
require.NotZero(t, originalLockWaitTimeout)
_, err = primaryTablet.VttabletProcess.QueryTablet("set global lock_wait_timeout=1", keyspaceName, false)
require.NoError(t, err)
})
// CREATE
t.Run("CREATE TABLEs t1, t2", func(t *testing.T) {
{ // The table does not exist
t1uuid = testOnlineDDLStatement(t, createParams(createT1Statement, ddlStrategy, "vtgate", "just-created", "", false))
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
checkTable(t, t1Name, true)
}
{
// The table does not exist
t2uuid = testOnlineDDLStatement(t, createParams(createT2Statement, ddlStrategy, "vtgate", "just-created", "", false))
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t2uuid, schema.OnlineDDLStatusComplete)
checkTable(t, t2Name, true)
}
testTableSequentialTimes(t, t1uuid, t2uuid)
})
t.Run("Postpone launch CREATE", func(t *testing.T) {
t1uuid = testOnlineDDLStatement(t, createParams(createT1IfNotExistsStatement, ddlStrategy+" --postpone-launch --cut-over-threshold=14s", "vtgate", "", "", true)) // skip wait
time.Sleep(2 * time.Second)
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeLaunch := row.AsInt64("postpone_launch", 0)
assert.EqualValues(t, 1, postponeLaunch)
}
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusQueued)
t.Run("launch all shards", func(t *testing.T) {
onlineddl.CheckLaunchMigration(t, &vtParams, shards, t1uuid, "", true)
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeLaunch := row.AsInt64("postpone_launch", 0)
assert.Equal(t, int64(0), postponeLaunch)
cutOverThresholdSeconds := row.AsInt64("cutover_threshold_seconds", 0)
// Threshold supplied in DDL strategy
assert.EqualValues(t, 14, cutOverThresholdSeconds)
}
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
})
t.Run("Postpone launch ALTER", func(t *testing.T) {
t1uuid = testOnlineDDLStatement(t, createParams(trivialAlterT1Statement, ddlStrategy+" --postpone-launch", "vtgate", "", "", true)) // skip wait
time.Sleep(2 * time.Second)
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeLaunch := row.AsInt64("postpone_launch", 0)
assert.Equal(t, int64(1), postponeLaunch)
}
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusQueued)
t.Run("launch irrelevant UUID", func(t *testing.T) {
someOtherUUID := "00000000_1111_2222_3333_444444444444"
onlineddl.CheckLaunchMigration(t, &vtParams, shards, someOtherUUID, "", false)
time.Sleep(2 * time.Second)
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeLaunch := row.AsInt64("postpone_launch", 0)
assert.Equal(t, int64(1), postponeLaunch)
}
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusQueued)
})
t.Run("launch irrelevant shards", func(t *testing.T) {
onlineddl.CheckLaunchMigration(t, &vtParams, shards, t1uuid, "x,y,z", false)
time.Sleep(2 * time.Second)
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeLaunch := row.AsInt64("postpone_launch", 0)
assert.Equal(t, int64(1), postponeLaunch)
}
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusQueued)
})
t.Run("launch relevant shard", func(t *testing.T) {
onlineddl.CheckLaunchMigration(t, &vtParams, shards, t1uuid, "x, y, 1", true)
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeLaunch := row.AsInt64("postpone_launch", 0)
assert.Equal(t, int64(0), postponeLaunch)
}
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
})
t.Run("Postpone completion ALTER", func(t *testing.T) {
t1uuid = testOnlineDDLStatement(t, createParams(trivialAlterT1Statement, ddlStrategy+" --postpone-completion", "vtgate", "", "", true)) // skip wait
t.Run("wait for t1 running", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusRunning)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
})
t.Run("wait for ready_to_complete", func(t *testing.T) {
waitForReadyToComplete(t, t1uuid, true)
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
assert.True(t, row["shadow_analyzed_timestamp"].IsNull())
assert.Equal(t, 100.0, row.AsFloat64("progress", 0))
assert.Equal(t, int64(0), row.AsInt64("eta_seconds", -1))
}
})
t.Run("check postpone_completion", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeCompletion := row.AsInt64("postpone_completion", 0)
assert.Equal(t, int64(1), postponeCompletion)
}
})
t.Run("set cut-over threshold", func(t *testing.T) {
onlineddl.CheckSetMigrationCutOverThreshold(t, &vtParams, shards, t1uuid, 17700*time.Millisecond, "")
})
t.Run("complete", func(t *testing.T) {
onlineddl.CheckCompleteMigration(t, &vtParams, shards, t1uuid, true)
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
t.Run("check no postpone_completion", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeCompletion := row.AsInt64("postpone_completion", 0)
assert.Equal(t, int64(0), postponeCompletion)
cutOverThresholdSeconds := row.AsInt64("cutover_threshold_seconds", 0)
// Expect 17800*time.Millisecond to be truncated to 17 seconds
assert.EqualValues(t, 17, cutOverThresholdSeconds)
assert.False(t, row["shadow_analyzed_timestamp"].IsNull())
}
})
})
t.Run("Postpone completion ALTER with shards", func(t *testing.T) {
t1uuid = testOnlineDDLStatement(t, createParams(trivialAlterT1Statement, ddlStrategy+" --postpone-completion", "vtgate", "", "", true)) // skip wait
t.Run("wait for t1 running", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusRunning)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
})
t.Run("wait for ready_to_complete", func(t *testing.T) {
waitForReadyToComplete(t, t1uuid, true)
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
assert.True(t, row["shadow_analyzed_timestamp"].IsNull())
assert.Equal(t, 100.0, row.AsFloat64("progress", 0))
assert.Equal(t, int64(0), row.AsInt64("eta_seconds", -1))
}
})
t.Run("check postpone_completion", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeCompletion := row.AsInt64("postpone_completion", 0)
assert.Equal(t, int64(1), postponeCompletion)
}
})
t.Run("complete with irrelevant shards", func(t *testing.T) {
onlineddl.CheckCompleteMigrationShards(t, &vtParams, shards, t1uuid, "x,y,z", false)
// Added an artificial sleep here just to ensure we're not missing a would-be completion./
time.Sleep(2 * time.Second)
// Migration should still be in running state
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusRunning)
// postpone_completion should still be set
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeCompletion := row.AsInt64("postpone_completion", 0)
assert.Equal(t, int64(1), postponeCompletion)
}
})
t.Run("complete with relevant shards", func(t *testing.T) {
onlineddl.CheckCompleteMigrationShards(t, &vtParams, shards, t1uuid, "x, y, 1", true)
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
t.Run("check no postpone_completion", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeCompletion := row.AsInt64("postpone_completion", 0)
assert.Equal(t, int64(0), postponeCompletion)
}
})
})
t.Run("Delayed postpone completion ALTER", func(t *testing.T) {
onlineddl.ThrottleAllMigrations(t, &vtParams)
defer onlineddl.UnthrottleAllMigrations(t, &vtParams)
onlineddl.CheckThrottledApps(t, &vtParams, throttlerapp.OnlineDDLName, true)
t1uuid = testOnlineDDLStatement(t, createParams(trivialAlterT1Statement, ddlStrategy, "vtgate", "", "", true)) // skip wait
t.Run("wait for t1 running", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusRunning)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
})
t.Run("check postpone_completion", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeCompletion := row.AsInt64("postpone_completion", 0)
assert.EqualValues(t, 0, postponeCompletion)
}
})
t.Run("postpone", func(t *testing.T) {
onlineddl.CheckPostponeCompleteMigration(t, &vtParams, shards, t1uuid, true)
})
t.Run("check postpone_completion set", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeCompletion := row.AsInt64("postpone_completion", 0)
assert.EqualValues(t, 1, postponeCompletion)
}
})
onlineddl.UnthrottleAllMigrations(t, &vtParams)
onlineddl.CheckThrottledApps(t, &vtParams, throttlerapp.OnlineDDLName, false)
t.Run("wait for ready_to_complete", func(t *testing.T) {
waitForReadyToComplete(t, t1uuid, true)
})
t.Run("complete", func(t *testing.T) {
onlineddl.CheckCompleteMigration(t, &vtParams, shards, t1uuid, true)
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
t.Run("check no postpone_completion", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
postponeCompletion := row.AsInt64("postpone_completion", 0)
assert.EqualValues(t, 0, postponeCompletion)
}
})
})
t.Run("show vitess_migrations in transaction", func(t *testing.T) {
// The function validates there is no error
rs := onlineddl.VtgateExecQueryInTransaction(t, &vtParams, "show vitess_migrations", "")
assert.NotEmpty(t, rs.Rows)
})
t.Run("low @@lock_wait_timeout", func(t *testing.T) {
defer primaryTablet.VttabletProcess.QueryTablet(fmt.Sprintf("set global lock_wait_timeout=%d", originalLockWaitTimeout), keyspaceName, false)
t1uuid = testOnlineDDLStatement(t, createParams(trivialAlterT1Statement, ddlStrategy, "vtgate", "", "", false)) // wait
t.Run("trivial t1 migration", func(t *testing.T) {
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
checkTable(t, t1Name, true)
})
})
forceCutoverCapable, err := capableOf(capabilities.PerformanceSchemaDataLocksTableCapability) // 8.0
require.NoError(t, err)
if forceCutoverCapable {
t.Run("force_cutover", func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), extendedWaitTime*5)
defer cancel()
t.Run("populate t1_test", func(t *testing.T) {
onlineddl.VtgateExecQuery(t, &vtParams, populateT1Statement, "")
})
t1uuid = testOnlineDDLStatement(t, createParams(trivialAlterT1Statement, ddlStrategy+" --postpone-completion", "vtgate", "", "", true)) // skip wait
t.Run("wait for t1 running", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusRunning)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
})
t.Run("wait for t1 ready to complete", func(t *testing.T) {
// Waiting for 'running', above, is not enough. We want to let vreplication a chance to start running, or else
// we attempt the cut-over too early. Specifically in this test, we're going to lock rows FOR UPDATE, which,
// if vreplication does not get the chance to start, will prevent it from doing anything at all.
// ready_to_complete is a great signal for us that vreplication is healthy and up to date.
waitForReadyToComplete(t, t1uuid, true)
})
commitTransactionChan := make(chan any)
transactionErrorChan := make(chan error)
t.Run("locking table rows", func(t *testing.T) {
go runInTransaction(t, ctx, primaryTablet, "select * from t1_test for update", commitTransactionChan, transactionErrorChan)
})
t.Run("injecting heartbeats asynchronously", func(t *testing.T) {
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
throttler.CheckThrottler(&clusterInstance.VtctldClientProcess, primaryTablet, throttlerapp.OnlineDDLName, nil)
select {
case <-ticker.C:
case <-ctx.Done():
return
}
}
}()
})
t.Run("check no force_cutover", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
forceCutOver := row.AsInt64("force_cutover", 0)
assert.Equal(t, int64(0), forceCutOver) // disabled
}
})
t.Run("attempt to complete", func(t *testing.T) {
onlineddl.CheckCompleteMigration(t, &vtParams, shards, t1uuid, true)
})
t.Run("cut-over fail due to timeout", func(t *testing.T) {
waitForMessage(t, t1uuid, "(errno 3024) (sqlstate HY000): Query execution was interrupted, maximum statement execution time exceeded")
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed, schema.OnlineDDLStatusRunning)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusRunning)
})
t.Run("force_cutover", func(t *testing.T) {
onlineddl.CheckForceMigrationCutOver(t, &vtParams, shards, t1uuid, true)
})
t.Run("check force_cutover", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
forceCutOver := row.AsInt64("force_cutover", 0)
assert.Equal(t, int64(1), forceCutOver) // enabled
}
})
t.Run("expect completion", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
t.Run("expect transaction failure", func(t *testing.T) {
select {
case commitTransactionChan <- true: // good
case <-ctx.Done():
assert.Fail(t, ctx.Err().Error())
}
// Transaction will now attempt to commit. But we expect our "force_cutover" to have terminated
// the transaction's connection.
select {
case err := <-transactionErrorChan:
assert.ErrorContains(t, err, "broken pipe")
case <-ctx.Done():
assert.Fail(t, ctx.Err().Error())
}
})
})
t.Run("force_cutover mdl", func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), extendedWaitTime*5)
defer cancel()
t1uuid = testOnlineDDLStatement(t, createParams(trivialAlterT1Statement, ddlStrategy+" --postpone-completion", "vtgate", "", "", true)) // skip wait
t.Run("wait for t1 running", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusRunning)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
})
t.Run("wait for t1 ready to complete", func(t *testing.T) {
// Waiting for 'running', above, is not enough. We want to let vreplication a chance to start running, or else
// we attempt the cut-over too early. Specifically in this test, we're going to lock rows FOR UPDATE, which,
// if vreplication does not get the chance to start, will prevent it from doing anything at all.
// ready_to_complete is a great signal for us that vreplication is healthy and up to date.
waitForReadyToComplete(t, t1uuid, true)
})
conn, err := primaryTablet.VttabletProcess.TabletConn(keyspaceName, true)
require.NoError(t, err)
defer conn.Close()
unlockTables := func() error {
_, err := conn.ExecuteFetch("unlock tables", 0, false)
return err
}
t.Run("locking table", func(t *testing.T) {
_, err := conn.ExecuteFetch("lock tables t1_test write", 0, false)
require.NoError(t, err)
})
defer unlockTables()
t.Run("injecting heartbeats asynchronously", func(t *testing.T) {
go func() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
throttler.CheckThrottler(&clusterInstance.VtctldClientProcess, primaryTablet, throttlerapp.OnlineDDLName, nil)
select {
case <-ticker.C:
case <-ctx.Done():
return
}
}
}()
})
t.Run("check no force_cutover", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
forceCutOver := row.AsInt64("force_cutover", 0)
assert.Equal(t, int64(0), forceCutOver) // disabled
}
})
t.Run("attempt to complete", func(t *testing.T) {
onlineddl.CheckCompleteMigration(t, &vtParams, shards, t1uuid, true)
})
t.Run("cut-over fail due to timeout", func(t *testing.T) {
waitForMessage(t, t1uuid, "(errno 3024) (sqlstate HY000): Query execution was interrupted, maximum statement execution time exceeded")
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed, schema.OnlineDDLStatusRunning)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusRunning)
})
t.Run("force_cutover", func(t *testing.T) {
onlineddl.CheckForceMigrationCutOver(t, &vtParams, shards, t1uuid, true)
})
t.Run("check force_cutover", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
forceCutOver := row.AsInt64("force_cutover", 0)
assert.Equal(t, int64(1), forceCutOver) // enabled
}
})
t.Run("expect completion", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
t.Run("expect unlock failure", func(t *testing.T) {
err := unlockTables()
assert.ErrorContains(t, err, "broken pipe")
})
})
}
if forceCutoverCapable {
t.Run("force_cutover_instant", func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), extendedWaitTime*5)
defer cancel()
t.Run("populate t1_test", func(t *testing.T) {
onlineddl.VtgateExecQuery(t, &vtParams, populateT1Statement, "")
})
commitTransactionChan := make(chan any)
transactionErrorChan := make(chan error)
t.Run("locking table rows", func(t *testing.T) {
go runInTransaction(t, ctx, primaryTablet, "select * from t1_test for update", commitTransactionChan, transactionErrorChan)
})
t.Run("execute migration", func(t *testing.T) {
t1uuid = testOnlineDDLStatement(t, createParams(instantAlterT1Statement, ddlStrategy+" --prefer-instant-ddl --force-cut-over-after=1ms", "vtgate", "", "", true)) // skip wait
})
t.Run("expect completion", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
t.Run("check special_plan", func(t *testing.T) {
rs := onlineddl.ReadMigrations(t, &vtParams, t1uuid)
require.NotNil(t, rs)
for _, row := range rs.Named().Rows {
specialPlan := row.AsString("special_plan", "")
assert.Contains(t, specialPlan, "instant-ddl")
}
})
t.Run("expect transaction failure", func(t *testing.T) {
select {
case commitTransactionChan <- true: // good
case <-ctx.Done():
assert.Fail(t, ctx.Err().Error())
}
// Transaction will now attempt to commit. But we expect our "force_cutover" to have terminated
// the transaction's connection.
select {
case err := <-transactionErrorChan:
assert.ErrorContains(t, err, "broken pipe")
case <-ctx.Done():
assert.Fail(t, ctx.Err().Error())
}
})
t.Run("cleanup: undo migration", func(t *testing.T) {
t1uuid = testOnlineDDLStatement(t, createParams(instantUndoAlterT1Statement, ddlStrategy+" --prefer-instant-ddl --force-cut-over-after=1ms", "vtgate", "", "", true)) // skip wait
})
t.Run("cleanup: expect completion", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusComplete, schema.OnlineDDLStatusFailed)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
onlineddl.CheckMigrationStatus(t, &vtParams, shards, t1uuid, schema.OnlineDDLStatusComplete)
})
})
}
t.Run("low wait_timeout", func(t *testing.T) {
// Validate that OnlineDDL cutover increases wait_timeout on its connections
// when the server has a low wait_timeout configured. Without this protection,
// MySQL would kill cutover connections mid-operation, potentially causing
// data corruption.
ctx, cancel := context.WithTimeout(t.Context(), extendedWaitTime*5)
defer cancel()
// Read the original wait_timeout.
rs, err := primaryTablet.VttabletProcess.QueryTabletWithDB("select @@global.wait_timeout as wait_timeout", "performance_schema")
require.NoError(t, err)
row := rs.Named().Row()
require.NotNil(t, row)
originalWaitTimeout := row.AsInt64("wait_timeout", 0)
require.NotZero(t, originalWaitTimeout)
// Ensure the table exists (may not if running this subtest in isolation).
t.Run("ensure table exists", func(t *testing.T) {
uuid := testOnlineDDLStatement(t, createParams(createT1IfNotExistsStatement, ddlStrategy, "vtgate", "", "", false))
onlineddl.CheckMigrationStatus(t, &vtParams, shards, uuid, schema.OnlineDDLStatusComplete)
})
t1uuid = testOnlineDDLStatement(t, createParams(trivialAlterT1Statement, ddlStrategy+" --postpone-completion", "vtgate", "", "", true)) // skip wait
t.Run("wait for t1 running", func(t *testing.T) {
status := onlineddl.WaitForMigrationStatus(t, &vtParams, shards, t1uuid, normalWaitTime, schema.OnlineDDLStatusRunning)
fmt.Printf("# Migration status (for debug purposes): <%s>\n", status)
})
t.Run("wait for t1 ready to complete", func(t *testing.T) {