-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
backup_test.go
10315 lines (8875 loc) · 388 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
import (
"bytes"
"context"
gosql "database/sql"
"encoding/base64"
"encoding/hex"
"fmt"
"hash/crc32"
"io"
"math"
"math/rand"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/blobs"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backupbase"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backupdest"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backupencryption"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backupinfo"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backuppb"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backuputils"
_ "github.com/cockroachdb/cockroach/pkg/ccl/kvccl"
_ "github.com/cockroachdb/cockroach/pkg/ccl/multiregionccl"
_ "github.com/cockroachdb/cockroach/pkg/ccl/multitenantccl"
_ "github.com/cockroachdb/cockroach/pkg/ccl/partitionccl"
"github.com/cockroachdb/cockroach/pkg/ccl/storageccl"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/cloud/amazon"
"github.com/cockroachdb/cockroach/pkg/cloud/azure"
"github.com/cockroachdb/cockroach/pkg/cloud/cloudpb"
"github.com/cockroachdb/cockroach/pkg/cloud/gcp"
_ "github.com/cockroachdb/cockroach/pkg/cloud/impl" // register cloud storage providers
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/jobs/jobstest"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/desctestutils"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/randgen"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/jobutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/ioctx"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/log/logpb"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"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/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/logtags"
"github.com/cockroachdb/redact"
"github.com/gogo/protobuf/proto"
pgx "github.com/jackc/pgx/v4"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
func init() {
cloud.RegisterKMSFromURIFactory(MakeTestKMS, "testkms")
}
func makeTableSpan(tableID uint32) roachpb.Span {
k := keys.SystemSQLCodec.TablePrefix(tableID)
return roachpb.Span{Key: k, EndKey: k.PrefixEnd()}
}
func TestBackupRestoreStatementResult(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1
_, sqlDB, dir, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, InitManualReplication)
defer cleanupFn()
if err := backuputils.VerifyBackupRestoreStatementResult(
t, sqlDB, "BACKUP DATABASE data TO $1", localFoo,
); err != nil {
t.Fatal(err)
}
// The GZipBackupManifest subtest is to verify that BackupManifest objects
// have been stored in the GZip compressed format.
t.Run("GZipBackupManifest", func(t *testing.T) {
backupDir := fmt.Sprintf("%s/foo", dir)
backupManifestFile := backupDir + "/" + backupbase.BackupManifestName
backupManifestBytes, err := os.ReadFile(backupManifestFile)
if err != nil {
t.Fatal(err)
}
require.True(t, backupinfo.IsGZipped(backupManifestBytes))
})
sqlDB.Exec(t, "CREATE DATABASE data2")
if err := backuputils.VerifyBackupRestoreStatementResult(
t, sqlDB, "RESTORE data.* FROM $1 WITH OPTIONS (into_db='data2')", localFoo,
); err != nil {
t.Fatal(err)
}
}
func TestBackupRestoreSingleUserfile(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, InitManualReplication)
defer cleanupFn()
backupAndRestore(ctx, t, tc, []string{"userfile:///a"}, []string{"userfile:///a"}, numAccounts)
}
func TestBackupRestoreSingleNodeLocal(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, InitManualReplication)
defer cleanupFn()
backupAndRestore(ctx, t, tc, []string{localFoo}, []string{localFoo}, numAccounts)
}
func TestBackupRestoreMultiNodeLocal(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
backupAndRestore(ctx, t, tc, []string{localFoo}, []string{localFoo}, numAccounts)
}
func TestBackupRestoreMultiNodeRemote(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
// Backing up to node2's local file system
remoteFoo := "nodelocal://2/foo"
backupAndRestore(ctx, t, tc, []string{remoteFoo}, []string{localFoo}, numAccounts)
}
func TestBackupRestorePartitioned(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
args := base.TestClusterArgs{
ServerArgsPerNode: map[int]base.TestServerArgs{
0: {
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "region", Value: "west"},
// NB: This has the same value as an az in the east region
// on purpose.
{Key: "az", Value: "az1"},
{Key: "dc", Value: "dc1"},
}},
},
1: {
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "region", Value: "east"},
// NB: This has the same value as an az in the west region
// on purpose.
{Key: "az", Value: "az1"},
{Key: "dc", Value: "dc2"},
}},
},
2: {
Locality: roachpb.Locality{Tiers: []roachpb.Tier{
{Key: "region", Value: "east"},
{Key: "az", Value: "az2"},
{Key: "dc", Value: "dc3"},
}},
},
},
}
ctx := context.Background()
_, sqlDB, dir, cleanupFn := backupRestoreTestSetupWithParams(t, 3 /* nodes */, numAccounts, InitManualReplication, args)
defer cleanupFn()
// locationToDir converts backup URIs based on localFoo to the temporary
// file it represents on disk.
locationToDir := func(location string) string {
return strings.Replace(location, localFoo, filepath.Join(dir, "foo"), 1)
}
hasSSTs := func(t *testing.T, location string) bool {
sstMatcher := regexp.MustCompile(`\d+\.sst`)
subDir := filepath.Join(locationToDir(location), "data")
files, err := os.ReadDir(subDir)
if err != nil {
if oserror.IsNotExist(err) {
return false
}
t.Fatal(err)
}
found := false
for _, f := range files {
if sstMatcher.MatchString(f.Name()) {
found = true
break
}
}
return found
}
requireHasSSTs := func(t *testing.T, locations ...string) {
for _, location := range locations {
require.True(t, hasSSTs(t, location))
}
}
requireHasNoSSTs := func(t *testing.T, locations ...string) {
for _, location := range locations {
require.False(t, hasSSTs(t, location))
}
}
requireCompressedManifest := func(t *testing.T, locations ...string) {
partitionMatcher := regexp.MustCompile(`^BACKUP_PART_`)
for _, location := range locations {
subDir := locationToDir(location)
files, err := os.ReadDir(subDir)
if err != nil {
t.Fatal(err)
}
for _, f := range files {
fName := f.Name()
if partitionMatcher.MatchString(fName) {
backupPartitionFile := subDir + "/" + fName
backupPartitionBytes, err := os.ReadFile(backupPartitionFile)
if err != nil {
t.Fatal(err)
}
require.True(t, backupinfo.IsGZipped(backupPartitionBytes))
}
}
}
}
runBackupRestore := func(t *testing.T, sqlDB *sqlutils.SQLRunner, backupURIs []string) {
locationFmtString, locationURIArgs := uriFmtStringAndArgs(backupURIs)
backupQuery := fmt.Sprintf("BACKUP DATABASE data TO %s", locationFmtString)
sqlDB.Exec(t, backupQuery, locationURIArgs...)
sqlDB.Exec(t, `DROP DATABASE data;`)
restoreQuery := fmt.Sprintf("RESTORE DATABASE data FROM %s", locationFmtString)
sqlDB.Exec(t, restoreQuery, locationURIArgs...)
}
// Ensure that each node has at least one leaseholder. These are wrapped with
// SucceedsSoon() because EXPERIMENTAL_RELOCATE can fail if there are other
// replication changes happening.
ensureLeaseholder := func(t *testing.T, sqlDB *sqlutils.SQLRunner) {
for _, stmt := range []string{
`ALTER TABLE data.bank SPLIT AT VALUES (0)`,
`ALTER TABLE data.bank SPLIT AT VALUES (100)`,
`ALTER TABLE data.bank SPLIT AT VALUES (200)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[1], 0)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[2], 100)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[3], 200)`,
} {
testutils.SucceedsSoon(t, func() error {
_, err := sqlDB.DB.ExecContext(ctx, stmt)
return err
})
}
}
t.Run("partition-by-unique-key", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
testSubDir := t.Name()
locations := []string{
localFoo + "/" + testSubDir + "/1",
localFoo + "/" + testSubDir + "/2",
localFoo + "/" + testSubDir + "/3",
}
backupURIs := []string{
// The first location will contain data from node 3 with config
// dc=dc3.
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[0], url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[1], url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[2], url.QueryEscape("dc=dc2")),
}
runBackupRestore(t, sqlDB, backupURIs)
// Verify that at least one SST exists in each backup destination.
requireHasSSTs(t, locations...)
// Verify that all of the partition manifests are compressed.
requireCompressedManifest(t, locations...)
})
// Test that we're selecting the most specific locality tier for a location.
t.Run("partition-by-different-tiers", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
testSubDir := t.Name()
locations := []string{
localFoo + "/" + testSubDir + "/1",
localFoo + "/" + testSubDir + "/2",
localFoo + "/" + testSubDir + "/3",
localFoo + "/" + testSubDir + "/4",
}
backupURIs := []string{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[0], url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[1], url.QueryEscape("region=east")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[2], url.QueryEscape("az=az1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[3], url.QueryEscape("az=az2")),
}
runBackupRestore(t, sqlDB, backupURIs)
// All data should be covered by az=az1 or az=az2, so expect all the
// data on those locations.
requireHasNoSSTs(t, locations[0], locations[1])
requireHasSSTs(t, locations[2], locations[3])
})
t.Run("partition-by-several-keys", func(t *testing.T) {
ensureLeaseholder(t, sqlDB)
testSubDir := t.Name()
locations := []string{
localFoo + "/" + testSubDir + "/1",
localFoo + "/" + testSubDir + "/2",
localFoo + "/" + testSubDir + "/3",
localFoo + "/" + testSubDir + "/4",
}
backupURIs := []string{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[0], url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[1], url.QueryEscape("region=east,az=az1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[2], url.QueryEscape("region=east,az=az2")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", locations[3], url.QueryEscape("region=west,az=az1")),
}
// Specifying multiple tiers is not supported.
locationFmtString, locationURIArgs := uriFmtStringAndArgs(backupURIs)
backupQuery := fmt.Sprintf("BACKUP DATABASE data TO %s", locationFmtString)
sqlDB.ExpectErr(t, `tier must be in the form "key=value" not "region=east,az=az1"`, backupQuery, locationURIArgs...)
})
}
// TestBackupManifestFileCount tests that we don't get more than 1 file per node
// in a case where we know that the entire dataset should fit inside the
// file_sst_sink reorder buffer.
func TestBackupManifestFileCount(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderStressRace(t, "multinode cluster setup times out under stressrace, likely due to resource starvation.")
const numAccounts = 1000
_, sqlDB, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
sqlDB.Exec(t, "SET CLUSTER SETTING bulkio.backup.merge_file_buffer_size='128mb'")
sqlDB.Exec(t, "BACKUP INTO 'userfile:///backup'")
rows := sqlDB.QueryRow(t, "SELECT count(distinct(path)) FROM [SHOW BACKUP FILES FROM LATEST IN 'userfile:///backup']")
var count int
rows.Scan(&count)
// We expect no more than 1 file per backup processor
require.True(t, multiNode >= count)
}
func TestBackupRestoreAppend(t *testing.T) {
defer leaktest.AfterTest(t)()
skip.WithIssue(t, 54599, "flaky test")
skip.UnderRace(t, "flaky test. Issues #50984, #54599")
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, sqlDB, tmpDir, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
// Ensure that each node has at least one leaseholder. (These splits were
// made in backupRestoreTestSetup.) These are wrapped with SucceedsSoon()
// because EXPERIMENTAL_RELOCATE can fail if there are other replication
// changes happening.
for _, stmt := range []string{
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[1], 0)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[2], 100)`,
`ALTER TABLE data.bank EXPERIMENTAL_RELOCATE VALUES (ARRAY[3], 200)`,
} {
testutils.SucceedsSoon(t, func() error {
_, err := sqlDB.DB.ExecContext(ctx, stmt)
return err
})
}
const localFoo1, localFoo2, localFoo3 = localFoo + "/1", localFoo + "/2", localFoo + "/3"
const userfileFoo1, userfileFoo2, userfileFoo3 = `userfile:///bar/1`, `userfile:///bar/2`,
`userfile:///bar/3`
makeBackups := func(b1, b2, b3 string) []interface{} {
return []interface{}{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s&AUTH=implicit", b1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s&AUTH=implicit", b2, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s&AUTH=implicit", b3, url.QueryEscape("dc=dc2")),
}
}
makeCollections := func(c1, c2, c3 string) []interface{} {
return []interface{}{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s&AUTH=implicit", c1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s&AUTH=implicit", c2, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s&AUTH=implicit", c3, url.QueryEscape("dc=dc2")),
}
}
makeCollectionsWithSubdir := func(c1, c2, c3 string) []interface{} {
return []interface{}{
fmt.Sprintf("%s/%s?COCKROACH_LOCALITY=%s&AUTH=implicit", c1, "foo", url.QueryEscape("default")),
fmt.Sprintf("%s/%s?COCKROACH_LOCALITY=%s&AUTH=implicit", c2, "foo", url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s/%s?COCKROACH_LOCALITY=%s&AUTH=implicit", c3, "foo", url.QueryEscape("dc=dc2")),
}
}
// for testing backup *into* with specified subdirectory.
const specifiedSubdir, newSpecifiedSubdir = `subdir`, `subdir2`
var full1, full2, subdirFull1, subdirFull2 string
for _, test := range []struct {
name string
backups []interface{}
collections []interface{}
collectionsWithSubdir []interface{}
}{
{
"nodelocal",
makeBackups(localFoo1, localFoo2, localFoo3),
// for testing backup *into* collection, pick collection shards on each
// node.
makeCollections(`nodelocal://0/`, `nodelocal://1/`, `nodelocal://2/`),
makeCollectionsWithSubdir(`nodelocal://0`, `nodelocal://1`, `nodelocal://2`),
},
{
"userfile",
makeBackups(userfileFoo1, userfileFoo2, userfileFoo3),
makeCollections(`userfile:///0`, `userfile:///1`, `userfile:///2`),
makeCollectionsWithSubdir(`userfile:///0`, `userfile:///1`, `userfile:///2`),
},
} {
var tsBefore, ts1, ts1again, ts2 string
sqlDB.QueryRow(t, "SELECT cluster_logical_timestamp()").Scan(&tsBefore)
sqlDB.Exec(t, "BACKUP TO ($1, $2, $3) AS OF SYSTEM TIME "+tsBefore,
test.backups...)
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3) AS OF SYSTEM TIME "+tsBefore, test.collections...)
sqlDB.Exec(t, "BACKUP INTO $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+tsBefore,
append(test.collectionsWithSubdir, specifiedSubdir)...)
sqlDB.QueryRow(t, "UPDATE data.bank SET balance = 100 RETURNING cluster_logical_timestamp()").Scan(&ts1)
sqlDB.Exec(t, "BACKUP TO ($1, $2, $3) AS OF SYSTEM TIME "+ts1, test.backups...)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1, test.collections...)
// This should be an incremental as we already have a manifest in specifiedSubdir.
sqlDB.Exec(t, "BACKUP INTO $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1,
append(test.collectionsWithSubdir, specifiedSubdir)...)
// Append to latest again, just to prove we can append to an appended one and
// that appended didn't e.g. mess up LATEST.
sqlDB.QueryRow(t, "SELECT cluster_logical_timestamp()").Scan(&ts1again)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1again, test.collections...)
// Ensure that LATEST was created (and can be resolved) even when you backed
// up into a specified subdir to begin with.
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1again,
test.collectionsWithSubdir...)
sqlDB.QueryRow(t, "UPDATE data.bank SET balance = 200 RETURNING cluster_logical_timestamp()").Scan(&ts2)
rowsTS2 := sqlDB.QueryStr(t, "SELECT * from data.bank ORDER BY id")
sqlDB.Exec(t, "BACKUP TO ($1, $2, $3) AS OF SYSTEM TIME "+ts2, test.backups...)
// Start a new full-backup in the collection version.
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3) AS OF SYSTEM TIME "+ts2, test.collections...)
// Write to a new subdirectory thereby triggering a full-backup.
sqlDB.Exec(t, "BACKUP INTO $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts2,
append(test.collectionsWithSubdir, newSpecifiedSubdir)...)
sqlDB.Exec(t, "ALTER TABLE data.bank RENAME TO data.renamed")
sqlDB.Exec(t, "BACKUP TO ($1, $2, $3)", test.backups...)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3)", test.collections...)
sqlDB.Exec(t, "BACKUP INTO $4 IN ($1, $2, $3)", append(test.collectionsWithSubdir,
newSpecifiedSubdir)...)
sqlDB.ExpectErr(t, "cannot append a backup of specific", "BACKUP system.users TO ($1, $2, "+
"$3)", test.backups...)
// TODO(dt): prevent backing up different targets to same collection?
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM ($1, $2, $3)", test.backups...)
sqlDB.ExpectErr(t, "relation \"data.bank\" does not exist", "SELECT * FROM data.bank ORDER BY id")
sqlDB.CheckQueryResults(t, "SELECT * from data.renamed ORDER BY id", rowsTS2)
findFullBackupPaths := func(baseDir, glob string) (string, string) {
matches, err := filepath.Glob(glob)
require.NoError(t, err)
require.Equal(t, 2, len(matches))
for i := range matches {
matches[i] = strings.TrimPrefix(filepath.Dir(matches[i]), baseDir)
}
return matches[0], matches[1]
}
runRestores := func(collections []interface{}, fullBackup1, fullBackup2 string) {
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+tsBefore,
append(collections, fullBackup1)...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1,
append(collections, fullBackup1)...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1again,
append(collections, fullBackup1)...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts2, append(collections, fullBackup2)...)
if test.name != "userfile" {
// Cluster restores from userfile are not supported yet since the
// restoring cluster needs to be empty, which means it can't contain any
// userfile tables.
_, sqlDBRestore, cleanupEmptyCluster := backupRestoreTestSetupEmpty(t, multiNode, tmpDir, InitManualReplication, base.TestClusterArgs{})
defer cleanupEmptyCluster()
sqlDBRestore.Exec(t, "RESTORE FROM $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+ts2, append(collections, fullBackup2)...)
}
}
if test.name == "userfile" {
// Find the backup times in the collection and try RESTORE'ing to each, and
// within each also check if we can restore to individual times captured with
// incremental backups that were appended to that backup.
store, err := cloud.ExternalStorageFromURI(ctx, "userfile:///0",
base.ExternalIODirConfig{},
tc.Servers[0].ClusterSettings(),
blobs.TestEmptyBlobClientFactory,
username.RootUserName(),
tc.Servers[0].InternalExecutor().(*sql.InternalExecutor),
tc.Servers[0].CollectionFactory().(*descs.CollectionFactory),
tc.Servers[0].DB(),
nil, /* limiters */
)
require.NoError(t, err)
defer store.Close()
var files []string
require.NoError(t, store.List(ctx, "/", "", func(f string) error {
ok, err := path.Match("*/*/*/"+backupbase.BackupManifestName, f)
if ok {
files = append(files, f)
}
return err
}))
full1 = strings.TrimSuffix(files[0], backupbase.BackupManifestName)
full2 = strings.TrimSuffix(files[1], backupbase.BackupManifestName)
// Find the full-backups written to the specified subdirectories, and within
// each also check if we can restore to individual times captured with
// incremental backups that were appended to that backup.
var subdirFiles []string
require.NoError(t, store.List(ctx, "foo/", "", func(f string) error {
ok, err := path.Match(specifiedSubdir+"*/"+backupbase.BackupManifestName, f)
if ok {
subdirFiles = append(subdirFiles, f)
}
return err
}))
require.NoError(t, err)
subdirFull1 = strings.TrimSuffix(strings.TrimPrefix(subdirFiles[0], "foo"),
backupbase.BackupManifestName)
subdirFull2 = strings.TrimSuffix(strings.TrimPrefix(subdirFiles[1], "foo"),
backupbase.BackupManifestName)
} else {
// Find the backup times in the collection and try RESTORE'ing to each, and
// within each also check if we can restore to individual times captured with
// incremental backups that were appended to that backup.
full1, full2 = findFullBackupPaths(tmpDir, path.Join(tmpDir, "*/*/*/"+backupbase.BackupManifestName))
// Find the full-backups written to the specified subdirectories, and within
// each also check if we can restore to individual times captured with
// incremental backups that were appended to that backup.
subdirFull1, subdirFull2 = findFullBackupPaths(path.Join(tmpDir, "foo"),
path.Join(tmpDir, "foo", fmt.Sprintf("%s*", specifiedSubdir), backupbase.BackupManifestName))
}
runRestores(test.collections, full1, full2)
runRestores(test.collectionsWithSubdir, subdirFull1, subdirFull2)
// TODO(dt): test restoring to other backups via AOST.
}
}
func TestBackupAndRestoreJobDescription(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1
_, sqlDB, tmpDir, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
const c1, c2, c3 = `nodelocal://0/full/`, `nodelocal://1/full/`, `nodelocal://2/full/`
const i1, i2, i3 = `nodelocal://0/inc/`, `nodelocal://1/inc/`, `nodelocal://2/inc/`
const localFoo1, localFoo2, localFoo3 = localFoo + "/1", localFoo + "/2", localFoo + "/3"
backups := []interface{}{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo2, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo3, url.QueryEscape("dc=dc2")),
}
collections := []interface{}{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", c1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", c2, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", c3, url.QueryEscape("dc=dc2")),
}
incrementals := []interface{}{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", i1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", i2, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", i3, url.QueryEscape("dc=dc2")),
}
sqlDB.Exec(t, "BACKUP TO ($1, $2, $3)", backups...)
sqlDB.Exec(t, "BACKUP TO ($1,$2,$3) INCREMENTAL FROM $4", append(incrementals, backups[0])...)
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3)", collections...)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3)", collections...)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3) WITH incremental_location = ($4, $5, $6)",
append(collections, incrementals...)...)
sqlDB.ExpectErr(t, "the incremental_location option must contain the same number of locality",
"BACKUP INTO LATEST IN $4 WITH incremental_location = ($1, $2, $3)",
append(incrementals, collections[0])...)
sqlDB.ExpectErr(t, "A full backup cannot be written to \"/subdir\", a user defined subdirectory. To take a full backup, remove the subdirectory from the backup command",
"BACKUP INTO $4 IN ($1, $2, $3)", append(collections, "subdir")...)
time.Sleep(time.Second + 2)
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3) AS OF SYSTEM TIME '-1s'", collections...)
{
// Ensure old style show backup runs properly with locality aware uri
sqlDB.Exec(t, "SHOW BACKUP $1", backups[0])
sqlDB.Exec(t, "SHOW BACKUP $1", incrementals[0])
}
// Find the subdirectory created by the full BACKUP INTO statement.
matches, err := filepath.Glob(path.Join(tmpDir, "full/*/*/*/"+backupbase.BackupManifestName))
require.NoError(t, err)
require.Equal(t, 2, len(matches))
for i := range matches {
matches[i] = strings.TrimPrefix(filepath.Dir(matches[i]), tmpDir)
}
full1 := strings.TrimPrefix(matches[0], "/full")
asOf1 := strings.TrimPrefix(matches[1], "/full")
sqlDB.CheckQueryResults(
t, "SELECT description FROM [SHOW JOBS] WHERE status != 'failed'",
[][]string{
{fmt.Sprintf("BACKUP TO ('%s', '%s', '%s')", backups[0].(string), backups[1].(string),
backups[2].(string))},
{fmt.Sprintf("BACKUP TO ('%s', '%s', '%s') INCREMENTAL FROM '%s'", incrementals[0],
incrementals[1], incrementals[2], backups[0])},
{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s')", full1, collections[0],
collections[1], collections[2])},
{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s')", full1,
collections[0], collections[1], collections[2])},
{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s') WITH incremental_location = ('%s', '%s', '%s')",
full1, collections[0], collections[1], collections[2], incrementals[0],
incrementals[1], incrementals[2])},
{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s') AS OF SYSTEM TIME '-1s'", asOf1, collections[0],
collections[1], collections[2])},
},
)
sqlDB.CheckQueryResults(t, "SELECT description FROM [SHOW JOBS] WHERE status = 'failed'",
[][]string{{fmt.Sprintf("BACKUP INTO '%s' IN ('%s', '%s', '%s')", "/subdir", collections[0],
collections[1], collections[2])}})
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM ($1, $2, $3)", backups...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3)", append(collections, full1)...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $7 IN ($1, $2, "+
"$3) WITH incremental_location = ($4, $5, $6)",
append(collections, incrementals[0], incrementals[1], incrementals[2], full1)...)
// Test restoring from the AOST backup
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM LATEST IN ($1, $2, $3)", collections...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM $4 IN ($1, $2, $3)", append(collections, asOf1)...)
// The flavors of BACKUP and RESTORE which automatically resolve the right
// directory to read/write data to, have URIs with the resolved path written
// to the job description.
getResolvedCollectionURIs := func(prefixes []interface{}, subdir string) []string {
resolvedCollectionURIs := make([]string, len(prefixes))
for i, collection := range prefixes {
parsed, err := url.Parse(collection.(string))
require.NoError(t, err)
parsed.Path = path.Join(parsed.Path, subdir)
resolvedCollectionURIs[i] = parsed.String()
}
return resolvedCollectionURIs
}
resolvedCollectionURIs := getResolvedCollectionURIs(collections, full1)
resolvedIncURIs := getResolvedCollectionURIs(incrementals, full1)
resolvedAsOfCollectionURIs := getResolvedCollectionURIs(collections, asOf1)
sqlDB.CheckQueryResults(
t, "SELECT description FROM [SHOW JOBS] WHERE job_type='RESTORE'",
[][]string{
{fmt.Sprintf("RESTORE DATABASE data FROM ('%s', '%s', '%s')",
backups[0].(string), backups[1].(string), backups[2].(string))},
{fmt.Sprintf("RESTORE DATABASE data FROM ('%s', '%s', '%s')",
resolvedCollectionURIs[0], resolvedCollectionURIs[1],
resolvedCollectionURIs[2])},
{fmt.Sprintf("RESTORE DATABASE data FROM ('%s', '%s', '%s') WITH incremental_location = ('%s', '%s', '%s')",
resolvedCollectionURIs[0], resolvedCollectionURIs[1], resolvedCollectionURIs[2],
resolvedIncURIs[0], resolvedIncURIs[1], resolvedIncURIs[2])},
{fmt.Sprintf("RESTORE DATABASE data FROM ('%s', '%s', '%s')",
resolvedAsOfCollectionURIs[0], resolvedAsOfCollectionURIs[1],
resolvedAsOfCollectionURIs[2])},
// and again from LATEST IN...
{fmt.Sprintf("RESTORE DATABASE data FROM ('%s', '%s', '%s')",
resolvedAsOfCollectionURIs[0], resolvedAsOfCollectionURIs[1],
resolvedAsOfCollectionURIs[2])},
},
)
}
func TestBackupRestorePartitionedMergeDirectories(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
defer cleanupFn()
// TODO (lucy): This test writes a partitioned backup where all files are
// written to the same directory, which is similar to the case where a backup
// is created and then all files are consolidated into the same directory, but
// we should still have a separate test where the files are actually moved.
const localFoo1 = localFoo + "/1"
backupURIs := []string{
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo1, url.QueryEscape("default")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo1, url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s?COCKROACH_LOCALITY=%s", localFoo1, url.QueryEscape("dc=dc2")),
}
restoreURIs := []string{
localFoo1,
}
backupAndRestore(ctx, t, tc, backupURIs, restoreURIs, numAccounts)
}
func TestBackupRestoreEmpty(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 0
ctx := context.Background()
tc, _, _, cleanupFn := backupRestoreTestSetup(t, singleNode, numAccounts, InitManualReplication)
defer cleanupFn()
backupAndRestore(ctx, t, tc, []string{localFoo}, []string{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)()
skip.WithIssue(t, 68127, "flaky test")
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx := context.Background()
tc, sqlDB, _, cleanupFn := backupRestoreTestSetup(t, multiNode, numAccounts, InitManualReplication)
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, []string{localFoo}, []string{localFoo}, numAccounts)
sqlDB.Exec(t, `CREATE UNIQUE INDEX id2 ON data.bank (id)`)
var unused string
var exportedRows, exportedIndexEntries int
sqlDB.QueryRow(t, `BACKUP DATABASE data TO $1`, localFoo+"/alteredPK").Scan(
&unused, &unused, &unused, &exportedRows, &exportedIndexEntries, &unused,
)
if exportedRows != numAccounts {
t.Fatalf("expected %d rows, got %d", numAccounts, exportedRows)
}
expectedIndexEntries := numAccounts * 2 // Indexes id2 and balance_idx
if exportedIndexEntries != expectedIndexEntries {
t.Fatalf("expected %d index entries, got %d", expectedIndexEntries, exportedIndexEntries)
}
}
func backupAndRestore(
ctx context.Context,
t *testing.T,
tc *testcluster.TestCluster,
backupURIs []string,
restoreURIs []string,
numAccounts int,
) {
ctx = logtags.AddTag(ctx, "backup-client", nil)
conn := tc.Conns[0]
sqlDB := sqlutils.MakeSQLRunner(conn)
storageConn := tc.StorageClusterConn()
storageSQLDB := sqlutils.MakeSQLRunner(storageConn)
{
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, bytes int64
}
backupURIFmtString, backupURIArgs := uriFmtStringAndArgs(backupURIs)
backupQuery := fmt.Sprintf("BACKUP DATABASE data TO %s", backupURIFmtString)
sqlDB.QueryRow(t, backupQuery, backupURIArgs...).Scan(
&unused, &unused, &unused, &exported.rows, &exported.idx, &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)
}
found := false
const stmt = "SELECT payload FROM system.jobs ORDER BY created DESC LIMIT 10"
rows := sqlDB.Query(t, stmt)
for rows.Next() {
var payloadBytes []byte
if err := rows.Scan(&payloadBytes); err != nil {
t.Fatal(err)
}
payload := &jobspb.Payload{}
if err := protoutil.Unmarshal(payloadBytes, payload); err != nil {
t.Fatal("cannot unmarshal job payload from system.jobs")
}
backupManifest := &backuppb.BackupManifest{}
backupPayload, ok := payload.Details.(*jobspb.Payload_Backup)
if !ok {
t.Logf("job %T is not a backup: %v", payload.Details, payload.Details)
continue
}
backupDetails := backupPayload.Backup
found = true
if backupDetails.DeprecatedBackupManifest != nil {
t.Fatal("expected backup_manifest field of backup descriptor payload to be nil")
}
if backupManifest.DeprecatedStatistics != nil {
t.Fatal("expected statistics field of backup descriptor payload to be nil")
}
}
if err := rows.Err(); err != nil {
t.Fatalf("unexpected error querying jobs: %s", err.Error())
}
if !found {
t.Fatal("scanned job rows did not contain a backup!")
}
}
uri, err := url.Parse(backupURIs[0])
require.NoError(t, err)
if uri.Scheme == "userfile" {
sqlDB.Exec(t, `CREATE DATABASE foo`)
sqlDB.Exec(t, `USE foo`)
sqlDB.Exec(t, `DROP DATABASE data CASCADE`)
restoreURIFmtString, restoreURIArgs := uriFmtStringAndArgs(restoreURIs)
restoreQuery := fmt.Sprintf("RESTORE DATABASE DATA FROM %s", restoreURIFmtString)
verifyRestoreData(t, sqlDB, storageSQLDB, restoreQuery, restoreURIArgs, numAccounts)
} else {
// Start a new cluster to restore into.
// If the backup is on nodelocal, we need to determine which node it's on.
// Othewise, default to 0.
backupNodeID := 0
if err != nil {
t.Fatal(err)
}
if uri.Scheme == "nodelocal" && uri.Host != "" {
// If the backup is on nodelocal and has specified a host, expect it to
// be an integer.
var err error
backupNodeID, err = strconv.Atoi(uri.Host)
if err != nil {
t.Fatal(err)
}
}
args := base.TestServerArgs{
ExternalIODir: tc.Servers[backupNodeID].ClusterSettings().ExternalIODir,
}
tcRestore := testcluster.StartTestCluster(t, singleNode, base.TestClusterArgs{ServerArgs: args})
defer tcRestore.Stopper().Stop(ctx)
sqlDBRestore := sqlutils.MakeSQLRunner(tcRestore.Conns[0])
storageSQLDBRestore := sqlutils.MakeSQLRunner(tcRestore.StorageClusterConn())
// 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)`)
restoreURIFmtString, restoreURIArgs := uriFmtStringAndArgs(restoreURIs)