-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
backup_planning.go
1789 lines (1621 loc) · 58.7 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 (
"bytes"
"context"
"fmt"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
"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/cloud"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"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/kv/kvserver/protectedts/ptpb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/scheduledjobs"
"github.com/cockroachdb/cockroach/pkg/security/username"
"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/descbuilder"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgnotice"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"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/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
pbtypes "github.com/gogo/protobuf/types"
)
const (
backupOptRevisionHistory = "revision_history"
backupOptEncPassphrase = "encryption_passphrase"
backupOptEncKMS = "kms"
backupOptWithPrivileges = "privileges"
backupOptAsJSON = "as_json"
backupOptWithDebugIDs = "debug_ids"
backupOptIncStorage = "incremental_location"
localityURLParam = "COCKROACH_LOCALITY"
defaultLocalityValue = "default"
backupOptDebugMetadataSST = "debug_dump_metadata_sst"
backupOptEncDir = "encryption_info_dir"
backupOptCheckFiles = "check_files"
)
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(
settings.TenantWritable,
"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
hashedMasterKeyID string
encryptedDataKeyMap struct {
m map[hashedMasterKeyID][]byte
}
)
// featureFullBackupUserSubdir, when true, will create a full backup at a user
// specified subdirectory if no backup already exists at that subdirectory. As
// of 22.1, this feature is default disabled, and will be totally disabled by 22.2.
var featureFullBackupUserSubdir = settings.RegisterBoolSetting(
settings.TenantWritable,
"bulkio.backup.deprecated_full_backup_with_subdir.enabled",
"when true, a backup command with a user specified subdirectory will create a full backup at"+
" the subdirectory if no backup already exists at that subdirectory.",
false,
).WithPublic()
// getPublicIndexTableSpans returns all the public index spans of the
// provided table.
func getPublicIndexTableSpans(
table catalog.TableDescriptor, added map[tableAndIndex]bool, codec keys.SQLCodec,
) ([]roachpb.Span, error) {
publicIndexSpans := make([]roachpb.Span, 0)
if err := catalog.ForEachActiveIndex(table, func(idx catalog.Index) error {
key := tableAndIndex{tableID: table.GetID(), indexID: idx.GetID()}
if added[key] {
return nil
}
added[key] = true
publicIndexSpans = append(publicIndexSpans, table.IndexSpan(codec, idx.GetID()))
return nil
}); err != nil {
return nil, err
}
return publicIndexSpans, nil
}
// spansForAllTableIndexes returns non-overlapping spans for every index and
// table passed in. They would normally overlap if any of them are interleaved.
// Overlapping index spans are merged so as to optimize the size/number of the
// spans we BACKUP and lay protected ts records for.
func spansForAllTableIndexes(
execCfg *sql.ExecutorConfig,
tables []catalog.TableDescriptor,
revs []BackupManifest_DescriptorRevision,
) ([]roachpb.Span, error) {
added := make(map[tableAndIndex]bool, len(tables))
sstIntervalTree := interval.NewTree(interval.ExclusiveOverlapper)
var publicIndexSpans []roachpb.Span
var err error
for _, table := range tables {
publicIndexSpans, err = getPublicIndexTableSpans(table, added, execCfg.Codec)
if err != nil {
return nil, err
}
for _, indexSpan := range publicIndexSpans {
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.Public() {
tbl := tabledesc.NewBuilder(rawTbl).BuildImmutableTable()
revSpans, err := getPublicIndexTableSpans(tbl, added, execCfg.Codec)
if err != nil {
return nil, err
}
publicIndexSpans = append(publicIndexSpans, revSpans...)
for _, indexSpan := range publicIndexSpans {
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()
parsedURI.Path = JoinURLPath(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,
) (defaultURI string, urisByLocalityKV map[string]string, err 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
}
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, incrementalStorage []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")
}
var err error
// TODO(msbutler): use cloud.RedactKMSURI(uri) here instead?
newOpts.EncryptionKMSURI, err = sanitizeURIList(kmsURIs)
if err != nil {
return tree.BackupOptions{}, err
}
newOpts.IncrementalStorage, err = sanitizeURIList(incrementalStorage)
if err != nil {
return tree.BackupOptions{}, err
}
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,
incrementalStorage []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)
}
var err error
b.To, err = sanitizeURIList(to)
if err != nil {
return nil, err
}
b.IncrementalFrom, err = sanitizeURIList(incrementalFrom)
if err != nil {
return nil, err
}
resolvedOpts, err := resolveOptionsForBackupJobDescription(backup.Options, kmsURIs,
incrementalStorage)
if err != nil {
return nil, err
}
b.Options = resolvedOpts
return b, nil
}
// sanitizeURIList sanitizes a list of URIS in order to build an AST
func sanitizeURIList(uris []string) ([]tree.Expr, error) {
var sanitizedURIs []tree.Expr
for _, uri := range uris {
sanitizedURI, err := cloud.SanitizeExternalStorageURI(uri, nil /* extraParams */)
if err != nil {
return nil, err
}
sanitizedURIs = append(sanitizedURIs, tree.NewDString(sanitizedURI))
}
return sanitizedURIs, nil
}
func backupJobDescription(
p sql.PlanHookState,
backup *tree.Backup,
to []string,
incrementalFrom []string,
kmsURIs []string,
resolvedSubdir string,
incrementalStorage []string,
) (string, error) {
b, err := GetRedactedBackupNode(backup, to, incrementalFrom, kmsURIs,
resolvedSubdir, incrementalStorage, true /* hasBeenPlanned */)
if err != nil {
return "", err
}
ann := p.ExtendedEvalContext().Annotations
return tree.AsStringWithFQNames(b, ann), nil
}
// annotatedBackupStatement is a tree.Backup, optionally
// annotated with the scheduling information.
type annotatedBackupStatement struct {
*tree.Backup
*jobs.CreatedByInfo
}
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.TenantID.IsSet() {
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:
if connectErr := p.CheckPrivilege(ctx, desc, privilege.CONNECT); connectErr != nil {
// SELECT is being deprecated as privilege on Databases in 22.1.
// In the meanwhile, we still allow backup if the user has SELECT.
// TODO(richardjcai): Remove this check for SELECT in 22.1.
if selectErr := p.CheckPrivilege(ctx, desc, privilege.SELECT); selectErr != nil {
// Return the connectErr as we want users to grant CONNECT to perform
// this backup and not select.
return connectErr
}
}
case 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
}
}
}
if p.ExecCfg().ExternalIODirConfig.EnableNonAdminImplicitAndArbitraryOutbound {
return nil
}
// Check that none of the destinations require an admin role.
for _, uri := range to {
conf, err := cloud.ExternalStorageConfFromURI(uri, p.User())
if err != nil {
return err
}
if !conf.AccessIsWithExplicitAuth() {
return pgerror.Newf(
pgcode.InsufficientPrivilege,
"only users with the admin role are allowed to BACKUP to the specified %s URI",
conf.Provider.String())
}
}
return nil
}
func requireEnterprise(execCfg *sql.ExecutorConfig, feature string) error {
if err := utilccl.CheckEnterpriseEnabled(
execCfg.Settings, execCfg.LogicalClusterID(), execCfg.Organization(),
fmt.Sprintf("BACKUP with %s", feature),
); err != nil {
return err
}
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
}
// Deprecation notice for `BACKUP TO` syntax. Remove this once the syntax is
// deleted in 22.2.
if !backupStmt.Nested {
p.BufferClientNotice(ctx,
pgnotice.Newf("The `BACKUP TO` syntax will be removed in a future release, please"+
" switch over to using `BACKUP INTO` to create a backup collection: %s. "+
"Backups created using the `BACKUP TO` syntax may not be restoreable in the next major version release.",
"https://www.cockroachlabs.com/docs/stable/backup.html#considerations"))
}
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
}
incToFn, err := p.TypeAsStringArray(ctx, tree.Exprs(backupStmt.Options.IncrementalStorage),
"BACKUP")
if err != nil {
return nil, nil, nil, false, err
}
encryptionParams := jobspb.BackupEncryptionOptions{Mode: jobspb.EncryptionMode_None}
var pwFn func() (string, error)
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.Mode = jobspb.EncryptionMode_Passphrase
}
var kmsFn func() ([]string, error)
if backupStmt.Options.EncryptionKMSURI != nil {
if encryptionParams.Mode != jobspb.EncryptionMode_None {
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, error) {
res, err := fn()
if err == nil {
return res, nil
}
return nil, err
}
encryptionParams.Mode = jobspb.EncryptionMode_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().TxnIsSingleStmt || backupStmt.Options.Detached) {
return errors.Errorf("BACKUP cannot be used inside a multi-statement transaction without DETACHED option")
}
subdir, err := subdirFn()
if err != nil {
return err
}
to, err := toFn()
if err != nil {
return err
}
if len(to) > 1 {
if err := requireEnterprise(p.ExecCfg(), "partitioned destinations"); err != nil {
return err
}
}
incrementalFrom, err := incrementalFromFn()
if err != nil {
return err
}
incrementalStorage, err := incToFn()
if err != nil {
return err
}
if !backupStmt.Nested && len(incrementalStorage) > 0 {
return errors.New("incremental_location option not supported with `BACKUP TO` syntax")
}
if len(incrementalStorage) > 0 && (len(incrementalStorage) != len(to)) {
return errors.New("the incremental_location option must contain the same number of locality" +
" aware URIs as the full backup destination")
}
endTime := p.ExecCfg().Clock.Now()
if backupStmt.AsOf.Expr != nil {
asOf, err := p.EvalAsOfTimestamp(ctx, backupStmt.AsOf)
if err != nil {
return err
}
endTime = asOf.Timestamp
}
switch encryptionParams.Mode {
case jobspb.EncryptionMode_Passphrase:
pw, err := pwFn()
if err != nil {
return err
}
if err := requireEnterprise(p.ExecCfg(), "encryption"); err != nil {
return err
}
encryptionParams.RawPassphrae = pw
case jobspb.EncryptionMode_KMS:
encryptionParams.RawKmsUris, err = kmsFn()
if err != nil {
return err
}
if err := requireEnterprise(p.ExecCfg(), "encryption"); err != nil {
return err
}
}
var revisionHistory bool
if backupStmt.Options.CaptureRevisionHistory {
if err := requireEnterprise(p.ExecCfg(), "revision_history"); err != nil {
return err
}
revisionHistory = true
}
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:
var err error
targetDescs, completeDBs, err = fullClusterTargetsBackup(ctx, p.ExecCfg(), endTime)
if err != nil {
return err
}
default:
return errors.AssertionFailedf("unexpected descriptor coverage %v", backupStmt.Coverage())
}
// Check BACKUP privileges.
err = checkPrivilegesForBackup(ctx, backupStmt, p, targetDescs, to)
if err != nil {
return err
}
initialDetails := jobspb.BackupDetails{
Destination: jobspb.BackupDetails_Destination{To: to, IncrementalStorage: incrementalStorage},
EndTime: endTime,
RevisionHistory: revisionHistory,
IncrementalFrom: incrementalFrom,
FullCluster: backupStmt.Coverage() == tree.AllDescriptors,
ResolvedCompleteDbs: completeDBs,
EncryptionOptions: &encryptionParams,
}
if backupStmt.CreatedByInfo != nil && backupStmt.CreatedByInfo.Name == jobs.CreatedByScheduledJobs {
initialDetails.ScheduleID = backupStmt.CreatedByInfo.ID
}
// For backups of specific targets, those targets were resolved with this
// planner's session, so we need to store the result of resolution. For
// full-cluster we can just recompute it during execution.
if !initialDetails.FullCluster {
descriptorProtos := make([]descpb.Descriptor, 0, len(targetDescs))
for _, desc := range targetDescs {
descriptorProtos = append(descriptorProtos, *desc.DescriptorProto())
}
initialDetails.ResolvedTargets = descriptorProtos
}
if backupStmt.Nested {
if backupStmt.AppendToLatest {
initialDetails.Destination.Subdir = latestFileName
initialDetails.Destination.Exists = true
} else if subdir != "" {
initialDetails.Destination.Subdir = "/" + strings.TrimPrefix(subdir, "/")
initialDetails.Destination.Exists = true
} else {
initialDetails.Destination.Subdir = endTime.GoTime().Format(DateBasedIntoFolderName)
}
}
if backupStmt.Targets != nil && backupStmt.Targets.TenantID.IsSet() {
if !p.ExecCfg().Codec.ForSystemTenant() {
return pgerror.Newf(pgcode.InsufficientPrivilege, "only the system tenant can backup other tenants")
}
initialDetails.SpecificTenantIds = []roachpb.TenantID{roachpb.MakeTenantID(backupStmt.Targets.TenantID.ID)}
}
jobID := p.ExecCfg().JobRegistry.MakeJobID()
if p.ExecCfg().Settings.Version.IsActive(ctx, clusterversion.BackupResolutionInJob) {
description, err := backupJobDescription(p,
backupStmt.Backup, to, incrementalFrom,
encryptionParams.RawKmsUris,
initialDetails.Destination.Subdir,
initialDetails.Destination.IncrementalStorage,
)
if err != nil {
return err
}
jr := jobs.Record{
Description: description,
Details: initialDetails,
Progress: jobspb.BackupProgress{},
CreatedBy: backupStmt.CreatedByInfo,
Username: p.User(),
DescriptorIDs: func() (sqlDescIDs []descpb.ID) {
for i := range targetDescs {
sqlDescIDs = append(sqlDescIDs, targetDescs[i].GetID())
}
return sqlDescIDs
}(),
}
plannerTxn := p.Txn()
if backupStmt.Options.Detached {
// When running inside an explicit transaction, we simply create the job
// record. We do not wait for the job to finish.
_, err := p.ExecCfg().JobRegistry.CreateAdoptableJobWithTxn(
ctx, jr, jobID, plannerTxn)
if err != nil {
return err
}
resultsCh <- tree.Datums{tree.NewDInt(tree.DInt(jobID))}
return nil
}
var sj *jobs.StartableJob
if err := func() (err error) {
defer func() {
if err == nil || sj == nil {
return
}
if cleanupErr := sj.CleanupOnRollback(ctx); cleanupErr != nil {
log.Errorf(ctx, "failed to cleanup job: %v", cleanupErr)
}
}()
if err := p.ExecCfg().JobRegistry.CreateStartableJobWithTxn(ctx, &sj, jobID, plannerTxn, jr); err != nil {
return err
}
// We commit the transaction here so that the job can be started. This
// is safe because we're in an implicit transaction. If we were in an
// explicit transaction the job would have to be run with the detached
// option and would have been handled above.
return plannerTxn.Commit(ctx)
}(); err != nil {
return err
}
if err := sj.Start(ctx); err != nil {
return err
}
if err := sj.AwaitCompletion(ctx); err != nil {
return err
}
return sj.ReportExecutionResults(ctx, resultsCh)
}
// TODO(dt): delete this in 22.2.
backupDetails, backupManifest, err := getBackupDetailAndManifest(
ctx, p.ExecCfg(), p.Txn(), initialDetails, p.User(),
)
if err != nil {
return err
}
description, err := backupJobDescription(p, backupStmt.Backup, to, incrementalFrom, encryptionParams.RawKmsUris, backupDetails.Destination.Subdir, initialDetails.Destination.IncrementalStorage)
if err != nil {
return err
}
// We create the job record in the planner's transaction to ensure that
// the job record creation happens transactionally.
plannerTxn := p.Txn()
// Write backup manifest into a temporary checkpoint file.
// This accomplishes 2 purposes:
// 1. Persists large state needed for backup job completion.
// 2. Verifies we can write to destination location.
// This temporary checkpoint file gets renamed to real checkpoint
// file when the backup jobs starts execution.
//
// TODO (pbardea): For partitioned backups, also add verification for other
// stores we are writing to in addition to the default.
if err := planSchedulePTSChaining(ctx, p.ExecCfg(), plannerTxn, &backupDetails, backupStmt.CreatedByInfo); err != nil {
return err
}
if p.ExecCfg().Settings.Version.IsActive(ctx, clusterversion.EnableProtectedTimestampsForTenant) {
protectedtsID := uuid.MakeV4()
backupDetails.ProtectedTimestampRecord = &protectedtsID
} else if len(backupManifest.Spans) > 0 && p.ExecCfg().Codec.ForSystemTenant() {
protectedtsID := uuid.MakeV4()
backupDetails.ProtectedTimestampRecord = &protectedtsID
}
jr := jobs.Record{
Description: description,
Username: p.User(),
// TODO(yevgeniy): Consider removing -- this info available in backup manifest.
DescriptorIDs: func() (sqlDescIDs []descpb.ID) {
for i := range backupManifest.Descriptors {
sqlDescIDs = append(sqlDescIDs,
descpb.GetDescriptorID(&backupManifest.Descriptors[i]))
}
return sqlDescIDs
}(),
Details: backupDetails,
Progress: jobspb.BackupProgress{},
CreatedBy: backupStmt.CreatedByInfo,
}
lic := utilccl.CheckEnterpriseEnabled(
p.ExecCfg().Settings, p.ExecCfg().LogicalClusterID(), p.ExecCfg().Organization(), "",
) != nil
if backupDetails.ProtectedTimestampRecord != nil {
if err := protectTimestampForBackup(
ctx, p.ExecCfg(), plannerTxn, jobID, backupManifest, backupDetails,
); err != nil {
return err
}
}
if backupStmt.Options.Detached {
// When running inside an explicit transaction, we simply create the job
// record. We do not wait for the job to finish.
_, err := p.ExecCfg().JobRegistry.CreateAdoptableJobWithTxn(
ctx, jr, jobID, plannerTxn)
if err != nil {
return err
}
if err := writeBackupManifestCheckpoint(
ctx, backupDetails.URI, backupDetails.EncryptionOptions, &backupManifest, p.ExecCfg(), p.User(),
); err != nil {
return err
}
resultsCh <- tree.Datums{tree.NewDInt(tree.DInt(jobID))}
collectTelemetry(backupManifest, initialDetails, backupDetails, lic)
return nil
}
// Construct the job and commit the transaction. Perform this work in a
// closure to ensure that the job is cleaned up if an error occurs.
var sj *jobs.StartableJob
if err := func() (err error) {
defer func() {
if err == nil || sj == nil {
return
}
if cleanupErr := sj.CleanupOnRollback(ctx); cleanupErr != nil {
log.Errorf(ctx, "failed to cleanup job: %v", cleanupErr)
}
}()
if err := p.ExecCfg().JobRegistry.CreateStartableJobWithTxn(ctx, &sj, jobID, plannerTxn, jr); err != nil {
return err
}
if err := writeBackupManifestCheckpoint(
ctx, backupDetails.URI, backupDetails.EncryptionOptions, &backupManifest, p.ExecCfg(), p.User(),
); err != nil {
return err
}
// We commit the transaction here so that the job can be started. This
// is safe because we're in an implicit transaction. If we were in an
// explicit transaction the job would have to be run with the detached
// option and would have been handled above.
return plannerTxn.Commit(ctx)
}(); err != nil {
return err
}
collectTelemetry(backupManifest, initialDetails, backupDetails, lic)
if err := sj.Start(ctx); err != nil {
return err
}
if err := sj.AwaitCompletion(ctx); err != nil {
return err
}
return sj.ReportExecutionResults(ctx, resultsCh)
}
if backupStmt.Options.Detached {
return fn, jobs.DetachedJobExecutionResultHeader, nil, false, nil
}
return fn, jobs.BulkJobExecutionResultHeader, nil, false, nil
}
func collectTelemetry(
backupManifest BackupManifest, initialDetails, backupDetails jobspb.BackupDetails, licensed bool,
) {
// sourceSuffix specifies if this schedule was created by a schedule.
sourceSuffix := ".manual"
if backupDetails.ScheduleID != 0 {
sourceSuffix = ".scheduled"
}
// countSource emits a telemetry counter and also adds a ".scheduled"
// suffix if the job was created by a schedule.
countSource := func(feature string) {
telemetry.Count(feature + sourceSuffix)
}
countSource("backup.total.started")
if backupManifest.isIncremental() || backupDetails.EncryptionOptions != nil {
countSource("backup.using-enterprise-features")
}
if licensed {
countSource("backup.licensed")
} else {
countSource("backup.free")
}
if backupDetails.StartTime.IsEmpty() {
countSource("backup.span.full")
} else {
countSource("backup.span.incremental")
telemetry.CountBucketed("backup.incremental-span-sec",
int64(backupDetails.EndTime.GoTime().Sub(backupDetails.StartTime.GoTime()).Seconds()))
if len(initialDetails.IncrementalFrom) == 0 {
countSource("backup.auto-incremental")
}
}
if len(backupDetails.URIsByLocalityKV) > 1 {
countSource("backup.partitioned")
}
if backupManifest.MVCCFilter == MVCCFilter_All {
countSource("backup.revision-history")
}
if backupDetails.EncryptionOptions != nil {
countSource("backup.encrypted")
switch backupDetails.EncryptionOptions.Mode {
case jobspb.EncryptionMode_Passphrase:
countSource("backup.encryption.passphrase")
case jobspb.EncryptionMode_KMS:
countSource("backup.encryption.kms")
}
}
if backupDetails.CollectionURI != "" {
countSource("backup.nested")
timeBaseSubdir := true
if _, err := time.Parse(DateBasedIntoFolderName,
initialDetails.Destination.Subdir); err != nil {
timeBaseSubdir = false
}
if backupDetails.StartTime.IsEmpty() {
if !timeBaseSubdir {
countSource("backup.deprecated-full-nontime-subdir")
} else if initialDetails.Destination.Exists {
countSource("backup.deprecated-full-time-subdir")
} else {
countSource("backup.full-no-subdir")
}
} else {
if initialDetails.Destination.Subdir == latestFileName {
countSource("backup.incremental-latest-subdir")