-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
restore_job.go
3019 lines (2752 loc) · 106 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"
"sort"
"time"
"github.com/cockroachdb/cockroach/pkg/build"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backupencryption"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backupinfo"
"github.com/cockroachdb/cockroach/pkg/ccl/backupccl/backuppb"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/cloud/cloudpb"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/joberror"
"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"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts/ptpb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descidgen"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/funcdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/ingesting"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/multiregion"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/nstree"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/rewrite"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemadesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scbackup"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"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/log/eventpb"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"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"
pbtypes "github.com/gogo/protobuf/types"
"github.com/lib/pq/oid"
)
// restoreStatsInsertBatchSize is an arbitrarily chosen value of the number of
// tables we process in a single txn when restoring their table statistics.
var restoreStatsInsertBatchSize = 10
// 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 the restore processor method which
// writes the KVs) 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(
codec keys.SQLCodec, kr *KeyRewriter, key roachpb.Key,
) (roachpb.Key, error) {
newKey, rewritten, err := kr.RewriteKey(append([]byte(nil), key...), 0 /*wallTime*/)
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)
}
if bytes.HasPrefix(newKey, keys.TenantPrefix) {
return newKey, nil
}
// 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 := codec.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 = codec.TablePrefix(id)
}
return newKey, nil
}
func restoreWithRetry(
restoreCtx context.Context,
execCtx sql.JobExecContext,
numNodes int,
backupManifests []backuppb.BackupManifest,
backupLocalityInfo []jobspb.RestoreDetails_BackupLocalityInfo,
endTime hlc.Timestamp,
dataToRestore restorationData,
job *jobs.Job,
encryption *jobspb.BackupEncryptionOptions,
kmsEnv cloud.KMSEnv,
) (roachpb.RowCount, error) {
// We retry on pretty generic failures -- any rpc error. If a worker node were
// to restart, it would produce this kind of error, but there may be other
// errors that are also rpc errors. Don't retry to aggressively.
retryOpts := retry.Options{
MaxBackoff: 1 * time.Second,
MaxRetries: 5,
}
// We want to retry a restore if there are transient failures (i.e. worker nodes
// dying), so if we receive a retryable error, re-plan and retry the backup.
var res roachpb.RowCount
var err error
for r := retry.StartWithCtx(restoreCtx, retryOpts); r.Next(); {
// Re-plan inner loop (does not count as retries, done by outer loop).
for {
res, err = restore(
restoreCtx,
execCtx,
numNodes,
backupManifests,
backupLocalityInfo,
endTime,
dataToRestore,
job,
encryption,
kmsEnv,
)
if err == nil || !errors.Is(err, sql.ErrPlanChanged) {
break
}
}
if err == nil {
break
}
if errors.HasType(err, &roachpb.InsufficientSpaceError{}) {
return roachpb.RowCount{}, jobs.MarkPauseRequestError(errors.UnwrapAll(err))
}
if joberror.IsPermanentBulkJobError(err) {
return roachpb.RowCount{}, err
}
log.Warningf(restoreCtx, `encountered retryable error: %+v`, err)
}
// We have exhausted retries, but we have not seen a "PermanentBulkJobError" so
// it is possible that this is a transient error that is taking longer than
// our configured retry to go away.
//
// Let's pause the job instead of failing it so that the user can decide
// whether to resume it or cancel it.
if err != nil {
return res, jobs.MarkPauseRequestError(errors.Wrap(err, "exhausted retries"))
}
return res, nil
}
type storeByLocalityKV map[string]cloudpb.ExternalStorage
func makeBackupLocalityMap(
backupLocalityInfos []jobspb.RestoreDetails_BackupLocalityInfo, user username.SQLUsername,
) (map[int]storeByLocalityKV, error) {
backupLocalityMap := make(map[int]storeByLocalityKV)
for i, localityInfo := range backupLocalityInfos {
storesByLocalityKV := make(storeByLocalityKV)
if localityInfo.URIsByOriginalLocalityKV != nil {
for kv, uri := range localityInfo.URIsByOriginalLocalityKV {
conf, err := cloud.ExternalStorageConfFromURI(uri, user)
if err != nil {
return nil, errors.Wrap(err,
"creating locality external storage configuration")
}
storesByLocalityKV[kv] = conf
}
}
backupLocalityMap[i] = storesByLocalityKV
}
return backupLocalityMap, nil
}
// restore imports a SQL table (or tables) from sets of non-overlapping sstable
// files.
func restore(
restoreCtx context.Context,
execCtx sql.JobExecContext,
numNodes int,
backupManifests []backuppb.BackupManifest,
backupLocalityInfo []jobspb.RestoreDetails_BackupLocalityInfo,
endTime hlc.Timestamp,
dataToRestore restorationData,
job *jobs.Job,
encryption *jobspb.BackupEncryptionOptions,
kmsEnv cloud.KMSEnv,
) (roachpb.RowCount, error) {
user := execCtx.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 := roachpb.RowCount{}
// If there isn't any data to restore, then return early.
if dataToRestore.isEmpty() {
return emptyRowCount, nil
}
// If we've already migrated some of the system tables we're about to
// restore, this implies that a previous attempt restored all of this data.
// We want to avoid restoring again since we'll be shadowing migrated keys.
details := job.Details().(jobspb.RestoreDetails)
if alreadyMigrated := checkForMigratedData(details, dataToRestore); alreadyMigrated {
return emptyRowCount, nil
}
mu := struct {
syncutil.Mutex
highWaterMark int
res roachpb.RowCount
requestsCompleted []bool
}{
highWaterMark: -1,
}
backupLocalityMap, err := makeBackupLocalityMap(backupLocalityInfo, user)
if err != nil {
return emptyRowCount, errors.Wrap(err, "resolving locality locations")
}
introducedSpanFrontier, err := createIntroducedSpanFrontier(backupManifests, endTime)
if err != nil {
return emptyRowCount, err
}
if err := checkCoverage(restoreCtx, dataToRestore.getSpans(), backupManifests); err != nil {
return emptyRowCount, err
}
// 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 := makeSimpleImportSpans(dataToRestore.getSpans(), backupManifests,
backupLocalityMap, introducedSpanFrontier, highWaterMark, targetRestoreSpanSize.Get(execCtx.ExecCfg().SV()))
if len(importSpans) == 0 {
// There are no files to restore.
return emptyRowCount, nil
}
for i := range importSpans {
importSpans[i].ProgressIdx = int64(i)
}
mu.requestsCompleted = make([]bool, len(importSpans))
// TODO(pbardea): 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.
// It tries to take the cluster size into account so that larger clusters
// distribute more chunks amongst them so that after scattering there isn't
// a large varience in the distribution of entries.
chunkSize := int(math.Sqrt(float64(len(importSpans)))) / numNodes
if chunkSize == 0 {
chunkSize = 1
}
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
progCh := make(chan *execinfrapb.RemoteProducerMetadata_BulkProcessorProgress)
// tasks are the concurrent tasks that are run during the restore.
var tasks []func(ctx context.Context) error
if dataToRestore.isMainBundle() {
// Only update the job progress on the main data bundle. This should account
// for the bulk of the data to restore. Other data (e.g. zone configs in
// cluster restores) may be restored first. When restoring that data, we
// don't want to update the high-water mark key, so instead progress is just
// defined on the main data bundle (of which there should only be one).
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)
}
})
jobProgressLoop := func(ctx context.Context) error {
ctx, progressSpan := tracing.ChildSpan(ctx, "progress-log")
defer progressSpan.Finish()
return progressLogger.Loop(ctx, requestFinishedCh)
}
tasks = append(tasks, jobProgressLoop)
}
jobCheckpointLoop := func(ctx context.Context) error {
defer close(requestFinishedCh)
// When a processor is done importing a span, it will send a progress update
// to progCh.
for progress := range progCh {
mu.Lock()
var progDetails backuppb.RestoreProgress
if err := pbtypes.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 the processor has finished importing a span, to update job
// progress.
requestFinishedCh <- struct{}{}
}
return nil
}
tasks = append(tasks, jobCheckpointLoop)
runRestore := func(ctx context.Context) error {
return distRestore(
ctx,
execCtx,
int64(job.ID()),
importSpanChunks,
dataToRestore.getPKIDs(),
encryption,
kmsEnv,
dataToRestore.getRekeys(),
dataToRestore.getTenantRekeys(),
endTime,
dataToRestore.isValidateOnly(),
progCh,
)
}
tasks = append(tasks, runRestore)
if err := ctxgroup.GoAndWait(restoreCtx, tasks...); 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,
mem *mon.BoundAccount,
p sql.JobExecContext,
details jobspb.RestoreDetails,
encryption *jobspb.BackupEncryptionOptions,
kmsEnv cloud.KMSEnv,
) ([]backuppb.BackupManifest, backuppb.BackupManifest, []catalog.Descriptor, int64, error) {
backupManifests, sz, err := backupinfo.LoadBackupManifestsAtTime(ctx, mem, details.URIs,
p.User(), p.ExecCfg().DistSQLSrv.ExternalStorageFromURI, encryption, kmsEnv, details.EndTime)
if err != nil {
return nil, backuppb.BackupManifest{}, nil, 0, err
}
allDescs, latestBackupManifest, err := backupinfo.LoadSQLDescsFromBackupsAtTime(backupManifests, details.EndTime)
if err != nil {
return nil, backuppb.BackupManifest{}, nil, 0, err
}
for _, m := range details.DatabaseModifiers {
for _, typ := range m.ExtraTypeDescs {
allDescs = append(allDescs, typedesc.NewBuilder(typ).BuildCreatedMutableType())
}
}
var sqlDescs []catalog.Descriptor
for _, desc := range allDescs {
id := desc.GetID()
switch desc := desc.(type) {
case *dbdesc.Mutable:
if m, ok := details.DatabaseModifiers[id]; ok {
desc.SetRegionConfig(m.RegionConfig)
}
}
if _, ok := details.DescriptorRewrites[id]; ok {
sqlDescs = append(sqlDescs, desc)
}
}
if err := maybeUpgradeDescriptors(sqlDescs, true /* skipFKsWithNoMatchingTable */); err != nil {
mem.Shrink(ctx, sz)
return nil, backuppb.BackupManifest{}, nil, 0, err
}
return backupManifests, latestBackupManifest, sqlDescs, sz, 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
restoreStats roachpb.RowCount
testingKnobs struct {
// beforePublishingDescriptors is called right before publishing
// descriptors, after any data has been restored.
beforePublishingDescriptors func() error
// afterPublishingDescriptors is called after committing the transaction to
// publish new descriptors in the public state.
afterPublishingDescriptors 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(systemTableName string) error
// afterOfflineTableCreation is called after creating the OFFLINE table
// descriptors we're ingesting. If an error is returned, we fail the
// restore.
afterOfflineTableCreation func() error
// afterPreRestore runs on cluster restores after restoring the "preRestore"
// data.
afterPreRestore func() error
// checksumRecover
checksumRecover func() error
}
}
var _ jobs.TraceableJob = &restoreResumer{}
// ForceRealSpan implements the TraceableJob interface.
func (r *restoreResumer) ForceRealSpan() bool {
return true
}
// 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(
ctx context.Context,
tableStatistics []*stats.TableStatisticProto,
descriptorRewrites jobspb.DescRewriteMap,
tableDescs []*descpb.TableDescriptor,
) []*stats.TableStatisticProto {
relevantTableStatistics := make([]*stats.TableStatisticProto, 0, len(tableStatistics))
tableHasStatsInBackup := make(map[descpb.ID]struct{})
for _, stat := range tableStatistics {
tableHasStatsInBackup[stat.TableID] = struct{}{}
if tableRewrite, ok := descriptorRewrites[stat.TableID]; ok {
// Statistics imported only when table re-write is present.
stat.TableID = tableRewrite.ID
relevantTableStatistics = append(relevantTableStatistics, stat)
}
}
// Check if we are missing stats for any table that is being restored. This
// could be because we ran into an error when computing stats during the
// backup.
for _, desc := range tableDescs {
if _, ok := tableHasStatsInBackup[desc.GetID()]; !ok {
log.Warningf(ctx, "statistics for table: %s, table ID: %d not found in the backup. "+
"Query performance on this table could suffer until statistics are recomputed.",
desc.GetName(), desc.GetID())
}
}
return relevantTableStatistics
}
// isDatabaseEmpty checks if there exists any tables in the given database.
// It pretends that the ignoredChildren 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,
txn *kv.Txn,
dbID descpb.ID,
allDescs []catalog.Descriptor,
ignoredChildren map[descpb.ID]struct{},
) (bool, error) {
for _, desc := range allDescs {
if _, ok := ignoredChildren[desc.GetID()]; ok {
continue
}
if desc.GetParentID() == dbID {
return false, nil
}
}
return true, nil
}
// isSchemaEmpty is like isDatabaseEmpty for schemas: it returns whether the
// schema is empty, disregarding the contents of ignoredChildren.
func isSchemaEmpty(
ctx context.Context,
txn *kv.Txn,
schemaID descpb.ID,
allDescs []catalog.Descriptor,
ignoredChildren map[descpb.ID]struct{},
) (bool, error) {
for _, desc := range allDescs {
if _, ok := ignoredChildren[desc.GetID()]; ok {
continue
}
if desc.GetParentSchemaID() == schemaID {
return false, nil
}
}
return true, nil
}
// spansForAllRestoreTableIndexes returns non-overlapping spans for every index
// and table passed in. They would normally overlap if any of them are
// interleaved.
func spansForAllRestoreTableIndexes(
codec keys.SQLCodec,
tables []catalog.TableDescriptor,
revs []backuppb.BackupManifest_DescriptorRevision,
schemaOnly bool,
) []roachpb.Span {
skipTableData := func(table catalog.TableDescriptor) bool {
// The only table data restored during a schemaOnly restore are from system tables,
// which only get covered during a cluster restore.
if table.GetParentID() != keys.SystemDatabaseID && schemaOnly {
return true
}
// We only import spans for physical tables.
if !table.IsPhysicalTable() {
return true
}
return false
}
added := make(map[tableAndIndex]bool, len(tables))
sstIntervalTree := interval.NewTree(interval.ExclusiveOverlapper)
for _, table := range tables {
if skipTableData(table) {
continue
}
for _, index := range table.ActiveIndexes() {
if err := sstIntervalTree.Insert(intervalSpan(table.IndexSpan(codec, index.GetID())), false); err != nil {
panic(errors.NewAssertionErrorWithWrappedErrf(err, "IndexSpan"))
}
added[tableAndIndex{tableID: table.GetID(), indexID: index.GetID()}] = true
}
}
// 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.
// TODO(pbardea): Consider and test the interaction between revision_history
// backups and OFFLINE tables.
rawTbl, _, _, _, _ := descpb.GetDescriptors(rev.Desc)
if rawTbl != nil && !rawTbl.Dropped() {
tbl := tabledesc.NewBuilder(rawTbl).BuildImmutableTable()
if skipTableData(tbl) {
continue
}
for _, idx := range tbl.ActiveIndexes() {
key := tableAndIndex{tableID: tbl.GetID(), indexID: idx.GetID()}
if !added[key] {
if err := sstIntervalTree.Insert(intervalSpan(tbl.IndexSpan(codec, idx.GetID())), false); err != nil {
panic(errors.NewAssertionErrorWithWrappedErrf(err, "IndexSpan"))
}
added[key] = true
}
}
}
}
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
})
return spans
}
func shouldPreRestore(table *tabledesc.Mutable) bool {
if table.GetParentID() != keys.SystemDatabaseID {
return false
}
tablesToPreRestore := getSystemTablesToRestoreBeforeData()
_, ok := tablesToPreRestore[table.GetName()]
return ok
}
// backedUpDescriptorWithInProgressImportInto returns true if the backed up descriptor represents a table with an in
// progress import that started in a cluster finalized to version 22.2.
func backedUpDescriptorWithInProgressImportInto(
ctx context.Context, p sql.JobExecContext, desc catalog.Descriptor,
) (bool, error) {
table, ok := desc.(catalog.TableDescriptor)
if !ok {
return false, nil
}
if table.GetInProgressImportStartTime() == 0 {
return false, nil
}
return true, nil
}
// createImportingDescriptors creates the tables that we will restore into and returns up to three
// configurations for separate restoration flows. The three restoration flows are
//
// 1. dataToPreRestore: a restoration flow cfg to ingest a subset of
// system tables (e.g. zone configs) during a cluster restore that are
// required to be set up before the rest of the data gets restored.
// This should be empty during non-cluster restores.
//
// 2. preValidation: a restoration flow cfg to ingest the remainder of system tables,
// during a verify_backup_table_data, cluster level, restores. This should be empty otherwise.
//
// 3. trackedRestore: a restoration flow cfg to ingest the remainder of
// restore targets. This flow should get executed last and should contain the
// bulk of the work, as it is used for job progress tracking.
func createImportingDescriptors(
ctx context.Context,
p sql.JobExecContext,
backupCodec keys.SQLCodec,
sqlDescs []catalog.Descriptor,
r *restoreResumer,
) (
dataToPreRestore *restorationDataBase,
preValidation *restorationDataBase,
trackedRestore *mainRestorationData,
err error,
) {
details := r.job.Details().(jobspb.RestoreDetails)
const kvTrace = false
var allMutableDescs []catalog.MutableDescriptor
var databases []catalog.DatabaseDescriptor
var writtenTypes []catalog.TypeDescriptor
var schemas []*schemadesc.Mutable
var types []*typedesc.Mutable
var functions []*funcdesc.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
oldTableIDs := make([]descpb.ID, 0)
// offlineSchemas is a slice of all the backed up schemas in a database that
// were in an offline state at the time of the backup. These offline schemas
// are not restored and need to be elided from the list of schemas when
// constructing the database descriptor.
offlineSchemas := make(map[descpb.ID]struct{})
tables := make([]catalog.TableDescriptor, 0)
postRestoreTables := make([]catalog.TableDescriptor, 0)
preRestoreTables := make([]catalog.TableDescriptor, 0)
for _, desc := range sqlDescs {
// Decide which offline tables to include in the restore:
//
// - An offline table created by RESTORE or IMPORT PGDUMP is fully discarded.
// The table will not exist in the restoring cluster.
//
// - An offline table undergoing an IMPORT INTO has all importing data
// elided in the restore processor and is restored online to its pre import
// state.
if desc.Offline() {
if schema, ok := desc.(catalog.SchemaDescriptor); ok {
offlineSchemas[schema.GetID()] = struct{}{}
}
if eligible, err := backedUpDescriptorWithInProgressImportInto(ctx, p, desc); err != nil {
return nil, nil, nil, err
} else if !eligible {
continue
}
}
switch desc := desc.(type) {
case catalog.TableDescriptor:
mut := tabledesc.NewBuilder(desc.TableDesc()).BuildCreatedMutableTable()
if shouldPreRestore(mut) {
preRestoreTables = append(preRestoreTables, mut)
} else {
postRestoreTables = append(postRestoreTables, mut)
}
tables = append(tables, mut)
mutableTables = append(mutableTables, mut)
allMutableDescs = append(allMutableDescs, mut)
oldTableIDs = append(oldTableIDs, mut.GetID())
case catalog.DatabaseDescriptor:
if _, ok := details.DescriptorRewrites[desc.GetID()]; ok {
mut := dbdesc.NewBuilder(desc.DatabaseDesc()).BuildCreatedMutableDatabase()
databases = append(databases, mut)
mutableDatabases = append(mutableDatabases, mut)
allMutableDescs = append(allMutableDescs, mut)
}
case catalog.SchemaDescriptor:
mut := schemadesc.NewBuilder(desc.SchemaDesc()).BuildCreatedMutableSchema()
schemas = append(schemas, mut)
allMutableDescs = append(allMutableDescs, mut)
case catalog.TypeDescriptor:
mut := typedesc.NewBuilder(desc.TypeDesc()).BuildCreatedMutableType()
types = append(types, mut)
allMutableDescs = append(allMutableDescs, mut)
case catalog.FunctionDescriptor:
mut := funcdesc.NewBuilder(desc.FuncDesc()).BuildCreatedMutableFunction()
functions = append(functions, mut)
allMutableDescs = append(allMutableDescs, mut)
}
}
tempSystemDBID := tempSystemDatabaseID(details, tables)
if tempSystemDBID != descpb.InvalidID {
tempSystemDB := dbdesc.NewInitial(tempSystemDBID, restoreTempSystemDB,
username.AdminRoleName(), dbdesc.WithPublicSchemaID(keys.SystemPublicSchemaID))
databases = append(databases, tempSystemDB)
}
// 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.
preRestoreSpans := spansForAllRestoreTableIndexes(backupCodec, preRestoreTables, nil, details.SchemaOnly)
postRestoreSpans := spansForAllRestoreTableIndexes(backupCodec, postRestoreTables, nil, details.SchemaOnly)
var verifySpans []roachpb.Span
if details.VerifyData {
// verifySpans contains the spans that should be read and checksum'd during a
// verify_backup_table_data RESTORE
verifySpans = spansForAllRestoreTableIndexes(backupCodec, postRestoreTables, nil, false)
}
log.Eventf(ctx, "starting restore for %d tables", len(mutableTables))
// Assign new IDs to the database descriptors.
if err := rewrite.DatabaseDescs(mutableDatabases, details.DescriptorRewrites, offlineSchemas); err != nil {
return nil, nil, nil, err
}
databaseDescs := make([]*descpb.DatabaseDescriptor, len(mutableDatabases))
for i, database := range mutableDatabases {
databaseDescs[i] = database.DatabaseDesc()
}
// 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, ok := details.DescriptorRewrites[sc.ID]
if ok {
if !rw.ToExisting {
schemasToWrite = append(schemasToWrite, sc)
writtenSchemas = append(writtenSchemas, sc)
}
}
}
if err := rewrite.SchemaDescs(schemasToWrite, details.DescriptorRewrites); err != nil {
return nil, nil, nil, err
}
if err := remapPublicSchemas(ctx, p, mutableDatabases, &schemasToWrite, &writtenSchemas, &details); err != nil {
return nil, nil, nil, err
}
// Assign new IDs and privileges to the tables, and update all references to
// use the new IDs.
if err := rewrite.TableDescs(
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)
}
}
// Perform rewrites on ALL type descriptors that are present in the rewrite
// mapping.
//
// `types` contains a mix of existing type descriptors in the restoring
// cluster, and new type descriptors we will write from the backup.
//
// New type descriptors need to be rewritten with their generated IDs before
// they are written out to disk.
//
// Existing type descriptors need to be rewritten to the type ID of the type
// they are referring to in the restoring cluster. This ID is different from
// the ID the descriptor had when it was backed up. Changes to existing type
// descriptors will not be written to disk, and is only for accurate,
// in-memory resolution hereon out.
if err := rewrite.TypeDescs(types, details.DescriptorRewrites); err != nil {
return nil, nil, nil, err
}
// TODO(chengxiong): for now, we know that functions are not referenced by any
// other objects, so that function descriptors are only restored when
// restoring databases. This means that all function descriptors are not
// remaps. Which means that we don't need resolve collisions between functions
// being restored and existing functions in target DB However, this won't be
// true when we start supporting udf references from other objects. For
// example, we need extra logic to handle remaps for udfs used by a table when
// backup/restore is on table level.
functionsToWrite := make([]*funcdesc.Mutable, len(functions))
writtenFunctions := make([]catalog.FunctionDescriptor, len(functions))
for i, fn := range functions {
functionsToWrite[i] = fn
writtenFunctions[i] = fn
}
if err := rewrite.FunctionDescs(functions, details.DescriptorRewrites, details.OverrideDB); err != nil {
return nil, nil, nil, err
}
// Finally, clean up / update any schema changer state inside descriptors
// globally.
if err := rewrite.MaybeClearSchemaChangerStateInDescs(allMutableDescs); 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")
}
for _, desc := range mutableDatabases {
desc.SetOffline("restoring")
}
for _, desc := range functionsToWrite {
desc.SetOffline("restoring")
}
if tempSystemDBID != descpb.InvalidID {
for _, desc := range mutableTables {
if desc.GetParentID() == tempSystemDBID {
desc.SetPublic()
}
}
}
// 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 := sql.DescsTxn(ctx, p.ExecCfg(), func(
ctx context.Context, txn *kv.Txn, descsCol *descs.Collection,
) error {
// A couple of pieces of cleanup are required for multi-region databases.
// First, we need to find all of the MULTIREGION_ENUMs types and remap the
// IDs stored in the corresponding database descriptors to match the type's
// new ID. Secondly, we need to rebuild the zone configuration for each
// multi-region database. We don't perform the zone configuration rebuild on
// cluster restores, as they will have the zone configurations restored as
// as the system tables are restored.
mrEnumsFound := make(map[descpb.ID]descpb.ID)
for _, t := range typesByID {
typeDesc := typedesc.NewBuilder(t.TypeDesc()).BuildImmutableType()
if typeDesc.GetKind() == descpb.TypeDescriptor_MULTIREGION_ENUM {
// Check to see if we've found more than one multi-region enum on any
// given database.
if id, ok := mrEnumsFound[typeDesc.GetParentID()]; ok {
return errors.AssertionFailedf(
"unexpectedly found more than one MULTIREGION_ENUM (IDs = %d, %d) "+
"on database %d during restore", id, typeDesc.GetID(), typeDesc.GetParentID())
}
mrEnumsFound[typeDesc.GetParentID()] = typeDesc.GetID()
if db, ok := dbsByID[typeDesc.GetParentID()]; ok {
desc := db.DatabaseDesc()
if desc.RegionConfig == nil {
return errors.AssertionFailedf(
"found MULTIREGION_ENUM on non-multi-region database %s", desc.Name)
}
// Update the RegionEnumID to record the new multi-region enum ID.
desc.RegionConfig.RegionEnumID = t.GetID()