-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
show.go
1366 lines (1261 loc) · 45 KB
/
show.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 2018 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 (
"context"
"fmt"
"path"
"sort"
"strings"
"time"
"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/storageccl"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/cloud/cloudprivilege"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descbuilder"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/doctor"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgnotice"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/protoreflect"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/json"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
)
type backupInfoReader interface {
showBackup(
context.Context,
*mon.BoundAccount,
cloud.ExternalStorageFromURIFactory,
backupInfo,
username.SQLUsername,
cloud.KMSEnv,
chan<- tree.Datums,
) error
header() colinfo.ResultColumns
}
type manifestInfoReader struct {
shower backupShower
}
var _ backupInfoReader = manifestInfoReader{}
func (m manifestInfoReader) header() colinfo.ResultColumns {
return m.shower.header
}
// showBackup reads backup info from the manifest, populates the manifestInfoReader,
// calls the backupShower to process the manifest info into datums,
// and pipes the information to the user's sql console via the results channel.
func (m manifestInfoReader) showBackup(
ctx context.Context,
mem *mon.BoundAccount,
_ cloud.ExternalStorageFromURIFactory,
info backupInfo,
_ username.SQLUsername,
kmsEnv cloud.KMSEnv,
resultsCh chan<- tree.Datums,
) error {
ctx, sp := tracing.ChildSpan(ctx, "backupccl.showBackup")
defer sp.Finish()
var memReserved int64
defer func() {
mem.Shrink(ctx, memReserved)
}()
// Ensure that the descriptors in the backup manifests are up to date.
//
// This is necessary in particular for upgrading descriptors with old-style
// foreign keys which are no longer supported.
// If we are restoring a backup with old-style foreign keys, skip over the
// FKs for which we can't resolve the cross-table references. We can't
// display them anyway, because we don't have the referenced table names,
// etc.
err := maybeUpgradeDescriptorsInBackupManifests(info.manifests,
true /* skipFKsWithNoMatchingTable */)
if err != nil {
return err
}
datums, err := m.shower.fn(ctx, info)
if err != nil {
return err
}
for _, row := range datums {
select {
case <-ctx.Done():
return ctx.Err()
case resultsCh <- row:
}
}
return nil
}
type metadataSSTInfoReader struct{}
var _ backupInfoReader = manifestInfoReader{}
func (m metadataSSTInfoReader) header() colinfo.ResultColumns {
return colinfo.ResultColumns{
{Name: "file", Typ: types.String},
{Name: "key", Typ: types.String},
{Name: "detail", Typ: types.Jsonb},
}
}
func (m metadataSSTInfoReader) showBackup(
ctx context.Context,
_ *mon.BoundAccount,
mkStore cloud.ExternalStorageFromURIFactory,
info backupInfo,
user username.SQLUsername,
kmsEnv cloud.KMSEnv,
resultsCh chan<- tree.Datums,
) error {
filename := backupinfo.MetadataSSTName
push := func(_, readable string, value json.JSON) error {
val := tree.DNull
if value != nil {
val = tree.NewDJSON(value)
}
select {
case <-ctx.Done():
return ctx.Err()
case resultsCh <- []tree.Datum{tree.NewDString(filename), tree.NewDString(readable), val}:
return nil
}
}
for _, uri := range info.defaultURIs {
store, err := mkStore(ctx, uri, user)
if err != nil {
return errors.Wrapf(err, "creating external store")
}
defer store.Close()
if err := backupinfo.DebugDumpMetadataSST(ctx, store, filename, info.enc,
kmsEnv, push); err != nil {
return err
}
}
return nil
}
// showBackupPlanHook implements PlanHookFn.
func showBackupPlanHook(
ctx context.Context, stmt tree.Statement, p sql.PlanHookState,
) (sql.PlanHookRowFn, colinfo.ResultColumns, []sql.PlanNode, bool, error) {
backup, ok := stmt.(*tree.ShowBackup)
if !ok {
return nil, nil, nil, false, nil
}
if backup.Path == nil && backup.InCollection != nil {
return showBackupsInCollectionPlanHook(ctx, backup, p)
}
toFn, err := p.TypeAsString(ctx, backup.Path, "SHOW BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
var inColFn func() ([]string, error)
if backup.InCollection != nil {
inColFn, err = p.TypeAsStringArray(ctx, tree.Exprs(backup.InCollection), "SHOW BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
}
expected := map[string]sql.KVStringOptValidate{
backupencryption.BackupOptEncPassphrase: sql.KVStringOptRequireValue,
backupencryption.BackupOptEncKMS: sql.KVStringOptRequireValue,
backupOptWithPrivileges: sql.KVStringOptRequireNoValue,
backupOptAsJSON: sql.KVStringOptRequireNoValue,
backupOptWithDebugIDs: sql.KVStringOptRequireNoValue,
backupOptIncStorage: sql.KVStringOptRequireValue,
backupOptDebugMetadataSST: sql.KVStringOptRequireNoValue,
backupOptEncDir: sql.KVStringOptRequireValue,
backupOptCheckFiles: sql.KVStringOptRequireNoValue,
}
optsFn, err := p.TypeAsStringOpts(ctx, backup.Options, expected)
if err != nil {
return nil, nil, nil, false, err
}
opts, err := optsFn()
if err != nil {
return nil, nil, nil, false, err
}
var infoReader backupInfoReader
if _, dumpSST := opts[backupOptDebugMetadataSST]; dumpSST {
infoReader = metadataSSTInfoReader{}
} else if _, asJSON := opts[backupOptAsJSON]; asJSON {
infoReader = manifestInfoReader{shower: jsonShower}
} else {
var shower backupShower
switch backup.Details {
case tree.BackupRangeDetails:
shower = backupShowerRanges
case tree.BackupFileDetails:
shower = backupShowerFileSetup(backup.InCollection)
case tree.BackupSchemaDetails:
shower = backupShowerDefault(p, true, opts)
case tree.BackupValidateDetails:
shower = backupShowerDoctor
default:
shower = backupShowerDefault(p, false, opts)
}
infoReader = manifestInfoReader{shower: shower}
}
fn := func(ctx context.Context, _ []sql.PlanNode, resultsCh chan<- tree.Datums) error {
ctx, span := tracing.ChildSpan(ctx, stmt.StatementTag())
defer span.Finish()
var (
dest []string
subdir string
)
// For old style show backup, 'to' is the resolved path to the full backup;
// for new SHOW BACKUP, 'to' is the subdirectory.
to, err := toFn()
if err != nil {
return err
}
if inColFn != nil {
subdir = to
dest, err = inColFn()
if err != nil {
return err
}
} else {
dest = append(dest, to)
// Deprecation notice for old `SHOW BACKUP` syntax. Remove this once the syntax is
// deleted in 22.2.
p.BufferClientNotice(ctx,
pgnotice.Newf("The `SHOW BACKUP` syntax without the `IN` keyword will be removed in a"+
" future release. Please switch over to using `SHOW BACKUP FROM <backup> IN"+
" <collection>` to view metadata on a backup collection: %s."+
" Also note that backups created using the `BACKUP TO` syntax may not be showable or"+
" restoreable in the next major version release. Use `BACKUP INTO` instead.",
"https://www.cockroachlabs.com/docs/stable/show-backup.html"))
}
if err := cloudprivilege.CheckDestinationPrivileges(ctx, p, dest); err != nil {
return err
}
fullyResolvedDest := dest
if subdir != "" {
if strings.EqualFold(subdir, backupbase.LatestFileName) {
subdir, err = backupdest.ReadLatestFile(ctx, dest[0],
p.ExecCfg().DistSQLSrv.ExternalStorageFromURI,
p.User())
if err != nil {
return errors.Wrap(err, "read LATEST path")
}
}
fullyResolvedDest, err = backuputils.AppendPaths(dest, subdir)
if err != nil {
return err
}
}
baseStores := make([]cloud.ExternalStorage, len(fullyResolvedDest))
for j := range fullyResolvedDest {
baseStores[j], err = p.ExecCfg().DistSQLSrv.ExternalStorageFromURI(ctx, fullyResolvedDest[j], p.User())
if err != nil {
return errors.Wrapf(err, "make storage")
}
defer baseStores[j].Close()
}
// TODO(msbutler): put encryption resolution in helper function, hopefully shared with RESTORE
// A user that calls SHOW BACKUP <incremental_dir> on an encrypted incremental
// backup will need to pass their full backup's directory to the
// encryption_info_dir parameter because the `ENCRYPTION-INFO` file
// necessary to decode the incremental backup lives in the full backup dir.
encStore := baseStores[0]
if encDir, ok := opts[backupOptEncDir]; ok {
encStore, err = p.ExecCfg().DistSQLSrv.ExternalStorageFromURI(ctx, encDir, p.User())
if err != nil {
return errors.Wrap(err, "make storage")
}
defer encStore.Close()
}
var encryption *jobspb.BackupEncryptionOptions
kmsEnv := backupencryption.MakeBackupKMSEnv(p.ExecCfg().Settings,
&p.ExecCfg().ExternalIODirConfig, p.ExecCfg().DB, p.User(), p.ExecCfg().InternalExecutor)
showEncErr := `If you are running SHOW BACKUP exclusively on an incremental backup,
you must pass the 'encryption_info_dir' parameter that points to the directory of your full backup`
if passphrase, ok := opts[backupencryption.BackupOptEncPassphrase]; ok {
opts, err := backupencryption.ReadEncryptionOptions(ctx, encStore)
if errors.Is(err, backupencryption.ErrEncryptionInfoRead) {
return errors.WithHint(err, showEncErr)
}
if err != nil {
return err
}
encryptionKey := storageccl.GenerateKey([]byte(passphrase), opts[0].Salt)
encryption = &jobspb.BackupEncryptionOptions{
Mode: jobspb.EncryptionMode_Passphrase,
Key: encryptionKey,
}
} else if kms, ok := opts[backupencryption.BackupOptEncKMS]; ok {
opts, err := backupencryption.ReadEncryptionOptions(ctx, encStore)
if errors.Is(err, backupencryption.ErrEncryptionInfoRead) {
return errors.WithHint(err, showEncErr)
}
if err != nil {
return err
}
var defaultKMSInfo *jobspb.BackupEncryptionOptions_KMSInfo
for _, encFile := range opts {
defaultKMSInfo, err = backupencryption.ValidateKMSURIsAgainstFullBackup(
ctx,
[]string{kms},
backupencryption.NewEncryptedDataKeyMapFromProtoMap(encFile.EncryptedDataKeyByKMSMasterKeyID),
&kmsEnv,
)
if err == nil {
break
}
}
if err != nil {
return err
}
encryption = &jobspb.BackupEncryptionOptions{
Mode: jobspb.EncryptionMode_KMS,
KMSInfo: defaultKMSInfo,
}
}
explicitIncPaths := make([]string, 0)
explicitIncPath := opts[backupOptIncStorage]
if len(explicitIncPath) > 0 {
explicitIncPaths = append(explicitIncPaths, explicitIncPath)
if len(dest) > 1 {
return errors.New("SHOW BACKUP on locality aware backups using incremental_location is" +
" not supported yet")
}
}
collection, computedSubdir := backupdest.CollectionAndSubdir(dest[0], subdir)
fullyResolvedIncrementalsDirectory, err := backupdest.ResolveIncrementalsBackupLocation(
ctx,
p.User(),
p.ExecCfg(),
explicitIncPaths,
[]string{collection},
computedSubdir,
)
if err != nil {
if errors.Is(err, cloud.ErrListingUnsupported) {
// We can proceed with base backups here just fine, so log a warning and move on.
// Note that actually _writing_ an incremental backup to this location would fail loudly.
log.Warningf(
ctx, "storage sink %v does not support listing, only showing the base backup", explicitIncPaths)
} else {
return err
}
}
mem := p.ExecCfg().RootMemoryMonitor.MakeBoundAccount()
defer mem.Close(ctx)
var (
info backupInfo
memReserved int64
)
info.collectionURI = dest[0]
info.subdir = computedSubdir
mkStore := p.ExecCfg().DistSQLSrv.ExternalStorageFromURI
incStores, cleanupFn, err := backupdest.MakeBackupDestinationStores(ctx, p.User(), mkStore,
fullyResolvedIncrementalsDirectory)
if err != nil {
return err
}
defer func() {
if err := cleanupFn(); err != nil {
log.Warningf(ctx, "failed to close incremental store: %+v", err)
}
}()
info.defaultURIs, info.manifests, info.localityInfo, memReserved,
err = backupdest.ResolveBackupManifests(
ctx, &mem, baseStores, incStores, mkStore, fullyResolvedDest,
fullyResolvedIncrementalsDirectory, hlc.Timestamp{}, encryption, &kmsEnv, p.User())
defer func() {
mem.Shrink(ctx, memReserved)
}()
if err != nil {
if errors.Is(err, backupinfo.ErrLocalityDescriptor) && subdir == "" {
p.BufferClientNotice(ctx,
pgnotice.Newf("`SHOW BACKUP` using the old syntax ("+
"without the `IN` keyword) on a locality aware backup does not display or validate"+
" data specific to locality aware backups. "+
"Consider using the new `BACKUP INTO` syntax and `SHOW BACKUP"+
" FROM <backup> IN <collection>`"))
} else if errors.Is(err, cloud.ErrFileDoesNotExist) {
latestFileExists, errLatestFile := backupdest.CheckForLatestFileInCollection(ctx, baseStores[0])
if errLatestFile == nil && latestFileExists {
return errors.WithHintf(err, "The specified path is the root of a backup collection. "+
"Use SHOW BACKUPS IN with this path to list all the backup subdirectories in the"+
" collection. SHOW BACKUP can be used with any of these subdirectories to inspect a"+
" backup.")
}
return errors.CombineErrors(err, errLatestFile)
} else {
return err
}
}
// If backup is locality aware, check that user passed at least some localities.
// TODO (msbutler): this is an extremely crude check that the user is
// passing at least as many URIS as there are localities in the backup. This
// check is only meant for the 22.1 backport. Ben is working on a much more
// robust check.
for _, locMap := range info.localityInfo {
if len(locMap.URIsByOriginalLocalityKV) > len(dest) && subdir != "" {
p.BufferClientNotice(ctx,
pgnotice.Newf("The backup contains %d localities; however, "+
"the SHOW BACKUP command contains only %d URIs. To capture all locality aware data, "+
"pass every locality aware URI from the backup", len(locMap.URIsByOriginalLocalityKV),
len(dest)))
}
}
if _, ok := opts[backupOptCheckFiles]; ok {
fileSizes, err := checkBackupFiles(ctx, info,
p.ExecCfg().DistSQLSrv.ExternalStorageFromURI,
p.User())
if err != nil {
return err
}
info.fileSizes = fileSizes
}
if err := infoReader.showBackup(ctx, &mem, mkStore, info, p.User(), &kmsEnv, resultsCh); err != nil {
return err
}
if backup.InCollection == nil {
telemetry.Count("show-backup.deprecated-subdir-syntax")
} else {
telemetry.Count("show-backup.collection")
}
return nil
}
return fn, infoReader.header(), nil, false, nil
}
// checkBackupFiles validates that each SST is in its expected storage location
func checkBackupFiles(
ctx context.Context,
info backupInfo,
storeFactory cloud.ExternalStorageFromURIFactory,
user username.SQLUsername,
) ([][]int64, error) {
const maxMissingFiles = 10
missingFiles := make(map[string]struct{}, maxMissingFiles)
checkLayer := func(layer int) ([]int64, error) {
// TODO (msbutler): Right now, checkLayer opens stores for each backup layer. In 22.2,
// once a backup chain cannot have mixed localities, only create stores for full backup
// and first incremental backup.
defaultStore, err := storeFactory(ctx, info.defaultURIs[layer], user)
if err != nil {
return nil, err
}
localityStores := make(map[string]cloud.ExternalStorage)
defer func() {
if err := defaultStore.Close(); err != nil {
log.Warningf(ctx, "close export storage failed %v", err)
}
for _, store := range localityStores {
if err := store.Close(); err != nil {
log.Warningf(ctx, "close export storage failed %v", err)
}
}
}()
// Check metadata files. Note: we do not check locality aware backup
// metadata files ( prefixed with `backupPartitionDescriptorPrefix`) , as
// they're validated in resolveBackupManifests.
for _, metaFile := range []string{
backupinfo.FileInfoPath,
backupinfo.MetadataSSTName,
backupbase.BackupManifestName + backupinfo.BackupManifestChecksumSuffix} {
if _, err := defaultStore.Size(ctx, metaFile); err != nil {
if metaFile == backupinfo.FileInfoPath || metaFile == backupinfo.MetadataSSTName {
log.Warningf(ctx, `%v not found. This is only relevant if kv.bulkio.write_metadata_sst.enabled = true`, metaFile)
continue
}
return nil, errors.Wrapf(err, "Error checking metadata file %s/%s",
info.defaultURIs[layer], metaFile)
}
}
// Check stat files.
for _, statFile := range info.manifests[layer].StatisticsFilenames {
if _, err := defaultStore.Size(ctx, statFile); err != nil {
return nil, errors.Wrapf(err, "Error checking metadata file %s/%s",
info.defaultURIs[layer], statFile)
}
}
for locality, uri := range info.localityInfo[layer].URIsByOriginalLocalityKV {
store, err := storeFactory(ctx, uri, user)
if err != nil {
return nil, err
}
localityStores[locality] = store
}
// Check all backup SSTs.
fileSizes := make([]int64, len(info.manifests[layer].Files))
for i, f := range info.manifests[layer].Files {
store := defaultStore
uri := info.defaultURIs[layer]
if _, ok := localityStores[f.LocalityKV]; ok {
store = localityStores[f.LocalityKV]
uri = info.localityInfo[layer].URIsByOriginalLocalityKV[f.LocalityKV]
}
sz, err := store.Size(ctx, f.Path)
if err != nil {
uriNoLocality := strings.Split(uri, "?")[0]
missingFile := path.Join(uriNoLocality, f.Path)
if _, ok := missingFiles[missingFile]; !ok {
missingFiles[missingFile] = struct{}{}
if maxMissingFiles == len(missingFiles) {
break
}
}
continue
}
fileSizes[i] = sz
}
return fileSizes, nil
}
manifestFileSizes := make([][]int64, len(info.manifests))
for layer := range info.manifests {
layerFileSizes, err := checkLayer(layer)
if err != nil {
return nil, err
}
if len(missingFiles) == maxMissingFiles {
break
}
manifestFileSizes[layer] = layerFileSizes
}
if len(missingFiles) > 0 {
filesForMsg := make([]string, 0, len(missingFiles))
for file := range missingFiles {
filesForMsg = append(filesForMsg, file)
}
errorMsgPrefix := "The following files are missing from the backup:"
if len(missingFiles) == maxMissingFiles {
errorMsgPrefix = "Multiple files cannot be read from the backup including:"
}
sort.Strings(filesForMsg)
return nil, errors.Newf("%s\n\t%s", errorMsgPrefix, strings.Join(filesForMsg, "\n\t"))
}
return manifestFileSizes, nil
}
type backupInfo struct {
collectionURI string
defaultURIs []string
manifests []backuppb.BackupManifest
subdir string
localityInfo []jobspb.RestoreDetails_BackupLocalityInfo
enc *jobspb.BackupEncryptionOptions
fileSizes [][]int64
}
type backupShower struct {
// header defines the columns of the table printed as output of the show command.
header colinfo.ResultColumns
// fn is the specific implementation of the shower that can either be a default, ranges, files,
// or JSON shower.
fn func(ctx context.Context, info backupInfo) ([]tree.Datums, error)
}
// backupShowerHeaders defines the schema for the table presented to the user.
func backupShowerHeaders(showSchemas bool, opts map[string]string) colinfo.ResultColumns {
baseHeaders := colinfo.ResultColumns{
{Name: "database_name", Typ: types.String},
{Name: "parent_schema_name", Typ: types.String},
{Name: "object_name", Typ: types.String},
{Name: "object_type", Typ: types.String},
{Name: "backup_type", Typ: types.String},
{Name: "start_time", Typ: types.Timestamp},
{Name: "end_time", Typ: types.Timestamp},
{Name: "size_bytes", Typ: types.Int},
{Name: "rows", Typ: types.Int},
{Name: "is_full_cluster", Typ: types.Bool},
{Name: "regions", Typ: types.String},
}
if showSchemas {
baseHeaders = append(baseHeaders, colinfo.ResultColumn{Name: "create_statement", Typ: types.String})
}
if _, shouldShowPrivleges := opts[backupOptWithPrivileges]; shouldShowPrivleges {
baseHeaders = append(baseHeaders, colinfo.ResultColumn{Name: "privileges", Typ: types.String})
baseHeaders = append(baseHeaders, colinfo.ResultColumn{Name: "owner", Typ: types.String})
}
if _, checkFiles := opts[backupOptCheckFiles]; checkFiles {
baseHeaders = append(baseHeaders, colinfo.ResultColumn{Name: "file_bytes", Typ: types.Int})
}
if _, shouldShowIDs := opts[backupOptWithDebugIDs]; shouldShowIDs {
baseHeaders = append(
colinfo.ResultColumns{
baseHeaders[0],
{Name: "database_id", Typ: types.Int},
baseHeaders[1],
{Name: "parent_schema_id", Typ: types.Int},
baseHeaders[2],
{Name: "object_id", Typ: types.Int},
},
baseHeaders[3:]...,
)
}
return baseHeaders
}
func backupShowerDefault(
p sql.PlanHookState, showSchemas bool, opts map[string]string,
) backupShower {
return backupShower{
header: backupShowerHeaders(showSchemas, opts),
fn: func(ctx context.Context, info backupInfo) ([]tree.Datums, error) {
ctx, sp := tracing.ChildSpan(ctx, "backupccl.backupShowerDefault.fn")
defer sp.Finish()
var rows []tree.Datums
for layer, manifest := range info.manifests {
ctx, sp := tracing.ChildSpan(ctx, "backupccl.backupShowerDefault.fn.layer")
// Map database ID to descriptor name.
dbIDToName := make(map[descpb.ID]string)
schemaIDToName := make(map[descpb.ID]string)
typeIDToTypeDescriptor := make(map[descpb.ID]catalog.TypeDescriptor)
schemaIDToName[keys.PublicSchemaIDForBackup] = catconstants.PublicSchemaName
for i := range manifest.Descriptors {
_, db, typ, schema, _ := descpb.FromDescriptor(&manifest.Descriptors[i])
switch {
case db != nil:
if _, ok := dbIDToName[db.ID]; !ok {
dbIDToName[db.ID] = db.Name
}
case typ != nil:
if _, ok := schemaIDToName[typ.ID]; !ok {
typeIDToTypeDescriptor[typ.ID] = typedesc.NewBuilder(typ).BuildImmutableType()
}
case schema != nil:
if _, ok := schemaIDToName[schema.ID]; !ok {
schemaIDToName[schema.ID] = schema.Name
}
}
}
var fileSizes []int64
if len(info.fileSizes) > 0 {
fileSizes = info.fileSizes[layer]
}
tableSizes, err := getTableSizes(ctx, manifest.Files, fileSizes)
if err != nil {
return nil, err
}
backupType := tree.NewDString("full")
if manifest.IsIncremental() {
backupType = tree.NewDString("incremental")
}
start := tree.DNull
end, err := tree.MakeDTimestamp(timeutil.Unix(0, manifest.EndTime.WallTime), time.Nanosecond)
if err != nil {
return nil, err
}
if manifest.StartTime.WallTime != 0 {
start, err = tree.MakeDTimestamp(timeutil.Unix(0, manifest.StartTime.WallTime), time.Nanosecond)
if err != nil {
return nil, err
}
}
var row tree.Datums
for i := range manifest.Descriptors {
descriptor := &manifest.Descriptors[i]
var dbName string
var parentSchemaName string
var descriptorType string
var dbID descpb.ID
var parentSchemaID descpb.ID
createStmtDatum := tree.DNull
dataSizeDatum := tree.DNull
rowCountDatum := tree.DNull
fileSizeDatum := tree.DNull
regionsDatum := tree.DNull
desc := descbuilder.NewBuilder(descriptor).BuildExistingMutable()
descriptorName := desc.GetName()
switch desc := desc.(type) {
case catalog.DatabaseDescriptor:
descriptorType = "database"
if desc.IsMultiRegion() {
regions, err := showRegions(typeIDToTypeDescriptor[desc.GetRegionConfig().RegionEnumID], desc.GetName())
if err != nil {
return nil, errors.Wrapf(err, "cannot generate regions column")
}
regionsDatum = nullIfEmpty(regions)
}
case catalog.SchemaDescriptor:
descriptorType = "schema"
dbName = dbIDToName[desc.GetParentID()]
dbID = desc.GetParentID()
case catalog.TypeDescriptor:
descriptorType = "type"
dbName = dbIDToName[desc.GetParentID()]
dbID = desc.GetParentID()
parentSchemaName = schemaIDToName[desc.GetParentSchemaID()]
parentSchemaID = desc.GetParentSchemaID()
case catalog.FunctionDescriptor:
descriptorType = "function"
dbName = dbIDToName[desc.GetParentID()]
dbID = desc.GetParentID()
parentSchemaName = schemaIDToName[desc.GetParentSchemaID()]
parentSchemaID = desc.GetParentSchemaID()
case catalog.TableDescriptor:
descriptorType = "table"
dbName = dbIDToName[desc.GetParentID()]
dbID = desc.GetParentID()
parentSchemaName = schemaIDToName[desc.GetParentSchemaID()]
parentSchemaID = desc.GetParentSchemaID()
tableSize := tableSizes[desc.GetID()]
dataSizeDatum = tree.NewDInt(tree.DInt(tableSize.rowCount.DataSize))
rowCountDatum = tree.NewDInt(tree.DInt(tableSize.rowCount.Rows))
fileSizeDatum = tree.NewDInt(tree.DInt(tableSize.fileSize))
// Only resolve the table schemas if running `SHOW BACKUP SCHEMAS`.
// In all other cases we discard these results and so it is wasteful
// to construct the SQL representation of the table's schema.
if showSchemas {
displayOptions := sql.ShowCreateDisplayOptions{
FKDisplayMode: sql.OmitMissingFKClausesFromCreate,
IgnoreComments: true,
}
createStmt, err := p.ShowCreate(ctx, dbName, manifest.Descriptors,
tabledesc.NewBuilder(desc.TableDesc()).BuildImmutableTable(), displayOptions)
if err != nil {
// We expect that we might get an error here due to X-DB
// references, which were possible on 20.2 betas and rcs.
log.Errorf(ctx, "error while generating create statement: %+v", err)
}
createStmtDatum = nullIfEmpty(createStmt)
}
default:
descriptorType = "unknown"
}
row = tree.Datums{
nullIfEmpty(dbName),
nullIfEmpty(parentSchemaName),
tree.NewDString(descriptorName),
tree.NewDString(descriptorType),
backupType,
start,
end,
dataSizeDatum,
rowCountDatum,
tree.MakeDBool(manifest.DescriptorCoverage == tree.AllDescriptors),
regionsDatum,
}
if showSchemas {
row = append(row, createStmtDatum)
}
if _, shouldShowPrivileges := opts[backupOptWithPrivileges]; shouldShowPrivileges {
row = append(row, tree.NewDString(showPrivileges(ctx, descriptor)))
owner := desc.GetPrivileges().Owner().SQLIdentifier()
row = append(row, tree.NewDString(owner))
}
if _, checkFiles := opts[backupOptCheckFiles]; checkFiles {
row = append(row, fileSizeDatum)
}
if _, shouldShowIDs := opts[backupOptWithDebugIDs]; shouldShowIDs {
// If showing debug IDs, interleave the IDs with the corresponding object names.
row = append(
tree.Datums{
row[0],
nullIfZero(dbID),
row[1],
nullIfZero(parentSchemaID),
row[2],
nullIfZero(desc.GetID()),
},
row[3:]...,
)
}
rows = append(rows, row)
}
for _, t := range manifest.GetTenants() {
row := tree.Datums{
tree.DNull, // Database
tree.DNull, // Schema
tree.NewDString(roachpb.MakeTenantID(t.ID).String()), // Object Name
tree.NewDString("TENANT"), // Object Type
backupType,
start,
end,
tree.DNull, // DataSize
tree.DNull, // RowCount
tree.DNull, // Descriptor Coverage
tree.DNull, // Regions
}
if showSchemas {
row = append(row, tree.DNull)
}
if _, shouldShowPrivileges := opts[backupOptWithPrivileges]; shouldShowPrivileges {
row = append(row, tree.DNull)
}
if _, checkFiles := opts[backupOptCheckFiles]; checkFiles {
row = append(row, tree.DNull)
}
if _, shouldShowIDs := opts[backupOptWithDebugIDs]; shouldShowIDs {
// If showing debug IDs, interleave the IDs with the corresponding object names.
row = append(
tree.Datums{
row[0],
tree.DNull, // Database ID
row[1],
tree.DNull, // Parent Schema ID
row[2],
tree.NewDInt(tree.DInt(t.ID)), // Object ID
},
row[3:]...,
)
}
rows = append(rows, row)
}
sp.Finish()
}
return rows, nil
},
}
}
type descriptorSize struct {
rowCount roachpb.RowCount
fileSize int64
}
// getLogicalSSTSize gets the total logical bytes stored in each SST. Note that a
// BackupManifest_File identifies a span in an SST and there can be multiple
// spans stored in an SST.
func getLogicalSSTSize(ctx context.Context, files []backuppb.BackupManifest_File) map[string]int64 {
ctx, span := tracing.ChildSpan(ctx, "backupccl.getLogicalSSTSize")
defer span.Finish()
_ = ctx
sstDataSize := make(map[string]int64)
for _, file := range files {
sstDataSize[file.Path] += file.EntryCounts.DataSize
}
return sstDataSize
}
// approximateSpanPhysicalSize approximates the number of bytes written to disk for the span.
func approximateSpanPhysicalSize(
logicalSpanSize int64, logicalSSTSize int64, physicalSSTSize int64,
) int64 {
return int64(float64(physicalSSTSize) * (float64(logicalSpanSize) / float64(logicalSSTSize)))
}
// getTableSizes gathers row and size count for each table in the manifest
func getTableSizes(
ctx context.Context, files []backuppb.BackupManifest_File, fileSizes []int64,
) (map[descpb.ID]descriptorSize, error) {
ctx, span := tracing.ChildSpan(ctx, "backupccl.getTableSizes")
defer span.Finish()
tableSizes := make(map[descpb.ID]descriptorSize)
if len(files) == 0 {
return tableSizes, nil
}
_, tenantID, err := keys.DecodeTenantPrefix(files[0].Span.Key)
if err != nil {
return nil, err
}
showCodec := keys.MakeSQLCodec(tenantID)
logicalSSTSize := getLogicalSSTSize(ctx, files)
for i, file := range files {
// TODO(dan): This assumes each file in the backup only
// contains data from a single table, which is usually but
// not always correct. It does not account for a BACKUP that
// happened to catch a newly created table that hadn't yet
// been split into its own range.
// TODO(msbutler): after handling the todo above, understand whether
// we should return an error if a key does not have tableId. The lack
// of error handling let #77705 sneak by our unit tests.
_, tableID, err := showCodec.DecodeTablePrefix(file.Span.Key)
if err != nil {
continue
}
s := tableSizes[descpb.ID(tableID)]
s.rowCount.Add(file.EntryCounts)
if len(fileSizes) > 0 {
s.fileSize += approximateSpanPhysicalSize(file.EntryCounts.DataSize, logicalSSTSize[file.Path],
fileSizes[i])
}
tableSizes[descpb.ID(tableID)] = s
}
return tableSizes, nil
}
func nullIfEmpty(s string) tree.Datum {
if s == "" {
return tree.DNull
}
return tree.NewDString(s)
}
func nullIfZero(i descpb.ID) tree.Datum {
if i == 0 {
return tree.DNull
}
return tree.NewDInt(tree.DInt(i))
}
// showRegions constructs a string containing the ALTER DATABASE
// commands that create the multi region specifications for a backed up database.
func showRegions(typeDesc catalog.TypeDescriptor, dbname string) (string, error) {
var regionsStringBuilder strings.Builder
if typeDesc == nil {
return "", fmt.Errorf("type descriptor for %s is nil", dbname)
}
primaryRegionName, err := typeDesc.PrimaryRegionName()
if err != nil {
return "", err
}
regionsStringBuilder.WriteString("ALTER DATABASE ")
regionsStringBuilder.WriteString(dbname)
regionsStringBuilder.WriteString(" SET PRIMARY REGION ")
regionsStringBuilder.WriteString("\"" + primaryRegionName.String() + "\"")
regionsStringBuilder.WriteString(";")
regionNames, err := typeDesc.RegionNames()
if err != nil {
return "", err
}
for _, regionName := range regionNames {
if regionName != primaryRegionName {
regionsStringBuilder.WriteString(" ALTER DATABASE ")
regionsStringBuilder.WriteString(dbname)
regionsStringBuilder.WriteString(" ADD REGION ")
regionsStringBuilder.WriteString("\"" + regionName.String() + "\"")
regionsStringBuilder.WriteString(";")
}
}