-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
backup_test.go
9014 lines (7750 loc) · 331 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/hex"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"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/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/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/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/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"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/tree"
"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/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"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/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/gogo/protobuf/proto"
"github.com/jackc/pgx/v4"
"github.com/kr/pretty"
"github.com/lib/pq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
func init() {
cloud.RegisterKMSFromURIFactory(MakeTestKMS, "testkms")
}
type sqlDBKey struct {
server string
user string
}
type datadrivenTestState struct {
servers map[string]serverutils.TestServerInterface
dataDirs map[string]string
sqlDBs map[sqlDBKey]*gosql.DB
noticeBuffer []string
cleanupFns []func()
}
var localityCfgs = map[string]roachpb.Locality{
"us-east-1": {
Tiers: []roachpb.Tier{
{Key: "region", Value: "us-east-1"},
{Key: "availability-zone", Value: "us-east1"},
},
},
"us-west-1": {
Tiers: []roachpb.Tier{
{Key: "region", Value: "us-west-1"},
{Key: "availability-zone", Value: "us-west1"},
},
},
"eu-central-1": {
Tiers: []roachpb.Tier{
{Key: "region", Value: "eu-central-1"},
{Key: "availability-zone", Value: "eu-central-1"},
},
},
"eu-north-1": {
Tiers: []roachpb.Tier{
{Key: "region", Value: "eu-north-1"},
{Key: "availability-zone", Value: "eu-north-1"},
},
},
}
func (d *datadrivenTestState) cleanup(ctx context.Context) {
for _, db := range d.sqlDBs {
db.Close()
}
for _, s := range d.servers {
s.Stopper().Stop(ctx)
}
for _, f := range d.cleanupFns {
f()
}
d.noticeBuffer = nil
}
func (d *datadrivenTestState) addServer(
t *testing.T,
name, iodir, tempCleanupFrequency string,
ioConf base.ExternalIODirConfig,
localities string,
) error {
var tc serverutils.TestClusterInterface
var cleanup func()
params := base.TestClusterArgs{}
params.ServerArgs.ExternalIODirConfig = ioConf
if tempCleanupFrequency != "" {
duration, err := time.ParseDuration(tempCleanupFrequency)
if err != nil {
return errors.New("unable to parse tempCleanupFrequency during server creation")
}
settings := cluster.MakeTestingClusterSettings()
sql.TempObjectCleanupInterval.Override(context.Background(), &settings.SV, duration)
sql.TempObjectWaitInterval.Override(context.Background(), &settings.SV, time.Millisecond)
params.ServerArgs.Settings = settings
}
clusterSize := singleNode
if localities != "" {
cfgs := strings.Split(localities, ",")
clusterSize = len(cfgs)
serverArgsPerNode := make(map[int]base.TestServerArgs)
for i, cfg := range cfgs {
param := params.ServerArgs
param.Locality = localityCfgs[cfg]
serverArgsPerNode[i] = param
}
params.ServerArgsPerNode = serverArgsPerNode
}
if iodir == "" {
_, tc, _, iodir, cleanup = backupRestoreTestSetupWithParams(t, clusterSize, 0, InitManualReplication, params)
} else {
_, tc, _, cleanup = backupRestoreTestSetupEmptyWithParams(t, clusterSize, iodir, InitManualReplication, params)
}
d.servers[name] = tc.Server(0)
d.dataDirs[name] = iodir
d.cleanupFns = append(d.cleanupFns, cleanup)
return nil
}
func (d *datadrivenTestState) getIODir(t *testing.T, server string) string {
dir, ok := d.dataDirs[server]
if !ok {
t.Fatalf("server %s does not exist", server)
}
return dir
}
func (d *datadrivenTestState) getSQLDB(t *testing.T, server string, user string) *gosql.DB {
key := sqlDBKey{server, user}
if db, ok := d.sqlDBs[key]; ok {
return db
}
addr := d.servers[server].ServingSQLAddr()
pgURL, cleanup := sqlutils.PGUrl(t, addr, "TestBackupRestoreDataDriven", url.User(user))
d.cleanupFns = append(d.cleanupFns, cleanup)
base, err := pq.NewConnector(pgURL.String())
if err != nil {
t.Fatal(err)
}
connector := pq.ConnectorWithNoticeHandler(base, func(notice *pq.Error) {
d.noticeBuffer = append(d.noticeBuffer, notice.Severity+": "+notice.Message)
if notice.Detail != "" {
d.noticeBuffer = append(d.noticeBuffer, "DETAIL: "+notice.Detail)
}
if notice.Hint != "" {
d.noticeBuffer = append(d.noticeBuffer, "HINT: "+notice.Hint)
}
})
d.sqlDBs[key] = gosql.OpenDB(connector)
return d.sqlDBs[key]
}
func newDatadrivenTestState() datadrivenTestState {
return datadrivenTestState{
servers: make(map[string]serverutils.TestServerInterface),
dataDirs: make(map[string]string),
sqlDBs: make(map[sqlDBKey]*gosql.DB),
}
}
// TestBackupRestoreDataDriven is a datadriven test to test standard
// backup/restore interactions involving setting up clusters and running
// different SQL commands. The test files are in testdata/backup-restore.
// It has the following commands:
//
// - "new-server name=<name> [share-io-dir=<name>]": create a new server with
// the input name. It takes in an optional share-io-dir argument to share an
// IO directory with an existing server. This is useful when restoring from a
// backup taken in another server.
// - "exec-sql server=<name>": executes the input SQL query on the target server.
// By default, server is the last created server.
// - "query-sql server=<name>": executes the input SQL query on the target server
// and expects that the results are as desired. By default, server is the last
// created server.
// - "reset": clear all state associated with the test.
func TestBackupRestoreDataDriven(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "takes >1 min under race")
skip.UnderDeadlock(t, "assertion failure under deadlock")
// This test uses this mock HTTP server to pass the backup files between tenants.
httpAddr, httpServerCleanup := makeInsecureHTTPServer(t)
defer httpServerCleanup()
ctx := context.Background()
datadriven.Walk(t, "testdata/backup-restore/", func(t *testing.T, path string) {
var lastCreatedServer string
ds := newDatadrivenTestState()
defer ds.cleanup(ctx)
datadriven.RunTest(t, path, func(t *testing.T, d *datadriven.TestData) string {
switch d.Cmd {
case "sleep":
var sleepDuration string
d.ScanArgs(t, "time", &sleepDuration)
duration, err := time.ParseDuration(sleepDuration)
if err != nil {
return err.Error()
}
time.Sleep(duration)
return ""
case "reset":
ds.cleanup(ctx)
ds = newDatadrivenTestState()
return ""
case "new-server":
var name, shareDirWith, iodir, tempCleanupFrequency, localities string
var io base.ExternalIODirConfig
d.ScanArgs(t, "name", &name)
if d.HasArg("share-io-dir") {
d.ScanArgs(t, "share-io-dir", &shareDirWith)
}
if shareDirWith != "" {
iodir = ds.getIODir(t, shareDirWith)
}
if d.HasArg("allow-implicit-access") {
io.EnableNonAdminImplicitAndArbitraryOutbound = true
}
if d.HasArg("disable-http") {
io.DisableHTTP = true
}
if d.HasArg("temp-cleanup-freq") {
d.ScanArgs(t, "temp-cleanup-freq", &tempCleanupFrequency)
}
if d.HasArg("localities") {
d.ScanArgs(t, "localities", &localities)
}
lastCreatedServer = name
err := ds.addServer(t, name, iodir, tempCleanupFrequency, io, localities)
if err != nil {
return err.Error()
}
return ""
case "exec-sql":
server := lastCreatedServer
user := "root"
if d.HasArg("server") {
d.ScanArgs(t, "server", &server)
}
if d.HasArg("user") {
d.ScanArgs(t, "user", &user)
}
ds.noticeBuffer = nil
d.Input = strings.ReplaceAll(d.Input, "http://COCKROACH_TEST_HTTP_SERVER/", httpAddr)
_, err := ds.getSQLDB(t, server, user).Exec(d.Input)
ret := ds.noticeBuffer
if err != nil {
ret = append(ds.noticeBuffer, err.Error())
if pqErr := (*pq.Error)(nil); errors.As(err, &pqErr) {
if pqErr.Detail != "" {
ret = append(ret, "DETAIL: "+pqErr.Detail)
}
if pqErr.Hint != "" {
ret = append(ret, "HINT: "+pqErr.Hint)
}
}
}
return strings.Join(ret, "\n")
case "query-sql":
server := lastCreatedServer
user := "root"
if d.HasArg("server") {
d.ScanArgs(t, "server", &server)
}
if d.HasArg("user") {
d.ScanArgs(t, "user", &user)
}
rows, err := ds.getSQLDB(t, server, user).Query(d.Input)
if err != nil {
return err.Error()
}
output, err := sqlutils.RowsToDataDrivenOutput(rows)
require.NoError(t, err)
return output
default:
return fmt.Sprintf("unknown command: %s", d.Cmd)
}
})
})
}
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 := 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 + "/" + backupManifestName
backupManifestBytes, err := ioutil.ReadFile(backupManifestFile)
if err != nil {
t.Fatal(err)
}
require.True(t, isGZipped(backupManifestBytes))
})
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 TestBackupRestoreSingleUserfile(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx, 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, 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, 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, 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, _, 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 := ioutil.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 := ioutil.ReadDir(subDir)
if err != nil {
t.Fatal(err)
}
for _, f := range files {
fName := f.Name()
if partitionMatcher.MatchString(fName) {
backupPartitionFile := subDir + "/" + fName
backupPartitionBytes, err := ioutil.ReadFile(backupPartitionFile)
if err != nil {
t.Fatal(err)
}
require.True(t, 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...)
})
}
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, 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,
security.RootUserName(),
tc.Servers[0].InternalExecutor().(*sql.InternalExecutor), tc.Servers[0].DB())
require.NoError(t, err)
defer store.Close()
var files []string
require.NoError(t, store.List(ctx, "/", "", func(f string) error {
ok, err := path.Match("*/*/*/"+backupManifestName, f)
if ok {
files = append(files, f)
}
return err
}))
full1 = strings.TrimSuffix(files[0], backupManifestName)
full2 = strings.TrimSuffix(files[1], 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+"*/"+backupManifestName, f)
if ok {
subdirFiles = append(subdirFiles, f)
}
return err
}))
require.NoError(t, err)
subdirFull1 = strings.TrimSuffix(strings.TrimPrefix(subdirFiles[0], "foo"),
backupManifestName)
subdirFull2 = strings.TrimSuffix(strings.TrimPrefix(subdirFiles[1], "foo"),
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, "*/*/*/"+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), 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/`, `nodelocal://1/`, `nodelocal://2/`
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")),
}
sqlDB.Exec(t, "BACKUP TO ($1, $2, $3)", backups...)
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 $4 IN ($1, $2, $3)", append(collections, "subdir")...)
// Find the subdirectory created by the full BACKUP INTO statement.
matches, err := filepath.Glob(path.Join(tmpDir, "*/*/*/"+backupManifestName))
require.NoError(t, err)
require.Equal(t, 1, len(matches))
for i := range matches {
matches[i] = strings.TrimPrefix(filepath.Dir(matches[i]), tmpDir)
}
full1 := matches[0]
sqlDB.CheckQueryResults(
t, "SELECT description FROM [SHOW JOBS]",
[][]string{
{fmt.Sprintf("BACKUP TO ('%s', '%s', '%s')", backups[0].(string), backups[1].(string),
backups[2].(string))},
{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')", strings.TrimPrefix(full1, "/"),
collections[0], collections[1], collections[2])},
{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 $4 IN ($1, $2, $3)", append(collections, "subdir")...)
sqlDB.Exec(t, "DROP DATABASE data CASCADE")
sqlDB.Exec(t, "RESTORE DATABASE data FROM LATEST IN ($1, $2, $3)", collections...)
// 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(subdir string) []string {
resolvedCollectionURIs := make([]string, len(collections))
for i, collection := range collections {
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(full1)
resolvedSubdirURIs := getResolvedCollectionURIs("subdir")
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')",
resolvedSubdirURIs[0], resolvedSubdirURIs[1],
resolvedSubdirURIs[2])},
// and again from LATEST IN...
{fmt.Sprintf("RESTORE DATABASE data FROM ('%s', '%s', '%s')",
resolvedSubdirURIs[0], resolvedSubdirURIs[1],
resolvedSubdirURIs[2])},
},
)
}
func TestBackupRestorePartitionedMergeDirectories(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx, 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, 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