-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
restore_job.go
1777 lines (1633 loc) · 60.9 KB
/
restore_job.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"
"math"
"github.com/cockroachdb/cockroach/pkg/ccl/storageccl"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"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/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemadesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/systemschema"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/covering"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/storage/cloud"
"github.com/cockroachdb/cockroach/pkg/storage/cloudimpl"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"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/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/gogo/protobuf/types"
)
type intervalSpan roachpb.Span
var _ interval.Interface = intervalSpan{}
// ID is part of `interval.Interface` but unused in makeImportSpans.
func (ie intervalSpan) ID() uintptr { return 0 }
// Range is part of `interval.Interface`.
func (ie intervalSpan) Range() interval.Range {
return interval.Range{Start: []byte(ie.Key), End: []byte(ie.EndKey)}
}
type importEntryType int
const (
backupSpan importEntryType = iota
backupFile
tableSpan
completedSpan
)
type importEntry struct {
roachpb.Span
entryType importEntryType
// Only set if entryType is backupSpan
start, end hlc.Timestamp
// Only set if entryType is backupFile
dir roachpb.ExternalStorage
file BackupManifest_File
}
// makeImportSpans pivots the backups, which are grouped by time, into
// spans for import, which are grouped by keyrange.
//
// The core logic of this is in OverlapCoveringMerge, which accepts sets of
// non-overlapping key ranges (aka coverings) each with a payload, and returns
// them aligned with the payloads in the same order as in the input.
//
// Example (input):
// - [A, C) backup t0 to t1 -> /file1
// - [C, D) backup t0 to t1 -> /file2
// - [A, B) backup t1 to t2 -> /file3
// - [B, C) backup t1 to t2 -> /file4
// - [C, D) backup t1 to t2 -> /file5
// - [B, D) requested table data to be restored
//
// Example (output):
// - [A, B) -> /file1, /file3
// - [B, C) -> /file1, /file4, requested (note that file1 was split into two ranges)
// - [C, D) -> /file2, /file5, requested
//
// This would be turned into two Import spans, one restoring [B, C) out of
// /file1 and /file4, the other restoring [C, D) out of /file2 and /file5.
// Nothing is restored out of /file3 and only part of /file1 is used.
//
// NB: All grouping operates in the pre-rewrite keyspace, meaning the keyranges
// as they were backed up, not as they're being restored.
//
// If a span is not covered, the onMissing function is called with the span and
// time missing to determine what error, if any, should be returned.
func makeImportSpans(
tableSpans []roachpb.Span,
backups []BackupManifest,
backupLocalityInfo []jobspb.RestoreDetails_BackupLocalityInfo,
lowWaterMark roachpb.Key,
user string,
onMissing func(span covering.Range, start, end hlc.Timestamp) error,
) ([]execinfrapb.RestoreSpanEntry, hlc.Timestamp, error) {
// Put the covering for the already-completed spans into the
// OverlapCoveringMerge input first. Payloads are returned in the same order
// that they appear in the input; putting the completedSpan first means we'll
// see it first when iterating over the output of OverlapCoveringMerge and
// avoid doing unnecessary work.
completedCovering := covering.Covering{
{
Start: []byte(keys.MinKey),
End: []byte(lowWaterMark),
Payload: importEntry{entryType: completedSpan},
},
}
// Put the merged table data covering into the OverlapCoveringMerge input
// next.
var tableSpanCovering covering.Covering
for _, span := range tableSpans {
tableSpanCovering = append(tableSpanCovering, covering.Range{
Start: span.Key,
End: span.EndKey,
Payload: importEntry{
Span: span,
entryType: tableSpan,
},
})
}
backupCoverings := []covering.Covering{completedCovering, tableSpanCovering}
// Iterate over backups creating two coverings for each. First the spans
// that were backed up, then the files in the backup. The latter is a subset
// when some of the keyranges in the former didn't change since the previous
// backup. These alternate (backup1 spans, backup1 files, backup2 spans,
// backup2 files) so they will retain that alternation in the output of
// OverlapCoveringMerge.
var maxEndTime hlc.Timestamp
for i, b := range backups {
if maxEndTime.Less(b.EndTime) {
maxEndTime = b.EndTime
}
var backupNewSpanCovering covering.Covering
for _, s := range b.IntroducedSpans {
backupNewSpanCovering = append(backupNewSpanCovering, covering.Range{
Start: s.Key,
End: s.EndKey,
Payload: importEntry{Span: s, entryType: backupSpan, start: hlc.Timestamp{}, end: b.StartTime},
})
}
backupCoverings = append(backupCoverings, backupNewSpanCovering)
var backupSpanCovering covering.Covering
for _, s := range b.Spans {
backupSpanCovering = append(backupSpanCovering, covering.Range{
Start: s.Key,
End: s.EndKey,
Payload: importEntry{Span: s, entryType: backupSpan, start: b.StartTime, end: b.EndTime},
})
}
backupCoverings = append(backupCoverings, backupSpanCovering)
var backupFileCovering covering.Covering
var storesByLocalityKV map[string]roachpb.ExternalStorage
if backupLocalityInfo != nil && backupLocalityInfo[i].URIsByOriginalLocalityKV != nil {
storesByLocalityKV = make(map[string]roachpb.ExternalStorage)
for kv, uri := range backupLocalityInfo[i].URIsByOriginalLocalityKV {
conf, err := cloudimpl.ExternalStorageConfFromURI(uri, user)
if err != nil {
return nil, hlc.Timestamp{}, err
}
storesByLocalityKV[kv] = conf
}
}
for _, f := range b.Files {
dir := b.Dir
if storesByLocalityKV != nil {
if newDir, ok := storesByLocalityKV[f.LocalityKV]; ok {
dir = newDir
}
}
backupFileCovering = append(backupFileCovering, covering.Range{
Start: f.Span.Key,
End: f.Span.EndKey,
Payload: importEntry{
Span: f.Span,
entryType: backupFile,
dir: dir,
file: f,
},
})
}
backupCoverings = append(backupCoverings, backupFileCovering)
}
// Group ranges covered by backups with ones needed to restore the selected
// tables. Note that this breaks intervals up as necessary to align them.
// See the function godoc for details.
importRanges := covering.OverlapCoveringMerge(backupCoverings)
// Translate the output of OverlapCoveringMerge into requests.
var requestEntries []execinfrapb.RestoreSpanEntry
rangeLoop:
for _, importRange := range importRanges {
needed := false
var ts hlc.Timestamp
var files []roachpb.ImportRequest_File
payloads := importRange.Payload.([]interface{})
for _, p := range payloads {
ie := p.(importEntry)
switch ie.entryType {
case completedSpan:
continue rangeLoop
case tableSpan:
needed = true
case backupSpan:
if ts != ie.start {
return nil, hlc.Timestamp{}, errors.Errorf(
"no backup covers time [%s,%s) for range [%s,%s) or backups listed out of order (mismatched start time)",
ts, ie.start,
roachpb.Key(importRange.Start), roachpb.Key(importRange.End))
}
ts = ie.end
case backupFile:
if len(ie.file.Path) > 0 {
files = append(files, roachpb.ImportRequest_File{
Dir: ie.dir,
Path: ie.file.Path,
Sha512: ie.file.Sha512,
})
}
}
}
if needed {
if ts != maxEndTime {
if err := onMissing(importRange, ts, maxEndTime); err != nil {
return nil, hlc.Timestamp{}, err
}
}
// If needed is false, we have data backed up that is not necessary
// for this restore. Skip it.
requestEntries = append(requestEntries, execinfrapb.RestoreSpanEntry{
Span: roachpb.Span{Key: importRange.Start, EndKey: importRange.End},
Files: files,
})
}
}
return requestEntries, maxEndTime, nil
}
// WriteDescriptors writes all the the new descriptors: First the ID ->
// TableDescriptor for the new table, then flip (or initialize) the name -> ID
// entry so any new queries will use the new one. The tables are assigned the
// permissions of their parent database and the user must have CREATE permission
// on that database at the time this function is called.
func WriteDescriptors(
ctx context.Context,
txn *kv.Txn,
databases []catalog.DatabaseDescriptor,
schemas []catalog.SchemaDescriptor,
tables []catalog.TableDescriptor,
types []catalog.TypeDescriptor,
descCoverage tree.DescriptorCoverage,
settings *cluster.Settings,
extra []roachpb.KeyValue,
) error {
ctx, span := tracing.ChildSpan(ctx, "WriteDescriptors")
defer tracing.FinishSpan(span)
err := func() error {
b := txn.NewBatch()
wroteDBs := make(map[descpb.ID]catalog.DatabaseDescriptor)
for i := range databases {
desc := databases[i]
// If the restore is not a full cluster restore we cannot know that
// the users on the restoring cluster match the ones that were on the
// cluster that was backed up. So we wipe the privileges on the database.
if descCoverage != tree.AllDescriptors {
if mut, ok := desc.(*dbdesc.Mutable); ok {
mut.Privileges = descpb.NewDefaultPrivilegeDescriptor(security.AdminRole)
} else {
log.Fatalf(ctx, "wrong type for table %d, %T, expected Mutable",
desc.GetID(), desc)
}
}
wroteDBs[desc.GetID()] = desc
if err := catalogkv.WriteNewDescToBatch(ctx, false /* kvTrace */, settings, b, keys.SystemSQLCodec, desc.GetID(), desc); err != nil {
return err
}
// Depending on which cluster version we are restoring to, we decide which
// namespace table to write the descriptor into. This may cause wrong
// behavior if the cluster version is bumped DURING a restore.
dKey := catalogkv.MakeDatabaseNameKey(ctx, settings, desc.GetName())
b.CPut(dKey.Key(keys.SystemSQLCodec), desc.GetID(), nil)
}
// Write namespace and descriptor entries for each schema.
for i := range schemas {
sc := schemas[i]
if err := catalogkv.WriteNewDescToBatch(
ctx,
false, /* kvTrace */
settings,
b,
keys.SystemSQLCodec,
sc.GetID(),
schemas[i],
); err != nil {
return err
}
skey := catalogkeys.NewSchemaKey(sc.GetParentID(), sc.GetName())
b.CPut(skey.Key(keys.SystemSQLCodec), sc.GetID(), nil)
}
for i := range tables {
table := tables[i]
// For full cluster restore, keep privileges as they were.
var updatedPrivileges *descpb.PrivilegeDescriptor
if wrote, ok := wroteDBs[table.GetParentID()]; ok {
// Leave the privileges of the temp system tables as
// the default.
if descCoverage != tree.AllDescriptors || wrote.GetName() == restoreTempSystemDB {
updatedPrivileges = wrote.GetPrivileges()
}
} else {
parentDB, err := catalogkv.MustGetDatabaseDescByID(ctx, txn, keys.SystemSQLCodec, table.GetParentID())
if err != nil {
return errors.Wrapf(err,
"failed to lookup parent DB %d", errors.Safe(table.GetParentID()))
}
// We don't check priv's here since we checked them during job planning.
// On full cluster restore, keep the privs as they are in the backup.
if descCoverage != tree.AllDescriptors {
// Default is to copy privs from restoring parent db, like CREATE TABLE.
// TODO(dt): Make this more configurable.
updatedPrivileges = parentDB.GetPrivileges()
}
}
if updatedPrivileges != nil {
if mut, ok := table.(*tabledesc.Mutable); ok {
mut.Privileges = updatedPrivileges
} else {
log.Fatalf(ctx, "wrong type for table %d, %T, expected Mutable",
table.GetID(), table)
}
}
if err := catalogkv.WriteNewDescToBatch(
ctx, false /* kvTrace */, settings, b, keys.SystemSQLCodec, table.GetID(), tables[i],
); err != nil {
return err
}
// Depending on which cluster version we are restoring to, we decide which
// namespace table to write the descriptor into. This may cause wrong
// behavior if the cluster version is bumped DURING a restore.
tkey := catalogkv.MakeObjectNameKey(
ctx,
settings,
table.GetParentID(),
table.GetParentSchemaID(),
table.GetName(),
)
b.CPut(tkey.Key(keys.SystemSQLCodec), table.GetID(), nil)
}
// Write all type descriptors -- create namespace entries and write to
// the system.descriptor table.
for i := range types {
typ := types[i].TypeDesc()
if err := catalogkv.WriteNewDescToBatch(
ctx,
false, /* kvTrace */
settings,
b,
keys.SystemSQLCodec,
typ.ID,
types[i],
); err != nil {
return err
}
tkey := catalogkv.MakeObjectNameKey(ctx, settings, typ.GetParentID(), typ.GetParentSchemaID(), typ.GetName())
b.CPut(tkey.Key(keys.SystemSQLCodec), typ.ID, nil)
}
for _, kv := range extra {
b.InitPut(kv.Key, &kv.Value, false)
}
if err := txn.Run(ctx, b); err != nil {
if errors.HasType(err, (*roachpb.ConditionFailedError)(nil)) {
return pgerror.Newf(pgcode.DuplicateObject, "table already exists")
}
return err
}
dg := catalogkv.NewOneLevelUncachedDescGetter(txn, keys.SystemSQLCodec)
for _, table := range tables {
if err := table.Validate(ctx, dg); err != nil {
return errors.Wrapf(err,
"validate table %d", errors.Safe(table.GetID()))
}
}
return nil
}()
return errors.Wrapf(err, "restoring table desc and namespace entries")
}
// rewriteBackupSpanKey rewrites a backup span start key for the purposes of
// splitting up the target key-space to send out the actual work of restoring.
//
// Keys for the primary index of the top-level table are rewritten to the just
// the overall start of the table. That is, /Table/51/1 becomes /Table/51.
//
// Any suffix of the key that does is not rewritten by kr's configured rewrites
// is truncated. For instance if a passed span has key /Table/51/1/77#/53/2/1
// but kr only configured with a rewrite for 51, it would return /Table/51/1/77.
// Such span boundaries are usually due to a interleaved table which has since
// been dropped -- any splits that happened to pick one of its rows live on, but
// include an ID of a table that no longer exists.
//
// Note that the actual restore process (i.e. inside ImportRequest) does not use
// these keys -- they are only used to split the key space and distribute those
// requests, thus truncation is fine. In the rare case where multiple backup
// spans are truncated to the same prefix (i.e. entire spans resided under the
// same interleave parent row) we'll generate some no-op splits and route the
// work to the same range, but the actual imported data is unaffected.
func rewriteBackupSpanKey(kr *storageccl.KeyRewriter, key roachpb.Key) (roachpb.Key, error) {
// TODO(dt): support rewriting tenant keys.
if bytes.HasPrefix(key, keys.TenantPrefix) {
return key, nil
}
newKey, rewritten, err := kr.RewriteKey(append([]byte(nil), key...), true /* isFromSpan */)
if err != nil {
return nil, errors.NewAssertionErrorWithWrappedErrf(err,
"could not rewrite span start key: %s", key)
}
if !rewritten && bytes.Equal(newKey, key) {
// if nothing was changed, we didn't match the top-level key at all.
return nil, errors.AssertionFailedf(
"no rewrite for span start key: %s", key)
}
// Modify all spans that begin at the primary index to instead begin at the
// start of the table. That is, change a span start key from /Table/51/1 to
// /Table/51. Otherwise a permanently empty span at /Table/51-/Table/51/1
// will be created.
if b, id, idx, err := keys.TODOSQLCodec.DecodeIndexPrefix(newKey); err != nil {
return nil, errors.NewAssertionErrorWithWrappedErrf(err,
"could not rewrite span start key: %s", key)
} else if idx == 1 && len(b) == 0 {
newKey = keys.TODOSQLCodec.TablePrefix(id)
}
return newKey, nil
}
// restore imports a SQL table (or tables) from sets of non-overlapping sstable
// files.
func restore(
restoreCtx context.Context,
phs sql.PlanHookState,
numClusterNodes int,
backupManifests []BackupManifest,
backupLocalityInfo []jobspb.RestoreDetails_BackupLocalityInfo,
endTime hlc.Timestamp,
tables []catalog.TableDescriptor,
oldTableIDs []descpb.ID,
spans []roachpb.Span,
job *jobs.Job,
encryption *jobspb.BackupEncryptionOptions,
) (RowCount, error) {
user := phs.User()
// A note about contexts and spans in this method: the top-level context
// `restoreCtx` is used for orchestration logging. All operations that carry
// out work get their individual contexts.
emptyRowCount := RowCount{}
// If there weren't any spans requested, then return early.
if len(spans) == 0 {
return emptyRowCount, nil
}
mu := struct {
syncutil.Mutex
highWaterMark int
res RowCount
requestsCompleted []bool
}{
highWaterMark: -1,
}
// Get TableRekeys to use when importing raw data.
var rekeys []roachpb.ImportRequest_TableRekey
for i := range tables {
tableToSerialize := tables[i]
newDescBytes, err := protoutil.Marshal(tableToSerialize.DescriptorProto())
if err != nil {
return mu.res, errors.NewAssertionErrorWithWrappedErrf(err,
"marshaling descriptor")
}
rekeys = append(rekeys, roachpb.ImportRequest_TableRekey{
OldID: uint32(oldTableIDs[i]),
NewDesc: newDescBytes,
})
}
// Pivot the backups, which are grouped by time, into requests for import,
// which are grouped by keyrange.
highWaterMark := job.Progress().Details.(*jobspb.Progress_Restore).Restore.HighWater
importSpans, _, err := makeImportSpans(spans, backupManifests, backupLocalityInfo,
highWaterMark, user, errOnMissingRange)
if err != nil {
return emptyRowCount, errors.Wrapf(err, "making import requests for %d backups", len(backupManifests))
}
for i := range importSpans {
importSpans[i].ProgressIdx = int64(i)
}
mu.requestsCompleted = make([]bool, len(importSpans))
progressLogger := jobs.NewChunkProgressLogger(job, len(importSpans), job.FractionCompleted(),
func(progressedCtx context.Context, details jobspb.ProgressDetails) {
switch d := details.(type) {
case *jobspb.Progress_Restore:
mu.Lock()
if mu.highWaterMark >= 0 {
d.Restore.HighWater = importSpans[mu.highWaterMark].Span.Key
}
mu.Unlock()
default:
log.Errorf(progressedCtx, "job payload had unexpected type %T", d)
}
})
pkIDs := make(map[uint64]bool)
for _, tbl := range tables {
pkIDs[roachpb.BulkOpSummaryID(uint64(tbl.GetID()), uint64(tbl.GetPrimaryIndexID()))] = true
}
g := ctxgroup.WithContext(restoreCtx)
// TODO(dan): This not super principled. I just wanted something that wasn't
// a constant and grew slower than linear with the length of importSpans. It
// seems to be working well for BenchmarkRestore2TB but worth revisiting.
chunkSize := int(math.Sqrt(float64(len(importSpans))))
importSpanChunks := make([][]execinfrapb.RestoreSpanEntry, 0, len(importSpans)/chunkSize)
for start := 0; start < len(importSpans); {
importSpanChunk := importSpans[start:]
end := start + chunkSize
if end < len(importSpans) {
importSpanChunk = importSpans[start:end]
}
importSpanChunks = append(importSpanChunks, importSpanChunk)
start = end
}
requestFinishedCh := make(chan struct{}, len(importSpans)) // enough buffer to never block
g.GoCtx(func(ctx context.Context) error {
ctx, progressSpan := tracing.ChildSpan(ctx, "progress-log")
defer tracing.FinishSpan(progressSpan)
return progressLogger.Loop(ctx, requestFinishedCh)
})
progCh := make(chan *execinfrapb.RemoteProducerMetadata_BulkProcessorProgress)
g.GoCtx(func(ctx context.Context) error {
// When a processor is done importing a span, it will send a progress update
// to progCh.
for progress := range progCh {
mu.Lock()
var progDetails RestoreProgress
if err := types.UnmarshalAny(&progress.ProgressDetails, &progDetails); err != nil {
log.Errorf(ctx, "unable to unmarshal restore progress details: %+v", err)
}
mu.res.add(progDetails.Summary)
idx := progDetails.ProgressIdx
// Assert that we're actually marking the correct span done. See #23977.
if !importSpans[progDetails.ProgressIdx].Span.Key.Equal(progDetails.DataSpan.Key) {
mu.Unlock()
return errors.Newf("request %d for span %v does not match import span for same idx: %v",
idx, progDetails.DataSpan, importSpans[idx],
)
}
mu.requestsCompleted[idx] = true
for j := mu.highWaterMark + 1; j < len(mu.requestsCompleted) && mu.requestsCompleted[j]; j++ {
mu.highWaterMark = j
}
mu.Unlock()
// Signal that an ImportRequest finished to update job progress.
requestFinishedCh <- struct{}{}
}
return nil
})
// TODO(pbardea): Improve logging in processors.
if err := distRestore(
restoreCtx,
phs,
importSpanChunks,
pkIDs,
encryption,
rekeys,
endTime,
progCh,
); err != nil {
return emptyRowCount, err
}
if err := g.Wait(); err != nil {
// This leaves the data that did get imported in case the user wants to
// retry.
// TODO(dan): Build tooling to allow a user to restart a failed restore.
return emptyRowCount, errors.Wrapf(err, "importing %d ranges", len(importSpans))
}
return mu.res, nil
}
// loadBackupSQLDescs extracts the backup descriptors, the latest backup
// descriptor, and all the Descriptors for a backup to be restored. It upgrades
// the table descriptors to the new FK representation if necessary. FKs that
// can't be restored because the necessary tables are missing are omitted; if
// skip_missing_foreign_keys was set, we should have aborted the RESTORE and
// returned an error prior to this.
// TODO(anzoteh96): this method returns two things: backup manifests
// and the descriptors of the relevant manifests. Ideally, this should
// be broken down into two methods.
func loadBackupSQLDescs(
ctx context.Context,
p sql.PlanHookState,
details jobspb.RestoreDetails,
encryption *jobspb.BackupEncryptionOptions,
) ([]BackupManifest, BackupManifest, []catalog.Descriptor, error) {
backupManifests, err := loadBackupManifests(ctx, details.URIs,
p.User(), p.ExecCfg().DistSQLSrv.ExternalStorageFromURI, encryption)
if err != nil {
return nil, BackupManifest{}, nil, err
}
// Upgrade the table descriptors to use the new FK representation.
// TODO(lucy, jordan): This should become unnecessary in 20.1 when we stop
// writing old-style descs in RestoreDetails (unless a job persists across
// an upgrade?).
if err := maybeUpgradeTableDescsInBackupManifests(ctx, backupManifests, true); err != nil {
return nil, BackupManifest{}, nil, err
}
allDescs, latestBackupManifest := loadSQLDescsFromBackupsAtTime(backupManifests, details.EndTime)
var sqlDescs []catalog.Descriptor
for _, desc := range allDescs {
id := desc.GetID()
if _, ok := details.DescriptorRewrites[id]; ok {
sqlDescs = append(sqlDescs, desc)
}
}
return backupManifests, latestBackupManifest, sqlDescs, nil
}
// restoreResumer should only store a reference to the job it's running. State
// should not be stored here, but rather in the job details.
type restoreResumer struct {
job *jobs.Job
settings *cluster.Settings
execCfg *sql.ExecutorConfig
testingKnobs struct {
// beforePublishingDescriptors is called right before publishing
// descriptors, after any data has been restored.
beforePublishingDescriptors func() error
// duringSystemTableRestoration is called once for every system table we
// restore. It is used to simulate any errors that we may face at this point
// of the restore.
duringSystemTableRestoration func() error
}
}
// getStatisticsFromBackup retrieves Statistics from backup manifest,
// either through the Statistics field or from the files.
func getStatisticsFromBackup(
ctx context.Context,
exportStore cloud.ExternalStorage,
encryption *jobspb.BackupEncryptionOptions,
backup BackupManifest,
) ([]*stats.TableStatisticProto, error) {
// This part deals with pre-20.2 stats format where backup statistics
// are stored as a field in backup manifests instead of in their
// individual files.
if backup.DeprecatedStatistics != nil {
return backup.DeprecatedStatistics, nil
}
tableStatistics := make([]*stats.TableStatisticProto, 0, len(backup.StatisticsFilenames))
uniqueFileNames := make(map[string]struct{})
for _, fname := range backup.StatisticsFilenames {
if _, exists := uniqueFileNames[fname]; !exists {
uniqueFileNames[fname] = struct{}{}
myStatsTable, err := readTableStatistics(ctx, exportStore, fname, encryption)
if err != nil {
return tableStatistics, err
}
tableStatistics = append(tableStatistics, myStatsTable.Statistics...)
}
}
return tableStatistics, nil
}
// remapRelevantStatistics changes the table ID references in the stats
// from those they had in the backed up database to what they should be
// in the restored database.
// It also selects only the statistics which belong to one of the tables
// being restored. If the descriptorRewrites can re-write the table ID, then that
// table is being restored.
func remapRelevantStatistics(
tableStatistics []*stats.TableStatisticProto, descriptorRewrites DescRewriteMap,
) []*stats.TableStatisticProto {
relevantTableStatistics := make([]*stats.TableStatisticProto, 0, len(tableStatistics))
for _, stat := range tableStatistics {
if tableRewrite, ok := descriptorRewrites[stat.TableID]; ok {
// Statistics imported only when table re-write is present.
stat.TableID = tableRewrite.ID
relevantTableStatistics = append(relevantTableStatistics, stat)
}
}
return relevantTableStatistics
}
// isDatabaseEmpty checks if there exists any tables in the given database.
// It pretends that the `ignoredTables` do not exist for the purposes of
// checking if a database is empty.
//
// It is used to construct a transaction which deletes a set of tables as well
// as some empty databases. However, we want to check that the databases are
// empty _after_ the transaction would have completed, so we want to ignore
// the tables that we're deleting in the same transaction. It is done this way
// to avoid having 2 transactions reading and writing the same keys one right
// after the other.
func isDatabaseEmpty(
ctx context.Context,
db *kv.DB,
dbDesc catalog.DatabaseDescriptor,
ignoredTables map[descpb.ID]struct{},
) (bool, error) {
var allDescs []catalog.Descriptor
if err := db.Txn(
ctx,
func(ctx context.Context, txn *kv.Txn) error {
var err error
allDescs, err = catalogkv.GetAllDescriptors(ctx, txn, keys.SystemSQLCodec)
return err
}); err != nil {
return false, err
}
for _, desc := range allDescs {
if _, ok := ignoredTables[desc.GetID()]; ok {
continue
}
if desc.GetParentID() == dbDesc.GetID() {
return false, nil
}
}
return true, nil
}
// createImportingDescriptors create the tables that we will restore into. It also
// fetches the information from the old tables that we need for the restore.
func createImportingDescriptors(
ctx context.Context, p sql.PlanHookState, sqlDescs []catalog.Descriptor, r *restoreResumer,
) (tables []catalog.TableDescriptor, oldTableIDs []descpb.ID, spans []roachpb.Span, err error) {
details := r.job.Details().(jobspb.RestoreDetails)
var databases []catalog.DatabaseDescriptor
var writtenTypes []catalog.TypeDescriptor
var schemas []*schemadesc.Mutable
var types []*typedesc.Mutable
// Store the tables as both the concrete mutable structs and the interface
// to deal with the lack of slice covariance in go. We want the slice of
// mutable descriptors for rewriting but ultimately want to return the
// tables as the slice of interfaces.
var mutableTables []*tabledesc.Mutable
var mutableDatabases []*dbdesc.Mutable
for _, desc := range sqlDescs {
switch desc := desc.(type) {
case catalog.TableDescriptor:
mut := tabledesc.NewCreatedMutable(*desc.TableDesc())
tables = append(tables, mut)
mutableTables = append(mutableTables, mut)
oldTableIDs = append(oldTableIDs, mut.GetID())
case catalog.DatabaseDescriptor:
if _, ok := details.DescriptorRewrites[desc.GetID()]; ok {
mut := dbdesc.NewCreatedMutable(*desc.DatabaseDesc())
databases = append(databases, mut)
mutableDatabases = append(mutableDatabases, mut)
}
case catalog.SchemaDescriptor:
schemas = append(schemas, schemadesc.NewCreatedMutable(*desc.SchemaDesc()))
case catalog.TypeDescriptor:
types = append(types, typedesc.NewCreatedMutable(*desc.TypeDesc()))
}
}
tempSystemDBID := keys.MinNonPredefinedUserDescID
for id := range details.DescriptorRewrites {
if int(id) > tempSystemDBID {
tempSystemDBID = int(id)
}
}
if details.DescriptorCoverage == tree.AllDescriptors {
databases = append(databases, dbdesc.NewInitial(
descpb.ID(tempSystemDBID), restoreTempSystemDB, security.AdminRole))
}
// We get the spans of the restoring tables _as they appear in the backup_,
// that is, in the 'old' keyspace, before we reassign the table IDs.
spans = spansForAllTableIndexes(p.ExecCfg().Codec, tables, nil)
log.Eventf(ctx, "starting restore for %d tables", len(mutableTables))
// Assign new IDs to the database descriptors.
dbDescsAreLeased := r.settings.Version.IsActive(ctx, clusterversion.VersionLeasedDatabaseDescriptors)
if err := rewriteDatabaseDescs(mutableDatabases, details.DescriptorRewrites, dbDescsAreLeased /* resetVersion */); err != nil {
return nil, nil, nil, err
}
databaseDescs := make([]*descpb.DatabaseDescriptor, len(mutableDatabases))
for i, database := range mutableDatabases {
databaseDescs[i] = database.DatabaseDesc()
}
// Assign new IDs and privileges to the tables, and update all references to
// use the new IDs.
if err := RewriteTableDescs(mutableTables, details.DescriptorRewrites, details.OverrideDB); err != nil {
return nil, nil, nil, err
}
tableDescs := make([]*descpb.TableDescriptor, len(mutableTables))
for i, table := range mutableTables {
tableDescs[i] = table.TableDesc()
}
// For each type, we might be writing the type in the backup, or we could be
// remapping to an existing type descriptor. Split up the descriptors into
// these two groups.
var typesToWrite []*typedesc.Mutable
existingTypeIDs := make(map[descpb.ID]struct{})
for i := range types {
typ := types[i]
rewrite := details.DescriptorRewrites[typ.GetID()]
if rewrite.ToExisting {
existingTypeIDs[rewrite.ID] = struct{}{}
} else {
typesToWrite = append(typesToWrite, typ)
writtenTypes = append(writtenTypes, typ)
}
}
// Assign new IDs to all of the type descriptors that need to be written.
if err := rewriteTypeDescs(typesToWrite, details.DescriptorRewrites); err != nil {
return nil, nil, nil, err
}
// Collect all schemas that are going to be restored.
var schemasToWrite []*schemadesc.Mutable
var writtenSchemas []catalog.SchemaDescriptor
for i := range schemas {
sc := schemas[i]
rw := details.DescriptorRewrites[sc.ID]
if !rw.ToExisting {
schemasToWrite = append(schemasToWrite, sc)
writtenSchemas = append(writtenSchemas, sc)
}
}
if err := rewriteSchemaDescs(schemasToWrite, details.DescriptorRewrites); err != nil {
return nil, nil, nil, err
}
// Set the new descriptors' states to offline.
for _, desc := range mutableTables {
desc.SetOffline("restoring")
}
for _, desc := range typesToWrite {
desc.SetOffline("restoring")
}
for _, desc := range schemasToWrite {
desc.SetOffline("restoring")
}
if r.settings.Version.IsActive(ctx, clusterversion.VersionLeasedDatabaseDescriptors) {
for _, desc := range mutableDatabases {
desc.SetOffline("restoring")
}
}
// Collect all types after they have had their ID's rewritten.
typesByID := make(map[descpb.ID]catalog.TypeDescriptor)
for i := range types {
typesByID[types[i].GetID()] = types[i]
}
// Collect all databases, for doing lookups of whether a database is new when
// updating schema references later on.
dbsByID := make(map[descpb.ID]catalog.DatabaseDescriptor)
for i := range databases {
dbsByID[databases[i].GetID()] = databases[i]
}
if !details.PrepareCompleted {
err := p.ExecCfg().DB.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
if len(details.Tenants) > 0 {
// TODO(dt): we need to set the system config trigger as the loop below
// will make a batch that anchors the txn at '/Table/...', and setting the trigger
// later (as we will have to) would fail.
if err := txn.SetSystemConfigTrigger(p.ExecCfg().Codec.ForSystemTenant()); err != nil {
return err
}
}
// Write the new descriptors which are set in the OFFLINE state.
if err := WriteDescriptors(ctx, txn, databases, writtenSchemas, tables, writtenTypes, details.DescriptorCoverage, r.settings, nil /* extra */); err != nil {
return errors.Wrapf(err, "restoring %d TableDescriptors from %d databases", len(tables), len(databases))
}
b := txn.NewBatch()
// For new schemas with existing parent databases, the schema map on the
// database descriptor needs to be updated.
existingDBsWithNewSchemas := make(map[descpb.ID][]catalog.SchemaDescriptor)
for _, sc := range writtenSchemas {
parentID := sc.GetParentID()
if _, ok := dbsByID[parentID]; !ok {
existingDBsWithNewSchemas[parentID] = append(existingDBsWithNewSchemas[parentID], sc)
}
}
// Write the updated databases.
for dbID, schemas := range existingDBsWithNewSchemas {
log.Infof(ctx, "writing %d schema entries to database %d", len(schemas), dbID)
// TODO (lucy): Replace these direct descriptor reads from the store
// with some interface backed by a descs.Collection.
desc, err := catalogkv.GetDescriptorByID(ctx, txn, keys.SystemSQLCodec,
dbID, catalogkv.Mutable, catalogkv.DatabaseDescriptorKind, true /* required */)
if err != nil {
return err
}
db := desc.(*dbdesc.Mutable)
if db.Schemas == nil {
db.Schemas = make(map[string]descpb.DatabaseDescriptor_SchemaInfo)
}
for _, sc := range schemas {
db.Schemas[sc.GetName()] = descpb.DatabaseDescriptor_SchemaInfo{ID: sc.GetID()}
}
// Note that since we're reading and writing these descriptors straight
// from/to the store every time, MaybeIncrementVersion doesn't provide
// any guarantees about incrementing the version exactly once in the
// transaction.
db.MaybeIncrementVersion()
if err := catalogkv.WriteDescToBatch(
ctx,
false, /* kvTrace */
p.ExecCfg().Settings,
b,
keys.SystemSQLCodec,
db.ID,
db,
); err != nil {
return err
}
}
// We could be restoring tables that point to existing types. We need to
// ensure that those existing types are updated with back references pointing
// to the new tables being restored.
for _, table := range mutableTables {
// Collect all types used by this table.
typeIDs, err := table.GetAllReferencedTypeIDs(func(id descpb.ID) (catalog.TypeDescriptor, error) {
return typesByID[id], nil