-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathbackup_test.go
2872 lines (2449 loc) · 98.9 KB
/
backup_test.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 2016 The Cockroach Authors.
//
// Licensed as a CockroachDB Enterprise file under the Cockroach Community
// License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// https://github.com/cockroachdb/cockroach/blob/master/licenses/CCL.txt
package backupccl_test
import (
"bytes"
"context"
gosql "database/sql"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"math/rand"
"net/url"
"os"
"path/filepath"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach-go/crdb"
"github.com/kr/pretty"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl/sampledataccl"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/jobutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/workload"
"github.com/cockroachdb/cockroach/pkg/workload/bank"
)
const (
singleNode = 1
multiNode = 3
backupRestoreDefaultRanges = 10
backupRestoreRowPayloadSize = 100
localFoo = "nodelocal:///foo"
)
func backupRestoreTestSetupWithParams(
t testing.TB,
clusterSize int,
numAccounts int,
init func(tc *testcluster.TestCluster),
params base.TestClusterArgs,
) (
ctx context.Context,
tc *testcluster.TestCluster,
sqlDB *sqlutils.SQLRunner,
tempDir string,
cleanup func(),
) {
ctx = context.Background()
dir, dirCleanupFn := testutils.TempDir(t)
params.ServerArgs.ExternalIODir = dir
params.ServerArgs.UseDatabase = "data"
tc = testcluster.StartTestCluster(t, clusterSize, params)
init(tc)
const payloadSize = 100
splits := 10
if numAccounts == 0 {
splits = 0
}
bankData := bank.FromConfig(numAccounts, payloadSize, splits)
sqlDB = sqlutils.MakeSQLRunner(tc.Conns[0])
sqlDB.Exec(t, `CREATE DATABASE data`)
const insertBatchSize = 1000
const concurrency = 4
if _, err := workload.Setup(ctx, sqlDB.DB, bankData, insertBatchSize, concurrency); err != nil {
t.Fatalf("%+v", err)
}
if err := workload.Split(ctx, sqlDB.DB, bankData.Tables()[0], 1 /* concurrency */); err != nil {
// This occasionally flakes, so ignore errors.
t.Logf("failed to split: %+v", err)
}
if err := tc.WaitForFullReplication(); err != nil {
t.Fatal(err)
}
cleanupFn := func() {
tempDirs := []string{dir}
for _, s := range tc.Servers {
for _, e := range s.Engines() {
tempDirs = append(tempDirs, e.GetAuxiliaryDir())
}
}
tc.Stopper().Stop(context.TODO()) // cleans up in memory storage's auxiliary dirs
dirCleanupFn() // cleans up dir, which is the nodelocal:// storage
for _, temp := range tempDirs {
testutils.SucceedsSoon(t, func() error {
items, err := ioutil.ReadDir(temp)
if err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
for _, leftover := range items {
return errors.Errorf("found %q remaining in %s", leftover.Name(), temp)
}
return nil
})
}
}
return ctx, tc, sqlDB, dir, cleanupFn
}
func backupRestoreTestSetup(
t testing.TB, clusterSize int, numAccounts int, init func(*testcluster.TestCluster),
) (
ctx context.Context,
tc *testcluster.TestCluster,
sqlDB *sqlutils.SQLRunner,
tempDir string,
cleanup func(),
) {
return backupRestoreTestSetupWithParams(t, clusterSize, numAccounts, init, base.TestClusterArgs{})
}
func verifyBackupRestoreStatementResult(
t *testing.T, sqlDB *sqlutils.SQLRunner, query string, args ...interface{},
) error {
t.Helper()
rows := sqlDB.Query(t, query, args...)
columns, err := rows.Columns()
if err != nil {
return err
}
if e, a := columns, []string{
"job_id", "status", "fraction_completed", "rows", "index_entries", "system_records", "bytes",
}; !reflect.DeepEqual(e, a) {
return errors.Errorf("unexpected columns:\n%s", strings.Join(pretty.Diff(e, a), "\n"))
}
type job struct {
id int64
status string
fractionCompleted float32
}
var expectedJob job
var actualJob job
var unused int64
if !rows.Next() {
return errors.New("zero rows in result")
}
if err := rows.Scan(
&actualJob.id, &actualJob.status, &actualJob.fractionCompleted, &unused, &unused, &unused, &unused,
); err != nil {
return err
}
if rows.Next() {
return errors.New("more than one row in result")
}
sqlDB.QueryRow(t,
`SELECT job_id, status, fraction_completed FROM crdb_internal.jobs WHERE job_id = $1`, actualJob.id,
).Scan(
&expectedJob.id, &expectedJob.status, &expectedJob.fractionCompleted,
)
if e, a := expectedJob, actualJob; !reflect.DeepEqual(e, a) {
return errors.Errorf("result does not match system.jobs:\n%s",
strings.Join(pretty.Diff(e, a), "\n"))
}
return nil
}
func TestBackupRestoreStatementResult(t *testing.T) {
defer leaktest.AfterTest(t)()
const numAccounts = 1
_, _, sqlDB, _, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, initNone)
defer cleanupFn()
if err := verifyBackupRestoreStatementResult(
t, sqlDB, "BACKUP DATABASE data TO $1", localFoo,
); err != nil {
t.Fatal(err)
}
sqlDB.Exec(t, "CREATE DATABASE data2")
if err := verifyBackupRestoreStatementResult(
t, sqlDB, "RESTORE data.* FROM $1 WITH OPTIONS ('into_db'='data2')", localFoo,
); err != nil {
t.Fatal(err)
}
}
func TestBackupRestoreLocal(t *testing.T) {
defer leaktest.AfterTest(t)()
const numAccounts = 1000
ctx, tc, _, _, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, initNone)
defer cleanupFn()
backupAndRestore(ctx, t, tc, localFoo, numAccounts)
}
func TestBackupRestoreEmpty(t *testing.T) {
defer leaktest.AfterTest(t)()
const numAccounts = 0
ctx, tc, _, _, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, initNone)
defer cleanupFn()
backupAndRestore(ctx, t, tc, localFoo, numAccounts)
}
// Regression test for #16008. In short, the way RESTORE constructed split keys
// for tables with negative primary key data caused AdminSplit to fail.
func TestBackupRestoreNegativePrimaryKey(t *testing.T) {
defer leaktest.AfterTest(t)()
const numAccounts = 1000
ctx, tc, sqlDB, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, initNone)
defer cleanupFn()
// Give half the accounts negative primary keys.
sqlDB.Exec(t, `UPDATE data.bank SET id = $1 - id WHERE id > $1`, numAccounts/2)
// Resplit that half of the table space.
sqlDB.Exec(t,
`ALTER TABLE data.bank SPLIT AT SELECT generate_series($1, 0, $2)`,
-numAccounts/2, numAccounts/backupRestoreDefaultRanges/2,
)
backupAndRestore(ctx, t, tc, localFoo, numAccounts)
}
func backupAndRestore(
ctx context.Context, t *testing.T, tc *testcluster.TestCluster, dest string, numAccounts int,
) {
sqlDB := sqlutils.MakeSQLRunner(tc.Conns[0])
{
sqlDB.Exec(t, `CREATE INDEX balance_idx ON data.bank (balance)`)
testutils.SucceedsSoon(t, func() error {
var unused string
var createTable string
sqlDB.QueryRow(t, `SHOW CREATE TABLE data.bank`).Scan(&unused, &createTable)
if !strings.Contains(createTable, "balance_idx") {
return errors.New("expected a balance_idx index")
}
return nil
})
var unused string
var exported struct {
rows, idx, sys, bytes int64
}
sqlDB.QueryRow(t, `BACKUP DATABASE data TO $1`, dest).Scan(
&unused, &unused, &unused, &exported.rows, &exported.idx, &exported.sys, &exported.bytes,
)
// When numAccounts == 0, our approxBytes formula breaks down because
// backups of no data still contain the system.users and system.descriptor
// tables. Just skip the check in this case.
if numAccounts > 0 {
approxBytes := int64(backupRestoreRowPayloadSize * numAccounts)
if max := approxBytes * 3; exported.bytes < approxBytes || exported.bytes > max {
t.Errorf("expected data size in [%d,%d] but was %d", approxBytes, max, exported.bytes)
}
}
if expected := int64(numAccounts * 1); exported.rows != expected {
t.Fatalf("expected %d rows for %d accounts, got %d", expected, numAccounts, exported.rows)
}
if _, err := sqlDB.DB.Exec(`BACKUP DATABASE data TO $1`, dest); !testutils.IsError(err,
"already contains a BACKUP file",
) {
t.Fatalf("expected to refuse to overwrite, got %v", err)
}
}
// Start a new cluster to restore into.
{
args := base.TestServerArgs{ExternalIODir: tc.Servers[0].ClusterSettings().ExternalIODir}
tcRestore := testcluster.StartTestCluster(t, singleNode, base.TestClusterArgs{ServerArgs: args})
defer tcRestore.Stopper().Stop(ctx)
sqlDBRestore := sqlutils.MakeSQLRunner(tcRestore.Conns[0])
// Create some other descriptors to change up IDs
sqlDBRestore.Exec(t, `CREATE DATABASE other`)
// Force the ID of the restored bank table to be different.
sqlDBRestore.Exec(t, `CREATE TABLE other.empty (a INT PRIMARY KEY)`)
var unused string
var restored struct {
rows, idx, sys, bytes int64
}
sqlDBRestore.QueryRow(t, `RESTORE DATABASE DATA FROM $1`, dest).Scan(
&unused, &unused, &unused, &restored.rows, &restored.idx, &restored.sys, &restored.bytes,
)
approxBytes := int64(backupRestoreRowPayloadSize * numAccounts)
if max := approxBytes * 3; restored.bytes < approxBytes || restored.bytes > max {
t.Errorf("expected data size in [%d,%d] but was %d", approxBytes, max, restored.bytes)
}
if expected := int64(numAccounts); restored.rows != expected {
t.Fatalf("expected %d rows for %d accounts, got %d", expected, numAccounts, restored.rows)
}
if expected := int64(numAccounts); restored.idx != expected {
t.Fatalf("expected %d idx rows for %d accounts, got %d", expected, numAccounts, restored.idx)
}
var rowCount int64
sqlDBRestore.QueryRow(t, `SELECT count(*) FROM data.bank`).Scan(&rowCount)
if rowCount != int64(numAccounts) {
t.Fatalf("expected %d rows but found %d", numAccounts, rowCount)
}
sqlDBRestore.QueryRow(t, `SELECT count(*) FROM data.bank@balance_idx`).Scan(&rowCount)
if rowCount != int64(numAccounts) {
t.Fatalf("expected %d rows but found %d", numAccounts, rowCount)
}
// Verify there's no /Table/51 - /Table/51/1 empty span.
{
var count int
sqlDBRestore.QueryRow(t, `
SELECT count(*) FROM crdb_internal.ranges
WHERE start_pretty = (
('/Table/' ||
(SELECT table_id FROM crdb_internal.tables
WHERE database_name = $1 AND name = $2
)::STRING) ||
'/1'
)
`, "data", "bank").Scan(&count)
if count != 0 {
t.Fatal("unexpected span start at primary index")
}
}
}
}
func TestBackupRestoreSystemTables(t *testing.T) {
defer leaktest.AfterTest(t)()
const numAccounts = 0
ctx, _, sqlDB, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, initNone)
defer cleanupFn()
// At the time this test was written, these were the only system tables that
// were reasonable for a user to backup and restore into another cluster.
tables := []string{"locations", "role_members", "users", "zones"}
tableSpec := "system." + strings.Join(tables, ", system.")
// Take a consistent fingerprint of the original tables.
var backupAsOf string
expectedFingerprints := map[string][][]string{}
err := crdb.ExecuteTx(ctx, sqlDB.DB, nil /* txopts */, func(tx *gosql.Tx) error {
for _, table := range tables {
rows, err := sqlDB.DB.Query("SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE system." + table)
if err != nil {
return err
}
defer rows.Close()
expectedFingerprints[table], err = sqlutils.RowsToStrMatrix(rows)
if err != nil {
return err
}
}
// Record the transaction's timestamp so we can take a backup at the
// same time.
return sqlDB.DB.QueryRow("SELECT cluster_logical_timestamp()").Scan(&backupAsOf)
})
if err != nil {
t.Fatal(err)
}
// Backup and restore the tables into a new database.
sqlDB.Exec(t, `CREATE DATABASE system_new`)
sqlDB.Exec(t, fmt.Sprintf(`BACKUP %s TO '%s' AS OF SYSTEM TIME %s`, tableSpec, localFoo, backupAsOf))
sqlDB.Exec(t, fmt.Sprintf(`RESTORE %s FROM '%s' WITH into_db='system_new'`, tableSpec, localFoo))
// Verify the fingerprints match.
for _, table := range tables {
a := sqlDB.QueryStr(t, "SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE system_new."+table)
if e := expectedFingerprints[table]; !reflect.DeepEqual(e, a) {
t.Fatalf("fingerprints between system.%[1]s and system_new.%[1]s did not match:%s\n",
table, strings.Join(pretty.Diff(e, a), "\n"))
}
}
// Verify we can't shoot ourselves in the foot by accidentally restoring
// directly over the existing system tables.
_, err = sqlDB.DB.Exec(fmt.Sprintf(`RESTORE %s FROM '%s'`, tableSpec, localFoo))
if !testutils.IsError(err, `relation ".+" already exists`) {
t.Fatalf("expected 'relation already exists' error, but got %s", err)
}
}
func TestBackupRestoreSystemJobs(t *testing.T) {
defer leaktest.AfterTest(t)()
const numAccounts = 0
_, _, sqlDB, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, initNone)
defer cleanupFn()
// Get the number of existing jobs.
baseNumJobs := jobutils.GetSystemJobsCount(t, sqlDB)
sanitizedIncDir := localFoo + "/inc"
incDir := sanitizedIncDir + "?secretCredentialsHere"
sanitizedFullDir := localFoo + "/full"
fullDir := sanitizedFullDir + "?moarSecretsHere"
backupDatabaseID, err := sqlutils.QueryDatabaseID(sqlDB.DB, "data")
if err != nil {
t.Fatal(err)
}
backupTableID, err := sqlutils.QueryTableID(sqlDB.DB, "data", "bank")
if err != nil {
t.Fatal(err)
}
sqlDB.Exec(t, `CREATE DATABASE restoredb`)
restoreDatabaseID, err := sqlutils.QueryDatabaseID(sqlDB.DB, "restoredb")
if err != nil {
t.Fatal(err)
}
// We create a full backup so that, below, we can test that incremental
// backups sanitize credentials in "INCREMENTAL FROM" URLs.
//
// NB: We don't bother making assertions about this full backup since there
// are no meaningful differences in how full and incremental backups report
// status to the system.jobs table. Since the incremental BACKUP syntax is a
// superset of the full BACKUP syntax, we'll cover everything by verifying the
// incremental backup below.
sqlDB.Exec(t, `BACKUP DATABASE data TO $1`, fullDir)
sqlDB.Exec(t, `SET DATABASE = data`)
sqlDB.Exec(t, `BACKUP TABLE bank TO $1 INCREMENTAL FROM $2`, incDir, fullDir)
if err := jobutils.VerifySystemJob(t, sqlDB, baseNumJobs+1, jobspb.TypeBackup, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: fmt.Sprintf(
`BACKUP TABLE bank TO '%s' INCREMENTAL FROM '%s'`,
sanitizedIncDir, sanitizedFullDir,
),
DescriptorIDs: sqlbase.IDs{
sqlbase.ID(backupDatabaseID),
sqlbase.ID(backupTableID),
},
}); err != nil {
t.Fatal(err)
}
sqlDB.Exec(t, `RESTORE TABLE bank FROM $1, $2 WITH OPTIONS ('into_db'='restoredb')`, fullDir, incDir)
if err := jobutils.VerifySystemJob(t, sqlDB, baseNumJobs+2, jobspb.TypeRestore, jobs.StatusSucceeded, jobs.Record{
Username: security.RootUser,
Description: fmt.Sprintf(
`RESTORE TABLE bank FROM '%s', '%s' WITH into_db = 'restoredb'`,
sanitizedFullDir, sanitizedIncDir,
),
DescriptorIDs: sqlbase.IDs{
sqlbase.ID(restoreDatabaseID + 1),
},
}); err != nil {
t.Fatal(err)
}
}
type inProgressChecker func(context context.Context, ip inProgressState) error
// inProgressState holds state about an in-progress backup or restore
// for use in inProgressCheckers.
type inProgressState struct {
*gosql.DB
backupTableID uint32
dir, name string
}
func (ip inProgressState) latestJobID() (int64, error) {
var id int64
if err := ip.QueryRow(
`SELECT job_id FROM crdb_internal.jobs ORDER BY created DESC LIMIT 1`,
).Scan(&id); err != nil {
return 0, err
}
return id, nil
}
// checkInProgressBackupRestore will run a backup and restore, pausing each
// approximately halfway through to run either `checkBackup` or `checkRestore`.
func checkInProgressBackupRestore(
t testing.TB, checkBackup inProgressChecker, checkRestore inProgressChecker,
) {
// To test incremental progress updates, we install a store response filter,
// which runs immediately before a KV command returns its response, in our
// test cluster. Whenever we see an Export or Import response, we do a
// blocking read on the allowResponse channel to give the test a chance to
// assert the progress of the job.
var allowResponse chan struct{}
params := base.TestClusterArgs{}
params.ServerArgs.Knobs.Store = &storage.StoreTestingKnobs{
TestingResponseFilter: func(ba roachpb.BatchRequest, br *roachpb.BatchResponse) *roachpb.Error {
for _, ru := range br.Responses {
switch ru.GetInner().(type) {
case *roachpb.ExportResponse, *roachpb.ImportResponse:
<-allowResponse
}
}
return nil
},
}
const numAccounts = 1000
const totalExpectedResponses = backupRestoreDefaultRanges
ctx, _, sqlDB, dir, cleanup := backupRestoreTestSetupWithParams(t, multiNode, numAccounts, initNone, params)
defer cleanup()
sqlDB.Exec(t, `CREATE DATABASE restoredb`)
backupTableID, err := sqlutils.QueryTableID(sqlDB.DB, "data", "bank")
if err != nil {
t.Fatal(err)
}
do := func(query string, check inProgressChecker) {
jobDone := make(chan error)
allowResponse = make(chan struct{}, totalExpectedResponses)
go func() {
_, err := sqlDB.DB.Exec(query, localFoo)
jobDone <- err
}()
// Allow half the total expected responses to proceed.
for i := 0; i < totalExpectedResponses/2; i++ {
allowResponse <- struct{}{}
}
err := retry.ForDuration(testutils.DefaultSucceedsSoonDuration, func() error {
return check(ctx, inProgressState{
DB: sqlDB.DB,
backupTableID: backupTableID,
dir: dir,
name: "foo",
})
})
// Close the channel to allow all remaining responses to proceed. We do this
// even if the above retry.ForDuration failed, otherwise the test will hang
// forever.
close(allowResponse)
if err := <-jobDone; err != nil {
t.Fatalf("%q: %+v", query, err)
}
if err != nil {
t.Fatal(err)
}
}
do(`BACKUP DATABASE data TO $1`, checkBackup)
do(`RESTORE data.* FROM $1 WITH OPTIONS ('into_db'='restoredb')`, checkRestore)
}
func TestBackupRestoreSystemJobsProgress(t *testing.T) {
defer leaktest.AfterTest(t)()
checkFraction := func(ctx context.Context, ip inProgressState) error {
jobID, err := ip.latestJobID()
if err != nil {
return err
}
var fractionCompleted float32
if err := ip.QueryRow(
`SELECT fraction_completed FROM crdb_internal.jobs WHERE job_id = $1`,
jobID,
).Scan(&fractionCompleted); err != nil {
return err
}
if fractionCompleted < 0.25 || fractionCompleted > 0.75 {
return errors.Errorf(
"expected progress to be in range [0.25, 0.75] but got %f",
fractionCompleted,
)
}
return nil
}
checkInProgressBackupRestore(t, checkFraction, checkFraction)
}
func TestBackupRestoreCheckpointing(t *testing.T) {
defer leaktest.AfterTest(t)()
defer func(oldInterval time.Duration) {
backupccl.BackupCheckpointInterval = oldInterval
}(backupccl.BackupCheckpointInterval)
backupccl.BackupCheckpointInterval = 0
var checkpointPath string
checkBackup := func(ctx context.Context, ip inProgressState) error {
checkpointPath = filepath.Join(ip.dir, ip.name, backupccl.BackupDescriptorCheckpointName)
checkpointDescBytes, err := ioutil.ReadFile(checkpointPath)
if err != nil {
return errors.Errorf("%+v", err)
}
var checkpointDesc backupccl.BackupDescriptor
if err := protoutil.Unmarshal(checkpointDescBytes, &checkpointDesc); err != nil {
return errors.Errorf("%+v", err)
}
if len(checkpointDesc.Files) == 0 {
return errors.Errorf("empty backup checkpoint descriptor")
}
return nil
}
checkRestore := func(ctx context.Context, ip inProgressState) error {
jobID, err := ip.latestJobID()
if err != nil {
return err
}
highWaterMark, err := getHighWaterMark(jobID, ip.DB)
if err != nil {
return err
}
low := keys.MakeTablePrefix(ip.backupTableID)
high := keys.MakeTablePrefix(ip.backupTableID + 1)
if bytes.Compare(highWaterMark, low) <= 0 || bytes.Compare(highWaterMark, high) >= 0 {
return errors.Errorf("expected high-water mark %v to be between %v and %v",
highWaterMark, roachpb.Key(low), roachpb.Key(high))
}
return nil
}
checkInProgressBackupRestore(t, checkBackup, checkRestore)
if _, err := os.Stat(checkpointPath); err == nil {
t.Fatalf("backup checkpoint descriptor at %s not cleaned up", checkpointPath)
} else if !os.IsNotExist(err) {
t.Fatal(err)
}
}
func createAndWaitForJob(
db *gosql.DB, descriptorIDs []sqlbase.ID, details jobspb.Details, progress jobspb.ProgressDetails,
) error {
now := timeutil.ToUnixMicros(timeutil.Now())
payload, err := protoutil.Marshal(&jobspb.Payload{
Username: security.RootUser,
DescriptorIDs: descriptorIDs,
StartedMicros: now,
Details: jobspb.WrapPayloadDetails(details),
Lease: &jobspb.Lease{NodeID: 1},
})
if err != nil {
return err
}
progressBytes, err := protoutil.Marshal(&jobspb.Progress{
ModifiedMicros: now,
Details: jobspb.WrapProgressDetails(progress),
})
if err != nil {
return err
}
var jobID int64
if err := db.QueryRow(
`INSERT INTO system.jobs (created, status, payload, progress) VALUES ($1, $2, $3, $4) RETURNING id`,
timeutil.FromUnixMicros(now), jobs.StatusRunning, payload, progressBytes,
).Scan(&jobID); err != nil {
return err
}
return jobutils.WaitForJob(db, jobID)
}
// TestBackupRestoreResume tests whether backup and restore jobs are properly
// resumed after a coordinator failure. It synthesizes a partially-complete
// backup job and a partially-complete restore job, both with expired leases, by
// writing checkpoints directly to system.jobs, then verifies they are resumed
// and successfully completed within a few seconds. The test additionally
// verifies that backup and restore do not re-perform work the checkpoint claims
// to have completed.
func TestBackupRestoreResume(t *testing.T) {
defer leaktest.AfterTest(t)()
defer func(oldInterval time.Duration) {
jobs.DefaultAdoptInterval = oldInterval
}(jobs.DefaultAdoptInterval)
jobs.DefaultAdoptInterval = 100 * time.Millisecond
ctx := context.Background()
const numAccounts = 1000
_, tc, outerDB, dir, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, initNone)
defer cleanupFn()
backupTableDesc := sqlbase.GetTableDescriptor(tc.Servers[0].DB(), "data", "bank")
t.Run("backup", func(t *testing.T) {
sqlDB := sqlutils.MakeSQLRunner(outerDB.DB)
backupStartKey := backupTableDesc.PrimaryIndexSpan().Key
backupEndKey, err := sqlbase.TestingMakePrimaryIndexKey(backupTableDesc, numAccounts/2)
if err != nil {
t.Fatal(err)
}
backupCompletedSpan := roachpb.Span{Key: backupStartKey, EndKey: backupEndKey}
backupDesc, err := protoutil.Marshal(&backupccl.BackupDescriptor{
ClusterID: tc.Servers[0].ClusterID(),
Files: []backupccl.BackupDescriptor_File{
{Path: "garbage-checkpoint", Span: backupCompletedSpan},
},
})
if err != nil {
t.Fatal(err)
}
backupDir := filepath.Join(dir, "backup")
if err := os.MkdirAll(backupDir, 0755); err != nil {
t.Fatal(err)
}
checkpointFile := filepath.Join(backupDir, backupccl.BackupDescriptorCheckpointName)
if err := ioutil.WriteFile(checkpointFile, backupDesc, 0644); err != nil {
t.Fatal(err)
}
if err := createAndWaitForJob(sqlDB.DB, []sqlbase.ID{backupTableDesc.ID}, jobspb.BackupDetails{
EndTime: tc.Servers[0].Clock().Now(),
URI: "nodelocal:///backup",
BackupDescriptor: backupDesc,
}, jobspb.BackupProgress{}); err != nil {
t.Fatal(err)
}
// If the backup properly took the (incorrect) checkpoint into account, it
// won't have tried to re-export any keys within backupCompletedSpan.
backupDescriptorFile := filepath.Join(backupDir, backupccl.BackupDescriptorName)
backupDescriptorBytes, err := ioutil.ReadFile(backupDescriptorFile)
if err != nil {
t.Fatal(err)
}
var backupDescriptor backupccl.BackupDescriptor
if err := protoutil.Unmarshal(backupDescriptorBytes, &backupDescriptor); err != nil {
t.Fatal(err)
}
for _, file := range backupDescriptor.Files {
if file.Span.Overlaps(backupCompletedSpan) && file.Path != "garbage-checkpoint" {
t.Fatalf("backup re-exported checkpointed span %s", file.Span)
}
}
})
t.Run("restore", func(t *testing.T) {
sqlDB := sqlutils.MakeSQLRunner(outerDB.DB)
restoreDir := "nodelocal:///restore"
sqlDB.Exec(t, `BACKUP DATABASE DATA TO $1`, restoreDir)
sqlDB.Exec(t, `CREATE DATABASE restoredb`)
restoreDatabaseID, err := sqlutils.QueryDatabaseID(sqlDB.DB, "restoredb")
if err != nil {
t.Fatal(err)
}
restoreTableID, err := sql.GenerateUniqueDescID(ctx, tc.Servers[0].DB())
if err != nil {
t.Fatal(err)
}
restoreHighWaterMark, err := sqlbase.TestingMakePrimaryIndexKey(backupTableDesc, numAccounts/2)
if err != nil {
t.Fatal(err)
}
if err := createAndWaitForJob(sqlDB.DB, []sqlbase.ID{restoreTableID}, jobspb.RestoreDetails{
TableRewrites: map[sqlbase.ID]*jobspb.RestoreDetails_TableRewrite{
backupTableDesc.ID: {
ParentID: sqlbase.ID(restoreDatabaseID),
TableID: restoreTableID,
},
},
URIs: []string{restoreDir},
}, jobspb.RestoreProgress{
HighWater: restoreHighWaterMark,
}); err != nil {
t.Fatal(err)
}
// If the restore properly took the (incorrect) low-water mark into account,
// the first half of the table will be missing.
var restoredCount int64
sqlDB.QueryRow(t, `SELECT count(*) FROM restoredb.bank`).Scan(&restoredCount)
if e, a := int64(numAccounts)/2, restoredCount; e != a {
t.Fatalf("expected %d restored rows, but got %d\n", e, a)
}
sqlDB.Exec(t, `DELETE FROM data.bank WHERE id < $1`, numAccounts/2)
sqlDB.CheckQueryResults(t,
`SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE restoredb.bank`,
sqlDB.QueryStr(t, `SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE data.bank`),
)
})
}
func getHighWaterMark(jobID int64, sqlDB *gosql.DB) (roachpb.Key, error) {
var progressBytes []byte
if err := sqlDB.QueryRow(
`SELECT progress FROM system.jobs WHERE id = $1`, jobID,
).Scan(&progressBytes); err != nil {
return nil, err
}
var payload jobspb.Progress
if err := protoutil.Unmarshal(progressBytes, &payload); err != nil {
return nil, err
}
switch d := payload.Details.(type) {
case *jobspb.Progress_Restore:
return d.Restore.HighWater, nil
default:
return nil, errors.Errorf("unexpected job details type %T", d)
}
}
// TestBackupRestoreControlJob tests that PAUSE JOB, RESUME JOB, and CANCEL JOB
// work as intended on backup and restore jobs.
func TestBackupRestoreControlJob(t *testing.T) {
defer leaktest.AfterTest(t)()
t.Skip("#24637")
// force every call to update
jobs.TestingSetProgressThreshold(-1.0)
defer func(oldInterval time.Duration) {
jobs.DefaultAdoptInterval = oldInterval
}(jobs.DefaultAdoptInterval)
jobs.DefaultAdoptInterval = 100 * time.Millisecond
serverArgs := base.TestServerArgs{}
// Disable external processing of mutations so that the final check of
// crdb_internal.tables is guaranteed to not be cleaned up. Although this
// was never observed by a stress test, it is here for safety.
serverArgs.Knobs.SQLSchemaChanger = &sql.SchemaChangerTestingKnobs{
AsyncExecNotification: func() error {
return errors.New("async schema changer disabled")
},
}
// PAUSE JOB and CANCEL JOB are racy in that it's hard to guarantee that the
// job is still running when executing a PAUSE or CANCEL--or that the job has
// even started running. To synchronize, we install a store response filter
// which does a blocking receive whenever it encounters an export or import
// response. Below, when we want to guarantee the job is in progress, we do
// exactly one blocking send. When this send completes, we know the job has
// started, as we've seen one export or import response. We also know the job
// has not finished, because we're blocking all future export and import
// responses until we close the channel, and our backup or restore is large
// enough that it will generate more than one export or import response.
var allowResponse chan struct{}
params := base.TestClusterArgs{ServerArgs: serverArgs}
params.ServerArgs.Knobs.Store = &storage.StoreTestingKnobs{
TestingResponseFilter: jobutils.BulkOpResponseFilter(&allowResponse),
}
// We need lots of ranges to see what happens when they get chunked. Rather
// than make a huge table, dial down the zone config for the bank table.
init := func(tc *testcluster.TestCluster) {
config.TestingSetupZoneConfigHook(tc.Stopper())
v, err := tc.Servers[0].DB().Get(context.TODO(), keys.DescIDGenerator)
if err != nil {
t.Fatal(err)
}
last := uint32(v.ValueInt())
config.TestingSetZoneConfig(last+1, config.ZoneConfig{RangeMaxBytes: 5000})
}
const numAccounts = 1000
_, _, outerDB, _, cleanup := backupRestoreTestSetupWithParams(t, multiNode, numAccounts, init, params)
defer cleanup()
sqlDB := sqlutils.MakeSQLRunner(outerDB.DB)
t.Run("foreign", func(t *testing.T) {
foreignDir := "nodelocal:///foreign"
sqlDB.Exec(t, `CREATE DATABASE orig_fkdb`)
sqlDB.Exec(t, `CREATE DATABASE restore_fkdb`)
sqlDB.Exec(t, `CREATE TABLE orig_fkdb.fk (i INT REFERENCES data.bank)`)
// Generate some FK data with splits so backup/restore block correctly.
for i := 0; i < 10; i++ {
sqlDB.Exec(t, `INSERT INTO orig_fkdb.fk (i) VALUES ($1)`, i)
sqlDB.Exec(t, `ALTER TABLE orig_fkdb.fk SPLIT AT VALUES ($1)`, i)
}
for i, query := range []string{
`BACKUP TABLE orig_fkdb.fk TO $1`,
`RESTORE TABLE orig_fkdb.fk FROM $1 WITH OPTIONS ('skip_missing_foreign_keys', 'into_db'='restore_fkdb')`,
} {
jobID, err := jobutils.RunJob(t, sqlDB, &allowResponse, []string{"PAUSE"}, query, foreignDir)
if !testutils.IsError(err, "job paused") {
t.Fatalf("%d: expected 'job paused' error, but got %+v", i, err)
}
sqlDB.Exec(t, fmt.Sprintf(`RESUME JOB %d`, jobID))
if err := jobutils.WaitForJob(sqlDB.DB, jobID); err != nil {
t.Fatal(err)
}
}
sqlDB.CheckQueryResults(t,
`SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE orig_fkdb.fk`,
sqlDB.QueryStr(t, `SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE restore_fkdb.fk`),
)
})
t.Run("pause", func(t *testing.T) {
pauseDir := "nodelocal:///pause"
sqlDB.Exec(t, `CREATE DATABASE pause`)
for i, query := range []string{
`BACKUP DATABASE data TO $1`,
`RESTORE TABLE data.* FROM $1 WITH OPTIONS ('into_db'='pause')`,
} {
ops := []string{"PAUSE", "RESUME", "PAUSE"}
jobID, err := jobutils.RunJob(t, sqlDB, &allowResponse, ops, query, pauseDir)
if !testutils.IsError(err, "job paused") {
t.Fatalf("%d: expected 'job paused' error, but got %+v", i, err)
}
sqlDB.Exec(t, fmt.Sprintf(`RESUME JOB %d`, jobID))
if err := jobutils.WaitForJob(sqlDB.DB, jobID); err != nil {
t.Fatal(err)
}
}
sqlDB.CheckQueryResults(t,
`SELECT count(*) FROM pause.bank`,
sqlDB.QueryStr(t, `SELECT count(*) FROM data.bank`),
)
sqlDB.CheckQueryResults(t,
`SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE pause.bank`,
sqlDB.QueryStr(t, `SHOW EXPERIMENTAL_FINGERPRINTS FROM TABLE data.bank`),
)
})
t.Run("cancel", func(t *testing.T) {
cancelDir := "nodelocal:///cancel"
sqlDB.Exec(t, `CREATE DATABASE cancel`)
for i, query := range []string{
`BACKUP DATABASE data TO $1`,
`RESTORE TABLE data.* FROM $1 WITH OPTIONS ('into_db'='cancel')`,
} {
if _, err := jobutils.RunJob(
t, sqlDB, &allowResponse, []string{"cancel"}, query, cancelDir,
); !testutils.IsError(err, "job canceled") {
t.Fatalf("%d: expected 'job canceled' error, but got %+v", i, err)
}
// Check that executing the same backup or restore succeeds. This won't
// work if the first backup or restore was not successfully canceled.
sqlDB.Exec(t, query, cancelDir)
}
// Verify the canceled RESTORE added some DROP tables.
sqlDB.CheckQueryResults(t,
`SELECT name FROM crdb_internal.tables WHERE database_name = 'cancel' AND state = 'DROP'`,
[][]string{{"bank"}},
)
})
}
// TestRestoreFailCleanup tests that a failed RESTORE is cleaned up.
func TestRestoreFailCleanup(t *testing.T) {
defer leaktest.AfterTest(t)()
params := base.TestServerArgs{}
// Disable external processing of mutations so that the final check of