-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
backup_test.go
6359 lines (5445 loc) · 230 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"
"fmt"
"hash/crc32"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"unicode/utf8"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/cockroachdb/cockroach-go/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
_ "github.com/cockroachdb/cockroach/pkg/ccl/kvccl"
_ "github.com/cockroachdb/cockroach/pkg/ccl/partitionccl"
"github.com/cockroachdb/cockroach/pkg/ccl/storageccl"
"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/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/storage/cloud"
"github.com/cockroachdb/cockroach/pkg/storage/cloudimpl"
"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/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/gogo/protobuf/proto"
"github.com/jackc/pgx"
"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")
}
type sqlDBKey struct {
server string
user string
}
type datadrivenTestState struct {
servers map[string]serverutils.TestServerInterface
dataDirs map[string]string
sqlDBs map[sqlDBKey]*gosql.DB
cleanupFns []func()
}
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()
}
}
func (d *datadrivenTestState) addServer(
t *testing.T, name, iodir string, allowImplicitAccess bool,
) {
var tc serverutils.TestClusterInterface
var cleanup func()
params := base.TestClusterArgs{}
if allowImplicitAccess {
params.ServerArgs.Knobs.BackupRestore = &sql.BackupRestoreTestingKnobs{
AllowImplicitAccess: true,
}
}
if iodir == "" {
_, tc, _, iodir, cleanup = backupRestoreTestSetupWithParams(t, singleNode, 0, InitNone, params)
} else {
_, tc, _, cleanup = backupRestoreTestSetupEmptyWithParams(t, singleNode, iodir, InitNone, params)
}
d.servers[name] = tc.Server(0)
d.dataDirs[name] = iodir
d.cleanupFns = append(d.cleanupFns, cleanup)
}
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)
db, err := gosql.Open("postgres", pgURL.String())
if err != nil {
t.Fatal(err)
}
d.sqlDBs[key] = db
return db
}
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)
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 "reset":
ds.cleanup(ctx)
ds = newDatadrivenTestState()
return ""
case "new-server":
var name, shareDirWith, iodir string
var allowImplicitAccess bool
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") {
allowImplicitAccess = true
}
lastCreatedServer = name
ds.addServer(t, name, iodir, allowImplicitAccess)
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)
}
_, err := ds.getSQLDB(t, server, user).Exec(d.Input)
if err == nil {
return ""
}
return err.Error()
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()
}
// Find out how many output columns there are.
cols, err := rows.Columns()
if err != nil {
t.Fatal(err)
}
// Allocate a buffer of *interface{} to write results into.
elemsI := make([]interface{}, len(cols))
for i := range elemsI {
elemsI[i] = new(interface{})
}
elems := make([]string, len(cols))
// Build string output of the row data.
var output strings.Builder
for rows.Next() {
if err := rows.Scan(elemsI...); err != nil {
t.Fatal(err)
}
for i, elem := range elemsI {
val := *(elem.(*interface{}))
switch t := val.(type) {
case []byte:
// The postgres wire protocol does not distinguish between
// strings and byte arrays, but our tests do. In order to do
// The Right Thing™, we replace byte arrays which are valid
// UTF-8 with strings. This allows byte arrays which are not
// valid UTF-8 to print as a list of bytes (e.g. `[124 107]`)
// while printing valid strings naturally.
if str := string(t); utf8.ValidString(str) {
elems[i] = str
}
default:
elems[i] = fmt.Sprintf("%v", val)
}
}
output.WriteString(strings.Join(elems, " "))
output.WriteString("\n")
}
return output.String()
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, InitNone)
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)
}
fileType := http.DetectContentType(backupManifestBytes)
require.Equal(t, ZipType, fileType)
})
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, InitNone)
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, InitNone)
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, InitNone)
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, InitNone)
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
ctx, tc, sqlDB, dir, cleanupFn := BackupRestoreTestSetup(t, MultiNode, numAccounts, InitNone)
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 = LocalFoo + "/1"
const localFoo2 = LocalFoo + "/2"
const localFoo3 = LocalFoo + "/3"
backupURIs := []string{
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")),
}
restoreURIs := []string{
localFoo1,
localFoo2,
localFoo3,
}
backupAndRestore(ctx, t, tc, backupURIs, restoreURIs, numAccounts)
// Verify that at least one SST exists in each backup destination.
sstMatcher := regexp.MustCompile(`\d+\.sst`)
for i := 1; i <= 3; i++ {
subDir := fmt.Sprintf("%s/foo/%d", dir, i)
files, err := ioutil.ReadDir(subDir)
if err != nil {
t.Fatal(err)
}
found := false
for _, f := range files {
if sstMatcher.MatchString(f.Name()) {
found = true
break
}
}
if !found {
t.Fatalf("no SSTs found in %s", subDir)
}
}
// The PartitionGZip subtest is to verify that partition descriptor files
// are in the GZip compressed format.
t.Run("PartitionGZip", func(t *testing.T) {
partitionMatcher := regexp.MustCompile(`^BACKUP_PART_`)
for i := 1; i <= 3; i++ {
subDir := fmt.Sprintf("%s/foo/%d", dir, i)
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)
}
fileType := http.DetectContentType(backupPartitionBytes)
require.Equal(t, ZipType, fileType)
}
}
}
})
}
func TestBackupRestoreAppend(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numAccounts = 1000
ctx, _, sqlDB, tmpDir, cleanupFn := BackupRestoreTestSetup(t, MultiNode, numAccounts, InitNone)
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"
// for testing backup *into* collection, pick collection shards on each node.
const c1, c2, c3 = `nodelocal://0/`, `nodelocal://1/`, `nodelocal://2/`
// for testing backup *into* with specified subdirectory.
const specifiedSubdir, newSpecifiedSubdir = `subdir`, `subdir2`
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")),
}
collectionsWithSubdir := []interface{}{
fmt.Sprintf("%s%s?COCKROACH_LOCALITY=%s", c1, "foo", url.QueryEscape("default")),
fmt.Sprintf("%s%s?COCKROACH_LOCALITY=%s", c2, "foo", url.QueryEscape("dc=dc1")),
fmt.Sprintf("%s%s?COCKROACH_LOCALITY=%s", c3, "foo", url.QueryEscape("dc=dc2")),
}
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, backups...)
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3) AS OF SYSTEM TIME "+tsBefore, collections...)
sqlDB.Exec(t, "BACKUP INTO $4 IN ($1, $2, $3) AS OF SYSTEM TIME "+tsBefore,
append(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, backups...)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3) AS OF SYSTEM TIME "+ts1, 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(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, 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,
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, backups...)
// Start a new full-backup in the collection version.
sqlDB.Exec(t, "BACKUP INTO ($1, $2, $3) AS OF SYSTEM TIME "+ts2, 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(collectionsWithSubdir, newSpecifiedSubdir)...)
sqlDB.Exec(t, "ALTER TABLE data.bank RENAME TO data.renamed")
sqlDB.Exec(t, "BACKUP TO ($1, $2, $3)", backups...)
sqlDB.Exec(t, "BACKUP INTO LATEST IN ($1, $2, $3)", collections...)
sqlDB.Exec(t, "BACKUP INTO $4 IN ($1, $2, $3)", append(collectionsWithSubdir,
newSpecifiedSubdir)...)
sqlDB.ExpectErr(t, "cannot append a backup of specific", "BACKUP system.users TO ($1, $2, $3)", 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)", 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)...)
}
// 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))
runRestores(collections, full1, full2)
// 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.
full1, full2 = findFullBackupPaths(path.Join(tmpDir, "foo"),
path.Join(tmpDir, "foo", fmt.Sprintf("%s*", specifiedSubdir), backupManifestName))
runRestores(collectionsWithSubdir, full1, full2)
// 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, InitNone)
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")...)
// 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])},
},
)
}
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, InitNone)
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, InitNone)
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)()
defer log.Scope(t).Close(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, []string{LocalFoo}, []string{LocalFoo}, numAccounts)
sqlDB.Exec(t, `CREATE UNIQUE INDEX id2 ON data.bank (id)`)
sqlDB.Exec(t, `ALTER TABLE data.bank ALTER PRIMARY KEY USING COLUMNS(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 * 3 // old PK, new and old secondary 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,
) {
// uriFmtStringAndArgs returns format strings like "$1" or "($1, $2, $3)" and
// an []interface{} of URIs for the BACKUP/RESTORE queries.
uriFmtStringAndArgs := func(uris []string) (string, []interface{}) {
urisForFormat := make([]interface{}, len(uris))
var fmtString strings.Builder
if len(uris) > 1 {
fmtString.WriteString("(")
}
for i, uri := range uris {
if i > 0 {
fmtString.WriteString(", ")
}
fmtString.WriteString(fmt.Sprintf("$%d", i+1))
urisForFormat[i] = uri
}
if len(uris) > 1 {
fmtString.WriteString(")")
}
return fmtString.String(), urisForFormat
}
conn := tc.Conns[0]
sqlDB := sqlutils.MakeSQLRunner(conn)
{
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"
for rows := sqlDB.Query(t, stmt); 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 := &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 err := protoutil.Unmarshal(backupDetails.BackupManifest, backupManifest); err != nil {
t.Fatal("cannot unmarshal backup descriptor from job payload from system.jobs")
}
if backupManifest.DeprecatedStatistics != nil {
t.Fatal("expected statistics field of backup descriptor payload to be nil")
}
}
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, 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])
// 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)
restoreQuery := fmt.Sprintf("RESTORE DATABASE DATA FROM %s", restoreURIFmtString)
verifyRestoreData(t, sqlDBRestore, restoreQuery, restoreURIArgs, numAccounts)
}
}
func verifyRestoreData(
t *testing.T,
sqlDB *sqlutils.SQLRunner,
restoreQuery string,
restoreURIArgs []interface{},
numAccounts int,
) {
var unused string
var restored struct {
rows, idx, bytes int64
}
sqlDB.QueryRow(t, restoreQuery, restoreURIArgs...).Scan(
&unused, &unused, &unused, &restored.rows, &restored.idx, &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
sqlDB.QueryRow(t, `SELECT count(*) FROM data.bank`).Scan(&rowCount)
if rowCount != int64(numAccounts) {
t.Fatalf("expected %d rows but found %d", numAccounts, rowCount)
}
sqlDB.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
sqlDB.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)()
defer log.Scope(t).Close(t)
const numAccounts = 0
ctx, _, sqlDB, _, cleanupFn := BackupRestoreTestSetup(t, MultiNode, numAccounts, InitNone)
conn := sqlDB.DB.(*gosql.DB)
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, conn, nil /* txopts */, func(tx *gosql.Tx) error {
for _, table := range tables {
rows, err := conn.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 conn.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.
sqlDB.ExpectErr(
t, `relation ".+" already exists`,
fmt.Sprintf(`RESTORE %s FROM '%s'`, tableSpec, LocalFoo),
)