-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
backup_planning.go
1651 lines (1484 loc) · 52.3 KB
/
backup_planning.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 (
"context"
"crypto"
cryptorand "crypto/rand"
"fmt"
"net/url"
"path"
"sort"
"strconv"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backupresolver"
"github.com/cockroachdb/cockroach/pkg/ccl/storageccl"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/featureflag"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/jobs/jobsprotectedts"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"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/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/covering"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"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/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/interval"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
)
const (
// BackupOptRevisionHistory is the option name for backup with revision history
// exported to cliccl for backup revision inspection
BackupOptRevisionHistory = "revision_history"
backupOptIncludeInterleaves = "include_deprecated_interleaves"
backupOptEncPassphrase = "encryption_passphrase"
backupOptEncKMS = "kms"
backupOptWithPrivileges = "privileges"
backupOptAsJSON = "as_json"
localityURLParam = "COCKROACH_LOCALITY"
defaultLocalityValue = "default"
)
type encryptionMode int
const (
noEncryption encryptionMode = iota
passphrase
kms
)
type tableAndIndex struct {
tableID descpb.ID
indexID descpb.IndexID
}
type backupKMSEnv struct {
settings *cluster.Settings
conf *base.ExternalIODirConfig
}
var _ cloud.KMSEnv = &backupKMSEnv{}
// featureBackupEnabled is used to enable and disable the BACKUP feature.
var featureBackupEnabled = settings.RegisterBoolSetting(
"feature.backup.enabled",
"set to true to enable backups, false to disable; default is true",
featureflag.FeatureFlagEnabledDefault,
).WithPublic()
func (p *backupKMSEnv) ClusterSettings() *cluster.Settings {
return p.settings
}
func (p *backupKMSEnv) KMSConfig() *base.ExternalIODirConfig {
return p.conf
}
type plaintextMasterKeyID string
type hashedMasterKeyID string
type encryptedDataKeyMap struct {
m map[hashedMasterKeyID][]byte
}
func newEncryptedDataKeyMap() *encryptedDataKeyMap {
return &encryptedDataKeyMap{make(map[hashedMasterKeyID][]byte)}
}
func newEncryptedDataKeyMapFromProtoMap(protoDataKeyMap map[string][]byte) *encryptedDataKeyMap {
encMap := &encryptedDataKeyMap{make(map[hashedMasterKeyID][]byte)}
for k, v := range protoDataKeyMap {
encMap.m[hashedMasterKeyID(k)] = v
}
return encMap
}
func (e *encryptedDataKeyMap) addEncryptedDataKey(
masterKeyID plaintextMasterKeyID, encryptedDataKey []byte,
) {
// Hash the master key ID before writing to the map.
hasher := crypto.SHA256.New()
hasher.Write([]byte(masterKeyID))
hash := hasher.Sum(nil)
e.m[hashedMasterKeyID(hash)] = encryptedDataKey
}
func (e *encryptedDataKeyMap) getEncryptedDataKey(
masterKeyID plaintextMasterKeyID,
) ([]byte, error) {
// Hash the master key ID before reading from the map.
hasher := crypto.SHA256.New()
hasher.Write([]byte(masterKeyID))
hash := hasher.Sum(nil)
var encDataKey []byte
var ok bool
if encDataKey, ok = e.m[hashedMasterKeyID(hash)]; !ok {
return nil, errors.New("could not find an entry in the encryptedDataKeyMap")
}
return encDataKey, nil
}
func (e *encryptedDataKeyMap) rangeOverMap(fn func(masterKeyID hashedMasterKeyID, dataKey []byte)) {
for k, v := range e.m {
fn(k, v)
}
}
type sortedIndexIDs []descpb.IndexID
func (s sortedIndexIDs) Less(i, j int) bool {
return s[i] < s[j]
}
func (s sortedIndexIDs) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortedIndexIDs) Len() int {
return len(s)
}
// getLogicallyMergedTableSpans returns all the non-drop index spans of the
// provided table but after merging them so as to minimize the number of spans
// generated. The following rules are used to logically merge the sorted set of
// non-drop index spans:
// - Contiguous index spans are merged.
// - Two non-contiguous index spans are merged if a scan request for the index
// IDs between them does not return any results.
//
// Egs: {/Table/51/1 - /Table/51/2}, {/Table/51/3 - /Table/51/4} => {/Table/51/1 - /Table/51/4}
// provided the dropped index represented by the span
// {/Table/51/2 - /Table/51/3} has been gc'ed.
func getLogicallyMergedTableSpans(
table catalog.TableDescriptor,
added map[tableAndIndex]bool,
codec keys.SQLCodec,
endTime hlc.Timestamp,
checkForKVInBounds func(start, end roachpb.Key, endTime hlc.Timestamp) (bool, error),
) ([]roachpb.Span, error) {
// Spans with adding indexes are not safe to include in the backup since
// they may see non-transactional AddSST traffic. Future incremental backups
// will not have a way of incrementally backing up the data until #62585 is
// resolved.
addingIndexIDs := make(map[descpb.IndexID]struct{})
var publicIndexIDs []descpb.IndexID
allPhysicalIndexOpts := catalog.IndexOpts{DropMutations: true, AddMutations: true}
if err := catalog.ForEachIndex(table, allPhysicalIndexOpts, func(idx catalog.Index) error {
key := tableAndIndex{tableID: table.GetID(), indexID: idx.GetID()}
if added[key] {
return nil
}
added[key] = true
if idx.Public() {
publicIndexIDs = append(publicIndexIDs, idx.GetID())
}
if idx.Adding() {
addingIndexIDs[idx.GetID()] = struct{}{}
}
return nil
}); err != nil {
return nil, err
}
if len(publicIndexIDs) == 0 {
return nil, nil
}
// There is no merging possible with only a single index, short circuit.
if len(publicIndexIDs) == 1 {
return []roachpb.Span{table.IndexSpan(codec, publicIndexIDs[0])}, nil
}
sort.Sort(sortedIndexIDs(publicIndexIDs))
var mergedIndexSpans []roachpb.Span
// mergedSpan starts off as the first span in the set of spans being
// considered for a logical merge.
// The logical span merge algorithm walks over the table's non drop indexes
// using an lhsSpan and rhsSpan (always offset by 1). It checks all index IDs
// between lhsSpan and rhsSpan to look for dropped but non-gced KVs. The
// existence of such a KV indicates that the rhsSpan cannot be included in the
// current set of spans being logically merged, and so we update the
// mergedSpan to encompass the lhsSpan as that is the furthest we can go.
// After recording the new "merged" span, we update mergedSpan to be the
// rhsSpan, and start processing the next logically mergeable span set.
mergedSpan := table.IndexSpan(codec, publicIndexIDs[0])
for curIndex := 0; curIndex < len(publicIndexIDs)-1; curIndex++ {
lhsIndexID := publicIndexIDs[curIndex]
rhsIndexID := publicIndexIDs[curIndex+1]
lhsSpan := table.IndexSpan(codec, lhsIndexID)
rhsSpan := table.IndexSpan(codec, rhsIndexID)
lhsIndex, err := table.FindIndexWithID(lhsIndexID)
if err != nil {
return nil, err
}
rhsIndex, err := table.FindIndexWithID(rhsIndexID)
if err != nil {
return nil, err
}
// If either the lhs or rhs is an interleaved index, we do not attempt to
// perform a logical merge of the spans because the index span for
// interleaved contains the tableID/indexID of the furthest ancestor in
// the interleaved chain.
if lhsIndex.IsInterleaved() || rhsIndex.IsInterleaved() {
mergedIndexSpans = append(mergedIndexSpans, mergedSpan)
mergedSpan = rhsSpan
} else {
var foundDroppedKV bool
// Iterate over all index IDs between the two candidates (lhs and
// rhs) which may be logically merged. These index IDs represent
// non-public (and perhaps dropped) indexes between the two public
// index spans.
for i := lhsIndexID + 1; i < rhsIndexID; i++ {
// If we find an index which has been dropped but not gc'ed, we
// cannot merge the lhs and rhs spans.
foundDroppedKV, err = checkForKVInBounds(lhsSpan.EndKey, rhsSpan.Key, endTime)
if err != nil {
return nil, err
}
// If we find an index that is being added, don't merge the
// spans. We don't want to backup data that is being backfilled
// until the backfill is complete. Even if the backfill has not
// started yet and there is not data we should not include this
// span in the spans to back up since we want these spans to
// appear as introduced when the index becomes PUBLIC.
// The indexes will appear in introduced spans because indexes
// will never go from PUBLIC to ADDING.
_, foundAddingIndex := addingIndexIDs[i]
if foundDroppedKV || foundAddingIndex {
mergedSpan.EndKey = lhsSpan.EndKey
mergedIndexSpans = append(mergedIndexSpans, mergedSpan)
mergedSpan = rhsSpan
break
}
}
}
// The loop will terminate after this iteration and so we must update the
// current mergedSpan to encompass the last element in the indexIDs
// slice as well.
if curIndex == len(publicIndexIDs)-2 {
mergedSpan.EndKey = rhsSpan.EndKey
mergedIndexSpans = append(mergedIndexSpans, mergedSpan)
}
}
return mergedIndexSpans, nil
}
// spansForAllTableIndexes returns non-overlapping spans for every index and
// table passed in. They would normally overlap if any of them are interleaved.
// The outputted spans are merged as described by the method
// getLogicallyMergedTableSpans, so as to optimize the size/number of the spans
// we BACKUP and lay protected ts records for.
func spansForAllTableIndexes(
ctx context.Context,
execCfg *sql.ExecutorConfig,
endTime hlc.Timestamp,
tables []catalog.TableDescriptor,
revs []BackupManifest_DescriptorRevision,
) ([]roachpb.Span, error) {
added := make(map[tableAndIndex]bool, len(tables))
sstIntervalTree := interval.NewTree(interval.ExclusiveOverlapper)
var mergedIndexSpans []roachpb.Span
var err error
// checkForKVInBounds issues a scan request between start and end at endTime,
// and returns true if a non-nil result is returned.
checkForKVInBounds := func(start, end roachpb.Key, endTime hlc.Timestamp) (bool, error) {
var foundKV bool
err := execCfg.DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
txn.SetFixedTimestamp(ctx, endTime)
res, err := txn.Scan(ctx, start, end, 1 /* maxRows */)
if err != nil {
return err
}
foundKV = len(res) != 0
return nil
})
return foundKV, err
}
for _, table := range tables {
mergedIndexSpans, err = getLogicallyMergedTableSpans(table, added, execCfg.Codec, endTime,
checkForKVInBounds)
if err != nil {
return nil, err
}
for _, indexSpan := range mergedIndexSpans {
if err := sstIntervalTree.Insert(intervalSpan(indexSpan), false); err != nil {
panic(errors.NewAssertionErrorWithWrappedErrf(err, "IndexSpan"))
}
}
}
// If there are desc revisions, ensure that we also add any index spans
// in them that we didn't already get above e.g. indexes or tables that are
// not in latest because they were dropped during the time window in question.
for _, rev := range revs {
// If the table was dropped during the last interval, it will have
// at least 2 revisions, and the first one should have the table in a PUBLIC
// state. We want (and do) ignore tables that have been dropped for the
// entire interval. DROPPED tables should never later become PUBLIC.
rawTbl, _, _, _ := descpb.FromDescriptor(rev.Desc)
if rawTbl != nil && rawTbl.State == descpb.DescriptorState_PUBLIC {
tbl := tabledesc.NewBuilder(rawTbl).BuildImmutableTable()
revSpans, err := getLogicallyMergedTableSpans(tbl, added, execCfg.Codec, rev.Time,
checkForKVInBounds)
if err != nil {
return nil, err
}
mergedIndexSpans = append(mergedIndexSpans, revSpans...)
for _, indexSpan := range mergedIndexSpans {
if err := sstIntervalTree.Insert(intervalSpan(indexSpan), false); err != nil {
panic(errors.NewAssertionErrorWithWrappedErrf(err, "IndexSpan"))
}
}
}
}
var spans []roachpb.Span
_ = sstIntervalTree.Do(func(r interval.Interface) bool {
spans = append(spans, roachpb.Span{
Key: roachpb.Key(r.Range().Start),
EndKey: roachpb.Key(r.Range().End),
})
return false
})
// Attempt to merge any contiguous spans generated from the tables and revs.
// No need to check if the spans are distinct, since some of the merged
// indexes may overlap between different revisions of the same descriptor.
mergedSpans, _ := roachpb.MergeSpans(spans)
knobs := execCfg.BackupRestoreTestingKnobs
if knobs != nil && knobs.CaptureResolvedTableDescSpans != nil {
knobs.CaptureResolvedTableDescSpans(mergedSpans)
}
return mergedSpans, nil
}
func getLocalityAndBaseURI(uri, appendPath string) (string, string, error) {
parsedURI, err := url.Parse(uri)
if err != nil {
return "", "", err
}
q := parsedURI.Query()
localityKV := q.Get(localityURLParam)
// Remove the backup locality parameter.
q.Del(localityURLParam)
parsedURI.RawQuery = q.Encode()
if appendPath != "" {
parsedURI.Path = path.Join(parsedURI.Path, appendPath)
}
baseURI := parsedURI.String()
return localityKV, baseURI, nil
}
// getURIsByLocalityKV takes a slice of URIs for a single (possibly partitioned)
// backup, and returns the default backup destination URI and a map of all other
// URIs by locality KV, appending appendPath to the path component of both the
// default URI and all the locality URIs. The URIs in the result do not include
// the COCKROACH_LOCALITY parameter.
func getURIsByLocalityKV(to []string, appendPath string) (string, map[string]string, error) {
urisByLocalityKV := make(map[string]string)
if len(to) == 1 {
localityKV, baseURI, err := getLocalityAndBaseURI(to[0], appendPath)
if err != nil {
return "", nil, err
}
if localityKV != "" && localityKV != defaultLocalityValue {
return "", nil, errors.Errorf("%s %s is invalid for a single BACKUP location",
localityURLParam, localityKV)
}
return baseURI, urisByLocalityKV, nil
}
var defaultURI string
for _, uri := range to {
localityKV, baseURI, err := getLocalityAndBaseURI(uri, appendPath)
if err != nil {
return "", nil, err
}
if localityKV == "" {
return "", nil, errors.Errorf(
"multiple URLs are provided for partitioned BACKUP, but %s is not specified",
localityURLParam,
)
}
if localityKV == defaultLocalityValue {
if defaultURI != "" {
return "", nil, errors.Errorf("multiple default URLs provided for partition backup")
}
defaultURI = baseURI
} else {
kv := roachpb.Tier{}
if err := kv.FromString(localityKV); err != nil {
return "", nil, errors.Wrap(err, "failed to parse backup locality")
}
if _, ok := urisByLocalityKV[localityKV]; ok {
return "", nil, errors.Errorf("duplicate URIs for locality %s", localityKV)
}
urisByLocalityKV[localityKV] = baseURI
}
}
if defaultURI == "" {
return "", nil, errors.Errorf("no default URL provided for partitioned backup")
}
return defaultURI, urisByLocalityKV, nil
}
func resolveOptionsForBackupJobDescription(
opts tree.BackupOptions, kmsURIs []string,
) (tree.BackupOptions, error) {
if opts.IsDefault() {
return opts, nil
}
newOpts := tree.BackupOptions{
CaptureRevisionHistory: opts.CaptureRevisionHistory,
Detached: opts.Detached,
}
if opts.EncryptionPassphrase != nil {
newOpts.EncryptionPassphrase = tree.NewDString("redacted")
}
for _, uri := range kmsURIs {
redactedURI, err := cloudimpl.RedactKMSURI(uri)
if err != nil {
return tree.BackupOptions{}, err
}
newOpts.EncryptionKMSURI = append(newOpts.EncryptionKMSURI, tree.NewDString(redactedURI))
}
return newOpts, nil
}
// GetRedactedBackupNode returns a copy of the argument `backup`, but with all
// the secret information redacted.
func GetRedactedBackupNode(
backup *tree.Backup,
to []string,
incrementalFrom []string,
kmsURIs []string,
resolvedSubdir string,
hasBeenPlanned bool,
) (*tree.Backup, error) {
b := &tree.Backup{
AsOf: backup.AsOf,
Targets: backup.Targets,
Nested: backup.Nested,
}
// We set Subdir to the directory resolved during BACKUP planning.
//
// - For `BACKUP INTO 'subdir' IN...` this would be the specified subdir
// (with a single / prefix).
// - For `BACKUP INTO LATEST...` this would be the sub-directory pointed to by
// LATEST, where we are appending an incremental BACKUP.
// - For `BACKUP INTO x` this would be the sub-directory we have selected to
// write the BACKUP to.
if b.Nested && hasBeenPlanned {
b.Subdir = tree.NewDString(resolvedSubdir)
}
for _, t := range to {
sanitizedTo, err := cloudimpl.SanitizeExternalStorageURI(t, nil /* extraParams */)
if err != nil {
return nil, err
}
b.To = append(b.To, tree.NewDString(sanitizedTo))
}
for _, from := range incrementalFrom {
sanitizedFrom, err := cloudimpl.SanitizeExternalStorageURI(from, nil /* extraParams */)
if err != nil {
return nil, err
}
b.IncrementalFrom = append(b.IncrementalFrom, tree.NewDString(sanitizedFrom))
}
resolvedOpts, err := resolveOptionsForBackupJobDescription(backup.Options, kmsURIs)
if err != nil {
return nil, err
}
b.Options = resolvedOpts
return b, nil
}
func backupJobDescription(
p sql.PlanHookState,
backup *tree.Backup,
to []string,
incrementalFrom []string,
kmsURIs []string,
resolvedSubdir string,
) (string, error) {
b, err := GetRedactedBackupNode(backup, to, incrementalFrom, kmsURIs, resolvedSubdir,
true /* hasBeenPlanned */)
if err != nil {
return "", err
}
ann := p.ExtendedEvalContext().Annotations
return tree.AsStringWithFQNames(b, ann), nil
}
// validateKMSURIsAgainstFullBackup ensures that the KMS URIs provided to an
// incremental BACKUP are a subset of those used during the full BACKUP. It does
// this by ensuring that the KMS master key ID of each KMS URI specified during
// the incremental BACKUP can be found in the map written to `encryption-info`
// during a base BACKUP.
//
// The method also returns the KMSInfo to be used for all subsequent
// encryption/decryption operations during this BACKUP. By default it is the
// first KMS URI passed during the incremental BACKUP.
func validateKMSURIsAgainstFullBackup(
kmsURIs []string, kmsMasterKeyIDToDataKey *encryptedDataKeyMap, kmsEnv cloud.KMSEnv,
) (*jobspb.BackupEncryptionOptions_KMSInfo, error) {
var defaultKMSInfo *jobspb.BackupEncryptionOptions_KMSInfo
for _, kmsURI := range kmsURIs {
kms, err := cloud.KMSFromURI(kmsURI, kmsEnv)
if err != nil {
return nil, err
}
defer func() {
_ = kms.Close()
}()
// Depending on the KMS specific implementation, this may or may not contact
// the remote KMS.
id, err := kms.MasterKeyID()
if err != nil {
return nil, err
}
encryptedDataKey, err := kmsMasterKeyIDToDataKey.getEncryptedDataKey(plaintextMasterKeyID(id))
if err != nil {
return nil,
errors.Wrap(err,
"one of the provided URIs was not used when encrypting the base BACKUP")
}
if defaultKMSInfo == nil {
defaultKMSInfo = &jobspb.BackupEncryptionOptions_KMSInfo{
Uri: kmsURI,
EncryptedDataKey: encryptedDataKey,
}
}
}
return defaultKMSInfo, nil
}
// annotatedBackupStatement is a tree.Backup, optionally
// annotated with the scheduling information.
type annotatedBackupStatement struct {
*tree.Backup
*jobs.CreatedByInfo
}
// backupEncryptionParams is a structured representation of the encryption
// options that the user provided in the backup statement.
type backupEncryptionParams struct {
encryptMode encryptionMode
kmsURIs []string
encryptionPassphrase []byte
kmsEnv *backupKMSEnv
}
func getBackupStatement(stmt tree.Statement) *annotatedBackupStatement {
switch backup := stmt.(type) {
case *annotatedBackupStatement:
return backup
case *tree.Backup:
return &annotatedBackupStatement{Backup: backup}
default:
return nil
}
}
func checkPrivilegesForBackup(
ctx context.Context,
backupStmt *annotatedBackupStatement,
p sql.PlanHookState,
targetDescs []catalog.Descriptor,
to []string,
) error {
hasAdmin, err := p.HasAdminRole(ctx)
if err != nil {
return err
}
if hasAdmin {
return nil
}
// Do not allow full cluster backups.
if backupStmt.Coverage() == tree.AllDescriptors {
return pgerror.Newf(
pgcode.InsufficientPrivilege,
"only users with the admin role are allowed to perform full cluster backups")
}
// Do not allow tenant backups.
if backupStmt.Targets != nil && backupStmt.Targets.Tenant != (roachpb.TenantID{}) {
return pgerror.Newf(
pgcode.InsufficientPrivilege,
"only users with the admin role can perform BACKUP TENANT")
}
for _, desc := range targetDescs {
switch desc := desc.(type) {
case catalog.DatabaseDescriptor, catalog.TableDescriptor:
if err := p.CheckPrivilege(ctx, desc, privilege.SELECT); err != nil {
return err
}
case catalog.TypeDescriptor, catalog.SchemaDescriptor:
if err := p.CheckPrivilege(ctx, desc, privilege.USAGE); err != nil {
return err
}
}
}
knobs := p.ExecCfg().BackupRestoreTestingKnobs
if knobs != nil && knobs.AllowImplicitAccess {
return nil
}
// Check that none of the destinations require an admin role.
for _, uri := range to {
hasExplicitAuth, uriScheme, err := cloud.AccessIsWithExplicitAuth(uri)
if err != nil {
return err
}
if !hasExplicitAuth {
return pgerror.Newf(
pgcode.InsufficientPrivilege,
"only users with the admin role are allowed to BACKUP to the specified %s URI",
uriScheme)
}
}
return nil
}
// backupPlanHook implements PlanHookFn.
func backupPlanHook(
ctx context.Context, stmt tree.Statement, p sql.PlanHookState,
) (sql.PlanHookRowFn, colinfo.ResultColumns, []sql.PlanNode, bool, error) {
backupStmt := getBackupStatement(stmt)
if backupStmt == nil {
return nil, nil, nil, false, nil
}
if err := featureflag.CheckEnabled(
ctx,
p.ExecCfg(),
featureBackupEnabled,
"BACKUP",
); err != nil {
return nil, nil, nil, false, err
}
var err error
subdirFn := func() (string, error) { return "", nil }
if backupStmt.Subdir != nil {
subdirFn, err = p.TypeAsString(ctx, backupStmt.Subdir, "BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
}
toFn, err := p.TypeAsStringArray(ctx, tree.Exprs(backupStmt.To), "BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
incrementalFromFn, err := p.TypeAsStringArray(ctx, backupStmt.IncrementalFrom, "BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
encryptionParams := backupEncryptionParams{}
var pwFn func() (string, error)
encryptionParams.encryptMode = noEncryption
if backupStmt.Options.EncryptionPassphrase != nil {
fn, err := p.TypeAsString(ctx, backupStmt.Options.EncryptionPassphrase, "BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
pwFn = fn
encryptionParams.encryptMode = passphrase
}
var kmsFn func() ([]string, *backupKMSEnv, error)
if backupStmt.Options.EncryptionKMSURI != nil {
if encryptionParams.encryptMode != noEncryption {
return nil, nil, nil, false,
errors.New("cannot have both encryption_passphrase and kms option set")
}
fn, err := p.TypeAsStringArray(ctx, tree.Exprs(backupStmt.Options.EncryptionKMSURI),
"BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
kmsFn = func() ([]string, *backupKMSEnv, error) {
res, err := fn()
if err == nil {
return res, &backupKMSEnv{
settings: p.ExecCfg().Settings,
conf: &p.ExecCfg().ExternalIODirConfig,
}, nil
}
return nil, nil, err
}
encryptionParams.encryptMode = kms
}
fn := func(ctx context.Context, _ []sql.PlanNode, resultsCh chan<- tree.Datums) error {
// TODO(dan): Move this span into sql.
ctx, span := tracing.ChildSpan(ctx, stmt.StatementTag())
defer span.Finish()
if !(p.ExtendedEvalContext().TxnImplicit || backupStmt.Options.Detached) {
return errors.Errorf("BACKUP cannot be used inside a transaction without DETACHED option")
}
var isEnterprise bool
requireEnterprise := func(feature string) error {
if isEnterprise {
return nil
}
if err := utilccl.CheckEnterpriseEnabled(
p.ExecCfg().Settings, p.ExecCfg().ClusterID(), p.ExecCfg().Organization(),
fmt.Sprintf("BACKUP with %s", feature),
); err != nil {
return err
}
isEnterprise = true
return nil
}
subdir, err := subdirFn()
if err != nil {
return err
}
to, err := toFn()
if err != nil {
return err
}
if len(to) > 1 {
if err := requireEnterprise("partitioned destinations"); err != nil {
return err
}
}
incrementalFrom, err := incrementalFromFn()
if err != nil {
return err
}
endTime := p.ExecCfg().Clock.Now()
if backupStmt.AsOf.Expr != nil {
var err error
if endTime, err = p.EvalAsOfTimestamp(ctx, backupStmt.AsOf); err != nil {
return err
}
}
mvccFilter := MVCCFilter_Latest
if backupStmt.Options.CaptureRevisionHistory {
if err := requireEnterprise("revision_history"); err != nil {
return err
}
mvccFilter = MVCCFilter_All
}
var targetDescs []catalog.Descriptor
var completeDBs []descpb.ID
switch backupStmt.Coverage() {
case tree.RequestedDescriptors:
var err error
targetDescs, completeDBs, err = backupresolver.ResolveTargetsToDescriptors(ctx, p, endTime, backupStmt.Targets)
if err != nil {
return errors.Wrap(err, "failed to resolve targets specified in the BACKUP stmt")
}
case tree.AllDescriptors:
allDescs, err := backupresolver.LoadAllDescs(ctx, p.ExecCfg().Codec, p.ExecCfg().DB, endTime)
if err != nil {
return err
}
targetDescs, completeDBs, err = fullClusterTargetsBackup(allDescs)
if err != nil {
return err
}
if len(targetDescs) == 0 {
return errors.New("no descriptors available to backup at selected time")
}
default:
return errors.AssertionFailedf("unexpected descriptor coverage %v", backupStmt.Coverage())
}
if !backupStmt.Options.IncludeDeprecatedInterleaves {
for _, desc := range targetDescs {
if table, ok := desc.(catalog.TableDescriptor); ok {
if table.IsInterleaved() {
return errors.Errorf("interleaved tables are deprecated and backups containing interleaved tables will not be able to be RESTORE'd by future versions -- use option %q to backup interleaved tables anyway %q", backupOptIncludeInterleaves, table.TableDesc().Name)
}
}
}
}
// Check BACKUP privileges.
err = checkPrivilegesForBackup(ctx, backupStmt, p, targetDescs, to)
if err != nil {
return err
}
var tables []catalog.TableDescriptor
statsFiles := make(map[descpb.ID]string)
for _, desc := range targetDescs {
switch desc := desc.(type) {
case catalog.TableDescriptor:
tables = append(tables, desc)
// TODO (anzo): look into the tradeoffs of having all objects in the array to be in the same file,
// vs having each object in a separate file, or somewhere in between.
statsFiles[desc.GetID()] = backupStatisticsFileName
}
}
if err := ensureInterleavesIncluded(tables); err != nil {
return err
}
if err := validateMultiRegionBackup(backupStmt, targetDescs, tables); err != nil {
return err
}
makeCloudStorage := p.ExecCfg().DistSQLSrv.ExternalStorageFromURI
switch encryptionParams.encryptMode {
case passphrase:
pw, err := pwFn()
if err != nil {
return err
}
if err := requireEnterprise("encryption"); err != nil {
return err
}
encryptionParams.encryptionPassphrase = []byte(pw)
case kms:
encryptionParams.kmsURIs, encryptionParams.kmsEnv, err = kmsFn()
if err != nil {
return err
}
if err := requireEnterprise("encryption"); err != nil {
return err
}
}
defaultURI, urisByLocalityKV, err := getURIsByLocalityKV(to, "")
if err != nil {
return err
}
// TODO(pbardea): Refactor (defaultURI and urisByLocalityKV) pairs into a
// backupDestination struct.
collectionURI, defaultURI, resolvedSubdir, urisByLocalityKV, prevs, err :=
resolveDest(ctx, p.User(), backupStmt.Nested, backupStmt.AppendToLatest, defaultURI,
urisByLocalityKV, makeCloudStorage, endTime, to, incrementalFrom, subdir)
if err != nil {
return err
}
prevBackups, encryptionOptions, err := fetchPreviousBackups(ctx, p.User(), makeCloudStorage, prevs,
encryptionParams)
if err != nil {
return err
}
if len(prevBackups) > 0 {
baseManifest := prevBackups[0]
if baseManifest.DescriptorCoverage == tree.AllDescriptors &&
backupStmt.Coverage() != tree.AllDescriptors {
return errors.Errorf("cannot append a backup of specific tables or databases to a cluster backup")
}
}
clusterID := p.ExecCfg().ClusterID()
for i := range prevBackups {
// IDs are how we identify tables, and those are only meaningful in the
// context of their own cluster, so we need to ensure we only allow
// incremental previous backups that we created.
if fromCluster := prevBackups[i].ClusterID; !fromCluster.Equal(clusterID) {
return errors.Newf("previous BACKUP belongs to cluster %s", fromCluster.String())
}
}
var startTime hlc.Timestamp
var newSpans roachpb.Spans
if len(prevBackups) > 0 {
if err := requireEnterprise("incremental"); err != nil {
return err
}
startTime = prevBackups[len(prevBackups)-1].EndTime
}
var priorIDs map[descpb.ID]descpb.ID
var revs []BackupManifest_DescriptorRevision
if mvccFilter == MVCCFilter_All {
priorIDs = make(map[descpb.ID]descpb.ID)
revs, err = getRelevantDescChanges(ctx, p.ExecCfg().Codec, p.ExecCfg().DB, startTime, endTime, targetDescs, completeDBs, priorIDs, backupStmt.Coverage())
if err != nil {
return err
}
}
var spans []roachpb.Span
var tenantRows []tree.Datums
if backupStmt.Targets != nil && backupStmt.Targets.Tenant != (roachpb.TenantID{}) {
if !p.ExecCfg().Codec.ForSystemTenant() {
return pgerror.Newf(pgcode.InsufficientPrivilege, "only the system tenant can backup other tenants")
}
tenID := backupStmt.Targets.Tenant
id := backupStmt.Targets.Tenant.ToUint64()
ds, err := p.ExecCfg().InternalExecutor.QueryRow(
ctx, "backup-lookup-tenant", p.ExtendedEvalContext().Txn,
`SELECT id, active, info FROM system.tenants WHERE id = $1`, id,
)
if err != nil {
return err
}
if ds == nil {
return errors.Errorf("tenant %s does not exist", tenID)
}
if !tree.MustBeDBool(ds[1]) {
return errors.Errorf("tenant %d is not active", id)
}