forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup_utils.go
More file actions
1651 lines (1397 loc) · 59.1 KB
/
backup_utils.go
File metadata and controls
1651 lines (1397 loc) · 59.1 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 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 vtctlbackup
import (
"bufio"
"context"
"encoding/json"
"fmt"
"math/rand/v2"
"os"
"os/exec"
"path"
"slices"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"vitess.io/vitess/go/json2"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/mysql/replication"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/test/endtoend/cluster"
"vitess.io/vitess/go/test/endtoend/utils"
"vitess.io/vitess/go/textutil"
"vitess.io/vitess/go/vt/mysqlctl"
"vitess.io/vitess/go/vt/mysqlctl/backupstorage"
"vitess.io/vitess/go/vt/proto/topodata"
"vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/sqlparser"
vtutils "vitess.io/vitess/go/vt/utils"
"vitess.io/vitess/go/vt/vterrors"
)
// constants for test variants
const (
XtraBackup = iota
BuiltinBackup
Mysqlctld
MySQLShell
timeout = time.Duration(60 * time.Second)
topoConsistencyTimeout = 20 * time.Second
)
var (
primary *cluster.Vttablet
replica1 *cluster.Vttablet
replica2 *cluster.Vttablet
replica3 *cluster.Vttablet
localCluster *cluster.LocalProcessCluster
newInitDBFile string
currentSetupType int
cell = cluster.DefaultCell
hostname = "localhost"
keyspaceName = "ks"
dbPassword = "VtDbaPass"
shardKsName = fmt.Sprintf("%s/%s", keyspaceName, shardName)
dbCredentialFile string
shardName = "0"
commonTabletArg = getDefaultCommonArgs()
vtInsertTest = `
create table vt_insert_test (
id bigint auto_increment,
msg varchar(64),
primary key (id)
) Engine=InnoDB
`
SetupReplica3Tablet func(extraArgs []string) (*cluster.Vttablet, error)
)
type CompressionDetails struct {
CompressorEngineName string
ExternalCompressorCmd string
ExternalCompressorExt string
ExternalDecompressorCmd string
ExternalDecompressorUseManifest bool
ManifestExternalDecompressorCmd string
}
// LaunchCluster : starts the cluster as per given params.
func LaunchCluster(setupType int, streamMode string, stripes int, cDetails *CompressionDetails) (int, error) {
currentSetupType = setupType
localCluster = cluster.NewCluster(cell, hostname)
// Start topo server
err := localCluster.StartTopo()
if err != nil {
return 1, err
}
// Start keyspace
localCluster.Keyspaces = []cluster.Keyspace{
{
Name: keyspaceName,
Shards: []cluster.Shard{
{
Name: shardName,
},
},
},
}
shard := &localCluster.Keyspaces[0].Shards[0]
// Create a new init_db.sql file that sets up passwords for all users.
// Then we use a db-credentials-file with the passwords.
// TODO: We could have operated with empty password here. Create a separate test for --db-credentials-file functionality (@rsajwani)
dbCredentialFile = cluster.WriteDbCredentialToTmp(localCluster.TmpDirectory)
initDb, _ := os.ReadFile(path.Join(os.Getenv("VTROOT"), "/config/init_db.sql"))
sql := string(initDb)
// The original init_db.sql does not have any passwords. Here we update the init file with passwords
sql, err = utils.GetInitDBSQL(sql, cluster.GetPasswordUpdateSQL(localCluster), "")
if err != nil {
return 1, err
}
newInitDBFile = path.Join(localCluster.TmpDirectory, "init_db_with_passwords.sql")
err = os.WriteFile(newInitDBFile, []byte(sql), 0o666)
if err != nil {
return 1, err
}
extraArgs := []string{"--db-credentials-file", dbCredentialFile}
commonTabletArg = append(commonTabletArg, "--db-credentials-file", dbCredentialFile)
// Update arguments for different backup engines
switch setupType {
case XtraBackup:
xtrabackupArgs := []string{
vtutils.GetFlagVariantForTests("--backup-engine-implementation"), "xtrabackup",
fmt.Sprintf("%s=%s", vtutils.GetFlagVariantForTests("--xtrabackup-stream-mode"), streamMode),
vtutils.GetFlagVariantForTests("--xtrabackup-user") + "=vt_dba",
fmt.Sprintf("%s=%d", vtutils.GetFlagVariantForTests("--xtrabackup-stripes"), stripes),
vtutils.GetFlagVariantForTests("--xtrabackup-backup-flags"), "--password=" + dbPassword,
}
// if streamMode is xbstream, add some additional args to test other xtrabackup flags
if streamMode == "xbstream" {
xtrabackupArgs = append(xtrabackupArgs, vtutils.GetFlagVariantForTests("--xtrabackup-prepare-flags"), "--use-memory=100M")
}
commonTabletArg = append(commonTabletArg, xtrabackupArgs...)
case MySQLShell:
mysqlShellBackupLocation := path.Join(localCluster.CurrentVTDATAROOT, "backups-mysqlshell")
err = os.MkdirAll(mysqlShellBackupLocation, 0o777)
if err != nil {
return 0, err
}
mysqlShellArgs := []string{
vtutils.GetFlagVariantForTests("--backup-engine-implementation"), "mysqlshell",
"--mysql-shell-backup-location", mysqlShellBackupLocation,
"--mysql-shell-speedup-restore=true",
}
commonTabletArg = append(commonTabletArg, mysqlShellArgs...)
}
commonTabletArg = append(commonTabletArg, getCompressorArgs(cDetails)...)
var mysqlProcs []*exec.Cmd
tabletTypes := map[int]string{
0: "primary",
1: "replica",
2: "rdonly",
3: "spare",
}
createTablet := func(tabletType string) error {
tablet := localCluster.NewVttabletInstance(tabletType, 0, cell)
tablet.VttabletProcess = localCluster.VtprocessInstanceFromVttablet(tablet, shard.Name, keyspaceName)
tablet.VttabletProcess.DbPassword = dbPassword
tablet.VttabletProcess.SupportsBackup = true
// since we spin different mysqld processes, we need to pass exactly the socket of the this particular
// one when running mysql shell dump/loads
if setupType == MySQLShell {
commonTabletArg = append(commonTabletArg,
"--mysql-shell-flags", fmt.Sprintf("--js -u vt_dba -p%s -S %s", dbPassword,
path.Join(os.Getenv("VTDATAROOT"), fmt.Sprintf("/vt_%010d", tablet.TabletUID), "mysql.sock"),
),
)
}
tablet.VttabletProcess.ExtraArgs = commonTabletArg
if setupType == Mysqlctld {
mysqlctldProcess, err := cluster.MysqlCtldProcessInstance(tablet.TabletUID, tablet.MySQLPort, localCluster.TmpDirectory)
if err != nil {
return err
}
tablet.MysqlctldProcess = *mysqlctldProcess
tablet.MysqlctldProcess.InitDBFile = newInitDBFile
tablet.MysqlctldProcess.ExtraArgs = extraArgs
tablet.MysqlctldProcess.Password = tablet.VttabletProcess.DbPassword
if err := tablet.MysqlctldProcess.Start(); err != nil {
return err
}
shard.Vttablets = append(shard.Vttablets, tablet)
return nil
}
mysqlctlProcess, err := cluster.MysqlCtlProcessInstance(tablet.TabletUID, tablet.MySQLPort, localCluster.TmpDirectory)
if err != nil {
return err
}
tablet.MysqlctlProcess = *mysqlctlProcess
tablet.MysqlctlProcess.InitDBFile = newInitDBFile
tablet.MysqlctlProcess.ExtraArgs = extraArgs
proc, err := tablet.MysqlctlProcess.StartProcess()
if err != nil {
return err
}
mysqlProcs = append(mysqlProcs, proc)
shard.Vttablets = append(shard.Vttablets, tablet)
return nil
}
for i := range 4 {
tabletType := tabletTypes[i]
if err := createTablet(tabletType); err != nil {
return 1, err
}
}
for _, proc := range mysqlProcs {
if err := proc.Wait(); err != nil {
return 1, err
}
}
primary = shard.Vttablets[0]
replica1 = shard.Vttablets[1]
replica2 = shard.Vttablets[2]
replica3 = shard.Vttablets[3]
if err := localCluster.InitTablet(primary, keyspaceName, shard.Name); err != nil {
return 1, err
}
if err := localCluster.InitTablet(replica1, keyspaceName, shard.Name); err != nil {
return 1, err
}
if err := localCluster.InitTablet(replica2, keyspaceName, shard.Name); err != nil {
return 1, err
}
vtctldClientProcess := cluster.VtctldClientProcessInstance(localCluster.VtctldProcess.GrpcPort, localCluster.TopoPort, "localhost", localCluster.TmpDirectory)
_, err = vtctldClientProcess.ExecuteCommandWithOutput("SetKeyspaceDurabilityPolicy", keyspaceName, "--durability-policy=semi_sync")
if err != nil {
return 1, err
}
for _, tablet := range []*cluster.Vttablet{primary, replica1, replica2} { // we don't start replica3 yet
if err := tablet.VttabletProcess.Setup(); err != nil {
return 1, err
}
}
SetupReplica3Tablet = func(extraArgs []string) (*cluster.Vttablet, error) {
replica3.VttabletProcess.ExtraArgs = append(replica3.VttabletProcess.ExtraArgs, extraArgs...)
if err := replica3.VttabletProcess.Setup(); err != nil {
return replica3, err
}
return replica3, nil
}
if err := localCluster.VtctldClientProcess.InitShardPrimary(keyspaceName, shard.Name, cell, primary.TabletUID); err != nil {
return 1, err
}
if err := localCluster.StartVTOrc(cell, keyspaceName); err != nil {
return 1, err
}
return 0, nil
}
func getCompressorArgs(cDetails *CompressionDetails) []string {
var args []string
if cDetails == nil {
return args
}
if cDetails.CompressorEngineName != "" {
args = append(args, "--compression-engine-name="+cDetails.CompressorEngineName)
}
if cDetails.ExternalCompressorCmd != "" {
args = append(args, "--external-compressor="+cDetails.ExternalCompressorCmd)
}
if cDetails.ExternalCompressorExt != "" {
args = append(args, "--external-compressor-extension="+cDetails.ExternalCompressorExt)
}
if cDetails.ExternalDecompressorCmd != "" {
args = append(args, "--external-decompressor="+cDetails.ExternalDecompressorCmd)
}
if cDetails.ExternalDecompressorUseManifest {
args = append(args, "--external-decompressor-use-manifest")
}
if cDetails.ManifestExternalDecompressorCmd != "" {
args = append(args, "--manifest-external-decompressor="+cDetails.ManifestExternalDecompressorCmd)
}
return args
}
// update arguments with new values of compressionDetail.
func updateCompressorArgs(commonArgs []string, cDetails *CompressionDetails) []string {
if cDetails == nil {
return commonArgs
}
// remove if any compression flag already exists
for i, s := range commonArgs {
if strings.Contains(s, "--compression-engine-name") || strings.Contains(s, "--external-compressor") ||
strings.Contains(s, "--external-compressor-extension") || strings.Contains(s, "--external-decompressor") {
commonArgs = append(commonArgs[:i], commonArgs[i+1:]...)
}
}
// update it with new values
commonArgs = append(commonArgs, getCompressorArgs(cDetails)...)
return commonArgs
}
// TearDownCluster shuts down all cluster processes
func TearDownCluster() {
localCluster.Teardown()
}
// TestBackup runs all the backup tests
func TestBackup(t *testing.T, setupType int, streamMode string, stripes int, cDetails *CompressionDetails, runSpecific []string) error {
verStr, err := mysqlctl.GetVersionString()
require.NoError(t, err)
_, vers, err := mysqlctl.ParseVersionString(verStr)
require.NoError(t, err)
switch streamMode {
case "xbstream":
if vers.Major < 8 {
t.Logf("Skipping xtrabackup tests with --xtrabackup-stream-mode=xbstream as those are only tested on XtraBackup/MySQL 8.0+")
return nil
}
case "", "tar": // streaming method of tar is the default for the vttablet --xtrabackup-stream-mode flag
// XtraBackup 8.0 must be used with MySQL 8.0 and it no longer supports tar as a stream method:
// https://docs.percona.com/percona-xtrabackup/2.4/innobackupex/streaming_backups_innobackupex.html
// https://docs.percona.com/percona-xtrabackup/8.0/xtrabackup_bin/backup.streaming.html
if vers.Major > 5 {
t.Logf("Skipping xtrabackup tests with --xtrabackup-stream-mode=tar as tar is no longer a streaming option in XtraBackup 8.0")
return nil
}
default:
require.FailNow(t, "Unsupported xtrabackup stream mode: "+streamMode)
}
testMethods := []struct {
name string
method func(t *testing.T)
}{
{
name: "TestReplicaBackup",
method: func(t *testing.T) {
vtctlBackup(t, "replica")
},
}, //
{
name: "TestRdonlyBackup",
method: func(t *testing.T) {
vtctlBackup(t, "rdonly")
},
}, //
{
name: "TestPrimaryBackup",
method: primaryBackup,
},
{
name: "TestPrimaryReplicaSameBackup",
method: primaryReplicaSameBackup,
}, //
{
name: "primaryReplicaSameBackupModifiedCompressionEngine",
method: primaryReplicaSameBackupModifiedCompressionEngine,
}, //
{
name: "TestRestoreOldPrimaryByRestart",
method: restoreOldPrimaryByRestart,
}, //
{
name: "TestRestoreOldPrimaryInPlace",
method: restoreOldPrimaryInPlace,
}, //
{
name: "TestTerminatedRestore",
method: terminatedRestore,
}, //
{
name: "DoNotDemoteNewlyPromotedPrimaryIfReparentingDuringBackup",
method: doNotDemoteNewlyPromotedPrimaryIfReparentingDuringBackup,
}, //
}
// setup cluster for the testing
code, err := LaunchCluster(setupType, streamMode, stripes, cDetails)
require.Nilf(t, err, "setup failed with status code %d", code)
// Teardown the cluster
defer TearDownCluster()
// Run all the backup tests
for _, test := range testMethods {
if len(runSpecific) > 0 && !isRegistered(test.name, runSpecific) {
continue
}
// don't run this one unless specified
if len(runSpecific) == 0 && test.name == "DoNotDemoteNewlyPromotedPrimaryIfReparentingDuringBackup" {
continue
}
if retVal := t.Run(test.name, test.method); !retVal {
return vterrors.Errorf(vtrpc.Code_UNKNOWN, "test failure: %s", test.name)
}
}
t.Run("check for files created with global permissions", func(t *testing.T) {
t.Logf("Confirming that none of the MySQL data directories that we've created have files with global permissions")
for _, ks := range localCluster.Keyspaces {
for _, shard := range ks.Shards {
for _, tablet := range shard.Vttablets {
tablet.VttabletProcess.ConfirmDataDirHasNoGlobalPerms(t)
}
}
}
})
return nil
}
func isRegistered(name string, runlist []string) bool {
return slices.Contains(runlist, name)
}
type restoreMethod func(t *testing.T, tablet *cluster.Vttablet)
// 1. create a shard with primary and replica1 only
// 2. run InitShardPrimary
// 3. insert some data
// 4. take a backup on primary and save the timestamp
// 5. bring up tablet_replica2 after the fact, let it restore the (latest/second) backup
// 6. check all data is right (before+after backup data)
// 7. insert more data on the primary
// 8. take another backup
// 9. verify that we now have 2 backups
// 10. do a PRS to make the original primary a replica so that we can do a restore there
// 11. Delete+teardown the new primary so that we can restore the first backup on the original
// primary to confirm we don't have the data from #7
// 12. restore first backup on the original primary tablet using the first backup timstamp
// 13. verify that don't have the data added after the first backup
// 14. remove the backups
func primaryBackup(t *testing.T) {
// Having the VTOrc in this test causes a lot of flakiness. For example when we delete the tablet `replica2` which
// is the current primary and then try to restore from backup the old primary (`primary.Alias`), but before that sometimes the VTOrc
// promotes the `replica1` to primary right after we delete the replica2 (current primary).
// This can result in unexpected behavior. Therefore, disabling the VTOrc in this test to remove flakiness.
localCluster.DisableVTOrcRecoveries(t)
defer func() {
localCluster.EnableVTOrcRecoveries(t)
}()
verifyInitialReplication(t)
output, err := localCluster.VtctldClientProcess.ExecuteCommandWithOutput("Backup", primary.Alias)
require.Error(t, err)
assert.Contains(t, output, "type PRIMARY cannot take backup. if you really need to do this, rerun the backup command with --allow_primary")
localCluster.VerifyBackupCount(t, shardKsName, 0)
err = localCluster.VtctldClientProcess.ExecuteCommand("Backup", "--allow-primary", primary.Alias)
require.NoError(t, err)
// We'll restore this on the primary later to test restores using a backup timestamp
firstBackupTimestamp := time.Now().UTC().Format(mysqlctl.BackupTimestampFormat)
backups := localCluster.VerifyBackupCount(t, shardKsName, 1)
assert.Contains(t, backups[0], primary.Alias)
_, err = primary.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test2')", keyspaceName, true)
require.NoError(t, err)
restoreWaitForBackup(t, "replica", nil, true)
err = replica2.VttabletProcess.WaitForTabletStatusesForTimeout([]string{"SERVING"}, timeout)
require.NoError(t, err)
// Verify that we have all the new data -- we should have 2 records now...
// And only 1 record after we restore using the first backup timestamp
cluster.VerifyRowsInTablet(t, replica2, keyspaceName, 2)
sqlInitTestTable := "init_test"
err = localCluster.VtctldClientProcess.ExecuteCommand("Backup", "--allow-primary",
// Test init SQL.
"--init-backup-sql-queries", fmt.Sprintf("create table `%s`.%s (id int),optimize table `%s`.%s,insert into `%s`.%s (id) values (1)",
primary.VttabletProcess.DbName, sqlInitTestTable, primary.VttabletProcess.DbName, sqlInitTestTable, primary.VttabletProcess.DbName, sqlInitTestTable),
"--init-backup-sql-timeout=10m",
"--init-backup-tablet-types=primary",
"--init-backup-sql-fail-on-error",
primary.Alias,
)
require.NoError(t, err)
backups = localCluster.VerifyBackupCount(t, shardKsName, 2)
assert.Contains(t, backups[1], primary.Alias)
verifyTabletBackupStats(t, primary.VttabletProcess.GetVars())
// Confirm that the init SQL quereies were run: the table was created and we inserted a row.
res, err := primary.VttabletProcess.QueryTablet("SELECT * FROM "+sqlInitTestTable, keyspaceName, true)
require.NoError(t, err)
require.Len(t, res.Rows, 1)
// Now get rid of the init_test table as its purpose has ended.
_, err = primary.VttabletProcess.QueryTablet("DROP TABLE "+sqlInitTestTable, keyspaceName, true)
require.NoError(t, err)
// Perform PRS to demote the primary tablet (primary) so that we can do a restore there and verify we don't have the
// data from after the older/first backup
err = localCluster.VtctldClientProcess.ExecuteCommand("PlannedReparentShard",
"--new-primary", replica2.Alias, shardKsName)
require.NoError(t, err)
// Delete the current primary tablet (replica2) so that the original primary tablet (primary) can be restored from the
// older/first backup w/o it replicating the subsequent insert done after the first backup was taken
err = localCluster.VtctldClientProcess.ExecuteCommand("DeleteTablets", "--allow-primary", replica2.Alias)
require.NoError(t, err)
err = replica2.VttabletProcess.TearDown()
require.NoError(t, err)
// Restore the older/first backup -- using the timestamp we saved -- on the original primary tablet (primary)
err = localCluster.VtctldClientProcess.ExecuteCommand("RestoreFromBackup", "--backup-timestamp", firstBackupTimestamp, primary.Alias)
require.NoError(t, err)
verifyTabletRestoreStats(t, primary.VttabletProcess.GetVars())
// Re-init the shard -- making the original primary tablet (primary) primary again -- for subsequent tests
err = localCluster.VtctldClientProcess.InitShardPrimary(keyspaceName, shardName, cell, primary.TabletUID)
require.NoError(t, err)
// Verify that we don't have the record created after the older/first backup
cluster.VerifyRowsInTablet(t, primary, keyspaceName, 1)
verifyAfterRemovingBackupNoBackupShouldBePresent(t, backups)
require.NoError(t, err)
_, err = primary.VttabletProcess.QueryTablet("DROP TABLE vt_insert_test", keyspaceName, true)
require.NoError(t, err)
restartPrimaryAndReplica(t)
}
// Check that a replica and primary both restored from the same backup
// can replicate successfully.
func primaryReplicaSameBackup(t *testing.T) {
// insert data on primary, wait for replica to get it
verifyInitialReplication(t)
// backup the replica
err := localCluster.VtctldClientProcess.ExecuteCommand("Backup", replica1.Alias)
require.NoError(t, err)
verifyTabletBackupStats(t, replica1.VttabletProcess.GetVars())
// insert more data on the primary
_, err = primary.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test2')", keyspaceName, true)
require.NoError(t, err)
// now bring up the other replica, letting it restore from backup.
restoreWaitForBackup(t, "replica", nil, true)
err = replica2.VttabletProcess.WaitForTabletStatusesForTimeout([]string{"SERVING"}, timeout)
require.NoError(t, err)
// check the new replica has the data
cluster.VerifyRowsInTablet(t, replica2, keyspaceName, 2)
// Promote replica2 to primary
err = localCluster.VtctldClientProcess.ExecuteCommand("PlannedReparentShard",
"--new-primary", replica2.Alias, shardKsName)
require.NoError(t, err)
// insert more data on replica2 (current primary)
_, err = replica2.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test3')", keyspaceName, true)
require.NoError(t, err)
// Force replica1 to restore from backup.
verifyRestoreTablet(t, replica1, "SERVING")
// wait for replica1 to catch up.
cluster.VerifyRowsInTablet(t, replica1, keyspaceName, 3)
// This is to test that replicationPosition is processed correctly
// while doing backup/restore after a reparent.
// It is written into the MANIFEST and read back from the MANIFEST.
//
// Take another backup on the replica.
err = localCluster.VtctldClientProcess.ExecuteCommand("Backup", replica1.Alias)
require.NoError(t, err)
// Insert more data on replica2 (current primary).
_, err = replica2.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test4')", keyspaceName, true)
require.NoError(t, err)
// Force replica1 to restore from backup.
verifyRestoreTablet(t, replica1, "SERVING")
cluster.VerifyRowsInTablet(t, replica1, keyspaceName, 4)
err = replica2.VttabletProcess.TearDown()
require.NoError(t, err)
restartPrimaryAndReplica(t)
}
// Test a primary and replica from the same backup.
//
// Check that a replica and primary both restored from the same backup
// We change compression alogrithm in between but it should not break any restore functionality
func primaryReplicaSameBackupModifiedCompressionEngine(t *testing.T) {
// insert data on primary, wait for replica to get it
verifyInitialReplication(t)
// TODO: The following Sleep in introduced as it seems like the previous step doesn't fully complete, causing
// this test to be flaky. Sleep seems to solve the problem. Need to fix this in a better way and Wait for
// previous test to complete (suspicion: MySQL does not fully start)
time.Sleep(5 * time.Second)
// backup the replica
err := localCluster.VtctldClientProcess.ExecuteCommand("Backup", replica1.Alias)
require.NoError(t, err)
verifyTabletBackupStats(t, replica1.VttabletProcess.GetVars())
// insert more data on the primary
_, err = primary.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test2')", keyspaceName, true)
require.NoError(t, err)
// now bring up the other replica, with change in compression engine
// this is to verify that restore will read engine name from manifest instead of reading the new values
cDetails := &CompressionDetails{
CompressorEngineName: "pgzip",
ExternalCompressorCmd: "gzip -c",
ExternalCompressorExt: ".gz",
ExternalDecompressorCmd: "",
}
restoreWaitForBackup(t, "replica", cDetails, false)
err = replica2.VttabletProcess.WaitForTabletStatusesForTimeout([]string{"SERVING"}, timeout)
require.NoError(t, err)
// check the new replica has the data
cluster.VerifyRowsInTablet(t, replica2, keyspaceName, 2)
// Promote replica2 to primary
err = localCluster.VtctldClientProcess.ExecuteCommand("PlannedReparentShard",
"--new-primary", replica2.Alias, shardKsName)
require.NoError(t, err)
// insert more data on replica2 (current primary)
_, err = replica2.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test3')", keyspaceName, true)
require.NoError(t, err)
// Force replica1 to restore from backup.
verifyRestoreTablet(t, replica1, "SERVING")
// wait for replica1 to catch up.
cluster.VerifyRowsInTablet(t, replica1, keyspaceName, 3)
// Promote replica1 to primary
err = localCluster.VtctldClientProcess.ExecuteCommand("PlannedReparentShard",
"--new-primary", replica1.Alias, shardKsName)
require.NoError(t, err)
// Insert more data on replica1 (current primary).
_, err = replica1.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test4')", keyspaceName, true)
require.NoError(t, err)
// wait for replica2 to catch up.
cluster.VerifyRowsInTablet(t, replica2, keyspaceName, 4)
// Now take replica2 backup with gzip (new compressor)
err = localCluster.VtctldClientProcess.ExecuteCommand("Backup", replica2.Alias)
require.NoError(t, err)
verifyTabletBackupStats(t, replica2.VttabletProcess.GetVars())
// Force replica2 to restore from backup.
verifyRestoreTablet(t, replica2, "SERVING")
cluster.VerifyRowsInTablet(t, replica2, keyspaceName, 4)
err = replica2.VttabletProcess.TearDown()
require.NoError(t, err)
restartPrimaryAndReplica(t)
}
func restoreOldPrimaryByRestart(t *testing.T) {
testRestoreOldPrimary(t, restoreUsingRestart)
}
func restoreOldPrimaryInPlace(t *testing.T) {
testRestoreOldPrimary(t, restoreInPlace)
}
// Test that a former primary replicates correctly after being restored.
//
// - Take a backup.
// - Reparent from old primary to new primary.
// - Force old primary to restore from a previous backup using restore_method.
//
// Args:
// restore_method: function accepting one parameter of type tablet.Tablet,
// this function is called to force a restore on the provided tablet
func testRestoreOldPrimary(t *testing.T, method restoreMethod) {
// insert data on primary, wait for replica to get it
verifyInitialReplication(t)
// TODO: The following Sleep in introduced as it seems like the previous step doesn't fully complete, causing
// this test to be flaky. Sleep seems to solve the problem. Need to fix this in a better way and Wait for
// previous test to complete (suspicion: MySQL does not fully start)
time.Sleep(5 * time.Second)
// backup the replica
err := localCluster.VtctldClientProcess.ExecuteCommand("Backup", replica1.Alias)
require.NoError(t, err)
verifyTabletBackupStats(t, replica1.VttabletProcess.GetVars())
// insert more data on the primary
_, err = primary.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test2')", keyspaceName, true)
require.NoError(t, err)
// reparent to replica1
err = localCluster.VtctldClientProcess.ExecuteCommand("PlannedReparentShard",
"--new-primary", replica1.Alias, shardKsName)
require.NoError(t, err)
// insert more data to new primary
_, err = replica1.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test3')", keyspaceName, true)
require.NoError(t, err)
// force the old primary to restore at the latest backup.
method(t, primary)
// wait for it to catch up.
cluster.VerifyRowsInTablet(t, primary, keyspaceName, 3)
verifyTabletRestoreStats(t, primary.VttabletProcess.GetVars())
// teardown
restartPrimaryAndReplica(t)
}
func restoreUsingRestart(t *testing.T, tablet *cluster.Vttablet) {
err := tablet.VttabletProcess.TearDown()
require.NoError(t, err)
verifyRestoreTablet(t, tablet, "SERVING")
}
func restoreInPlace(t *testing.T, tablet *cluster.Vttablet) {
err := localCluster.VtctldClientProcess.ExecuteCommand("RestoreFromBackup", tablet.Alias)
require.NoError(t, err)
}
func restartPrimaryAndReplica(t *testing.T) {
// Stop all primary, replica tablet and mysql instance
stopAllTablets()
// remove all backups
localCluster.RemoveAllBackups(t, shardKsName)
// start all tablet and mysql instances
var mysqlProcs []*exec.Cmd
for _, tablet := range []*cluster.Vttablet{primary, replica1, replica2} {
if tablet.MysqlctldProcess.TabletUID > 0 {
err := tablet.MysqlctldProcess.Start()
require.Nilf(t, err, "error while starting mysqlctld, tabletUID %v", tablet.TabletUID)
continue
}
proc, _ := tablet.MysqlctlProcess.StartProcess()
mysqlProcs = append(mysqlProcs, proc)
}
for _, proc := range mysqlProcs {
proc.Wait()
}
for _, tablet := range []*cluster.Vttablet{primary, replica1} {
err := localCluster.InitTablet(tablet, keyspaceName, shardName)
require.NoError(t, err)
err = tablet.VttabletProcess.Setup()
require.NoError(t, err)
}
err := localCluster.VtctldClientProcess.InitShardPrimary(keyspaceName, shardName, cell, primary.TabletUID)
require.NoError(t, err)
}
func stopAllTablets() {
var mysqlProcs []*exec.Cmd
for _, tablet := range []*cluster.Vttablet{primary, replica1, replica2} {
tablet.VttabletProcess.TearDown()
if tablet.MysqlctldProcess.TabletUID > 0 {
tablet.MysqlctldProcess.Stop()
localCluster.VtctldClientProcess.ExecuteCommand("DeleteTablets", "--allow-primary", tablet.Alias)
continue
}
proc, _ := tablet.MysqlctlProcess.StopProcess()
mysqlProcs = append(mysqlProcs, proc)
localCluster.VtctldClientProcess.ExecuteCommand("DeleteTablets", "--allow-primary", tablet.Alias)
}
for _, proc := range mysqlProcs {
proc.Wait()
}
for _, tablet := range []*cluster.Vttablet{primary, replica1} {
os.RemoveAll(tablet.VttabletProcess.Directory)
}
}
func terminatedRestore(t *testing.T) {
// insert data on primary, wait for replica to get it
verifyInitialReplication(t)
// TODO: The following Sleep in introduced as it seems like the previous step doesn't fully complete, causing
// this test to be flaky. Sleep seems to solve the problem. Need to fix this in a better way and Wait for
// previous test to complete (suspicion: MySQL does not fully start)
time.Sleep(5 * time.Second)
checkTabletType(t, replica1.Alias, topodata.TabletType_REPLICA)
terminateBackup(t, replica1.Alias)
// If backup fails then the tablet type goes back to original type.
checkTabletType(t, replica1.Alias, topodata.TabletType_REPLICA)
// backup the replica
err := localCluster.VtctldClientProcess.ExecuteCommand("Backup", replica1.Alias)
require.NoError(t, err)
checkTabletType(t, replica1.Alias, topodata.TabletType_REPLICA)
verifyTabletBackupStats(t, replica1.VttabletProcess.GetVars())
// insert more data on the primary
_, err = primary.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test2')", keyspaceName, true)
require.NoError(t, err)
// reparent to replica1
err = localCluster.VtctldClientProcess.ExecuteCommand("PlannedReparentShard",
"--new-primary", replica1.Alias, shardKsName)
require.NoError(t, err)
// insert more data to new primary
_, err = replica1.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test3')", keyspaceName, true)
require.NoError(t, err)
checkTabletType(t, primary.Alias, topodata.TabletType_REPLICA)
terminateRestore(t)
// If restore fails then the tablet type goes back to original type.
checkTabletType(t, primary.Alias, topodata.TabletType_REPLICA)
err = localCluster.VtctldClientProcess.ExecuteCommand("RestoreFromBackup", primary.Alias)
require.NoError(t, err)
checkTabletType(t, primary.Alias, topodata.TabletType_REPLICA)
_, err = os.Stat(path.Join(primary.VttabletProcess.Directory, "restore_in_progress"))
assert.True(t, os.IsNotExist(err))
cluster.VerifyRowsInTablet(t, primary, keyspaceName, 3)
verifyTabletRestoreStats(t, primary.VttabletProcess.GetVars())
stopAllTablets()
}
func checkTabletType(t *testing.T, alias string, tabletType topodata.TabletType) {
t.Helper()
// for loop for 15 seconds to check if tablet type is correct
for range 15 {
output, err := localCluster.VtctldClientProcess.ExecuteCommandWithOutput("GetTablet", alias)
require.NoError(t, err)
var tabletPB topodata.Tablet
err = json2.UnmarshalPB([]byte(output), &tabletPB)
require.NoError(t, err)
if tabletType == tabletPB.Type {
return
}
time.Sleep(1 * time.Second)
}
require.Failf(t, "checkTabletType failed.", "Tablet type is not correct. Expected: %v", tabletType)
}
func doNotDemoteNewlyPromotedPrimaryIfReparentingDuringBackup(t *testing.T) {
var wg sync.WaitGroup
wg.Add(2)
// Start the backup on a replica
go func() {
defer wg.Done()
// ensure this is a primary first
checkTabletType(t, primary.Alias, topodata.TabletType_PRIMARY)
// now backup
err := localCluster.VtctldClientProcess.ExecuteCommand("Backup", replica1.Alias)
require.NoError(t, err)
}()
// Perform a graceful reparent operation
go func() {
defer wg.Done()
// ensure this is a primary first
checkTabletType(t, primary.Alias, topodata.TabletType_PRIMARY)
// now reparent
_, err := localCluster.VtctldClientProcess.ExecuteCommandWithOutput(
"PlannedReparentShard",
"--new-primary", replica1.Alias,
fmt.Sprintf("%s/%s", keyspaceName, shardName),
)
require.NoError(t, err)
// check that we reparented
checkTabletType(t, replica1.Alias, topodata.TabletType_PRIMARY)
}()
wg.Wait()
// check that this is still a primary
checkTabletType(t, replica1.Alias, topodata.TabletType_PRIMARY)
}
// test_backup will:
// - create a shard with primary and replica1 only
// - run InitShardPrimary
// - bring up tablet_replica2 concurrently, telling it to wait for a backup
// - insert some data
// - take a backup
// - insert more data on the primary
// - wait for tablet_replica2 to become SERVING
// - check all data is right (before+after backup data)
// - list the backup, remove it
//
// Args:
// tablet_type: 'replica' or 'rdonly'.
func vtctlBackup(t *testing.T, tabletType string) {
// StopReplication on replica1. We verify that the replication works fine later in
// verifyInitialReplication. So this will also check that VTOrc is running.
err := localCluster.VtctldClientProcess.ExecuteCommand("StopReplication", replica1.Alias)
require.NoError(t, err)
verifyInitialReplication(t)
restoreWaitForBackup(t, tabletType, nil, true)
err = localCluster.VtctldClientProcess.ExecuteCommand("Backup", replica1.Alias)
require.NoError(t, err)
backups := localCluster.VerifyBackupCount(t, shardKsName, 1)
verifyTabletBackupStats(t, replica1.VttabletProcess.GetVars())
_, err = primary.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test2')", keyspaceName, true)
require.NoError(t, err)
err = replica2.VttabletProcess.WaitForTabletStatusesForTimeout([]string{"SERVING"}, 25*time.Second)
require.NoError(t, err)
cluster.VerifyRowsInTablet(t, replica2, keyspaceName, 2)
verifyAfterRemovingBackupNoBackupShouldBePresent(t, backups)
err = replica2.VttabletProcess.TearDown()
require.NoError(t, err)
err = localCluster.VtctldClientProcess.ExecuteCommand("DeleteTablets", replica2.Alias)
require.NoError(t, err)
_, err = primary.VttabletProcess.QueryTablet("DROP TABLE vt_insert_test", keyspaceName, true)
require.NoError(t, err)
}
func InitTestTable(t *testing.T) {
_, err := primary.VttabletProcess.QueryTablet("DROP TABLE IF EXISTS vt_insert_test", keyspaceName, true)
require.NoError(t, err)
_, err = primary.VttabletProcess.QueryTablet(vtInsertTest, keyspaceName, true)
require.NoError(t, err)
}
// This will create schema in primary, insert some data to primary and verify the same data in replica
func verifyInitialReplication(t *testing.T) {
InitTestTable(t)
_, err := primary.VttabletProcess.QueryTablet("insert into vt_insert_test (msg) values ('test1')", keyspaceName, true)
require.NoError(t, err)
cluster.VerifyRowsInTablet(t, replica1, keyspaceName, 1)
}
// Bring up another replica concurrently, telling it to wait until a backup
// is available instead of starting up empty.
//
// Override the backup engine implementation to a non-existent one for restore.
// This setting should only matter for taking new backups. We should be able