-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
restore.go
1815 lines (1658 loc) · 62.2 KB
/
restore.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"
"math"
"runtime"
"sort"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/ccl/storageccl"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl"
"github.com/cockroachdb/cockroach/pkg/ccl/utilccl/intervalccl"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"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/tracing"
"github.com/cockroachdb/errors"
opentracing "github.com/opentracing/opentracing-go"
)
// TableRewriteMap maps old table IDs to new table and parent IDs.
type TableRewriteMap map[sqlbase.ID]*jobspb.RestoreDetails_TableRewrite
const (
restoreOptIntoDB = "into_db"
restoreOptSkipMissingFKs = "skip_missing_foreign_keys"
restoreOptSkipMissingSequences = "skip_missing_sequences"
restoreOptSkipMissingViews = "skip_missing_views"
)
var restoreOptionExpectValues = map[string]sql.KVStringOptValidate{
restoreOptIntoDB: sql.KVStringOptRequireValue,
restoreOptSkipMissingFKs: sql.KVStringOptRequireNoValue,
restoreOptSkipMissingSequences: sql.KVStringOptRequireNoValue,
restoreOptSkipMissingViews: sql.KVStringOptRequireNoValue,
}
func loadBackupDescs(
ctx context.Context, uris []string, settings *cluster.Settings,
) ([]BackupDescriptor, error) {
backupDescs := make([]BackupDescriptor, len(uris))
for i, uri := range uris {
desc, err := ReadBackupDescriptorFromURI(ctx, uri, settings)
if err != nil {
return nil, errors.Wrapf(err, "failed to read backup descriptor")
}
backupDescs[i] = desc
}
if len(backupDescs) == 0 {
return nil, errors.Newf("no backups found")
}
return backupDescs, nil
}
// getBackupLocalityInfo takes a list of store URIs that together contain a
// partitioned backup, the first of which must contain the main BACKUP manifest,
// and searches for BACKUP_PART files in each store to build a map of (non-
// default) original backup locality values to URIs that currently contain
// the backup files.
func getBackupLocalityInfo(
ctx context.Context, uris []string, settings *cluster.Settings,
) (jobspb.RestoreDetails_BackupLocalityInfo, error) {
var info jobspb.RestoreDetails_BackupLocalityInfo
if len(uris) == 1 {
return info, nil
}
stores := make([]storageccl.ExportStorage, len(uris))
for i, uri := range uris {
conf, err := storageccl.ExportStorageConfFromURI(uri)
if err != nil {
return info, errors.Wrapf(err, "export configuration")
}
store, err := storageccl.MakeExportStorage(ctx, conf, settings)
if err != nil {
return info, errors.Wrapf(err, "make storage")
}
defer store.Close()
stores[i] = store
}
// First read the main backup descriptor, which is required to be at the first
// URI in the list. We don't read the table descriptors, so there's no need to
// upgrade them.
mainBackupDesc, err := readBackupDescriptor(ctx, stores[0], BackupDescriptorName)
if err != nil {
return info, err
}
// Now get the list of expected partial per-store backup manifest filenames
// and attempt to find them.
urisByOrigLocality := make(map[string]string)
for _, filename := range mainBackupDesc.PartitionDescriptorFilenames {
found := false
for i, store := range stores {
if desc, err := readBackupPartitionDescriptor(ctx, store, filename); err == nil {
if desc.BackupID != mainBackupDesc.ID {
return info, errors.Errorf(
"expected backup part to have backup ID %s, found %s",
mainBackupDesc.ID, desc.BackupID,
)
}
origLocalityKV := desc.LocalityKV
kv := roachpb.Tier{}
if err := kv.FromString(origLocalityKV); err != nil {
return info, errors.Wrapf(err, "reading backup manifest from %s", uris[i])
}
if _, ok := urisByOrigLocality[origLocalityKV]; ok {
return info, errors.Errorf("duplicate locality %s found in backup", origLocalityKV)
}
urisByOrigLocality[origLocalityKV] = uris[i]
found = true
break
}
}
if !found {
return info, errors.Errorf("expected manifest %s not found in backup locations", filename)
}
}
info.URIsByOriginalLocalityKV = urisByOrigLocality
return info, nil
}
func loadSQLDescsFromBackupsAtTime(
backupDescs []BackupDescriptor, asOf hlc.Timestamp,
) ([]sqlbase.Descriptor, BackupDescriptor) {
lastBackupDesc := backupDescs[len(backupDescs)-1]
if asOf.IsEmpty() {
return lastBackupDesc.Descriptors, lastBackupDesc
}
for _, b := range backupDescs {
if asOf.Less(b.StartTime) {
break
}
lastBackupDesc = b
}
if len(lastBackupDesc.DescriptorChanges) == 0 {
return lastBackupDesc.Descriptors, lastBackupDesc
}
byID := make(map[sqlbase.ID]*sqlbase.Descriptor, len(lastBackupDesc.Descriptors))
for _, rev := range lastBackupDesc.DescriptorChanges {
if asOf.Less(rev.Time) {
break
}
if rev.Desc == nil {
delete(byID, rev.ID)
} else {
byID[rev.ID] = rev.Desc
}
}
allDescs := make([]sqlbase.Descriptor, 0, len(byID))
for _, desc := range byID {
if t := desc.GetTable(); t != nil {
// A table revisions may have been captured before it was in a DB that is
// backed up -- if the DB is missing, filter the table.
if byID[t.ParentID] == nil {
continue
}
}
allDescs = append(allDescs, *desc)
}
return allDescs, lastBackupDesc
}
func selectTargets(
ctx context.Context,
p sql.PlanHookState,
backupDescs []BackupDescriptor,
targets tree.TargetList,
asOf hlc.Timestamp,
) ([]sqlbase.Descriptor, []*sqlbase.DatabaseDescriptor, error) {
allDescs, lastBackupDesc := loadSQLDescsFromBackupsAtTime(backupDescs, asOf)
matched, err := descriptorsMatchingTargets(ctx,
p.CurrentDatabase(), p.CurrentSearchPath(), allDescs, targets)
if err != nil {
return nil, nil, err
}
seenTable := false
for _, desc := range matched.descs {
if desc.GetTable() != nil {
seenTable = true
break
}
}
if !seenTable {
return nil, nil, errors.Errorf("no tables found: %s", tree.ErrString(&targets))
}
if lastBackupDesc.FormatVersion >= BackupFormatDescriptorTrackingVersion {
if err := matched.checkExpansions(lastBackupDesc.CompleteDbs); err != nil {
return nil, nil, err
}
}
return matched.descs, matched.requestedDBs, nil
}
// rewriteViewQueryDBNames rewrites the passed table's ViewQuery replacing all
// non-empty db qualifiers with `newDB`.
//
// TODO: this AST traversal misses tables named in strings (#24556).
func rewriteViewQueryDBNames(table *sqlbase.TableDescriptor, newDB string) error {
stmt, err := parser.ParseOne(table.ViewQuery)
if err != nil {
return pgerror.Wrapf(err, pgcode.Syntax,
"failed to parse underlying query from view %q", table.Name)
}
// Re-format to change all DB names to `newDB`.
f := tree.NewFmtCtx(tree.FmtParsable)
f.SetReformatTableNames(func(ctx *tree.FmtCtx, tn *tree.TableName) {
// empty catalog e.g. ``"".information_schema.tables` should stay empty.
if tn.CatalogName != "" {
tn.CatalogName = tree.Name(newDB)
}
ctx.WithReformatTableNames(nil, func() {
ctx.FormatNode(tn)
})
})
f.FormatNode(stmt.AST)
table.ViewQuery = f.CloseAndGetString()
return nil
}
// maybeFilterMissingViews filters the set of tables to restore to exclude views
// whose dependencies are either missing or are themselves unrestorable due to
// missing dependencies, and returns the resulting set of tables. If the
// restoreOptSkipMissingViews option is not set, an error is returned if any
// unrestorable views are found.
func maybeFilterMissingViews(
tablesByID map[sqlbase.ID]*sqlbase.TableDescriptor, opts map[string]string,
) (map[sqlbase.ID]*sqlbase.TableDescriptor, error) {
// Function that recursively determines whether a given table, if it is a
// view, has valid dependencies. Dependencies are looked up in tablesByID.
var hasValidViewDependencies func(*sqlbase.TableDescriptor) bool
hasValidViewDependencies = func(desc *sqlbase.TableDescriptor) bool {
if !desc.IsView() {
return true
}
for _, id := range desc.DependsOn {
if desc, ok := tablesByID[id]; !ok || !hasValidViewDependencies(desc) {
return false
}
}
return true
}
filteredTablesByID := make(map[sqlbase.ID]*sqlbase.TableDescriptor)
for id, table := range tablesByID {
if hasValidViewDependencies(table) {
filteredTablesByID[id] = table
} else {
if _, ok := opts[restoreOptSkipMissingViews]; !ok {
return nil, errors.Errorf(
"cannot restore view %q without restoring referenced table (or %q option)",
table.Name, restoreOptSkipMissingViews,
)
}
}
}
return filteredTablesByID, nil
}
// allocateTableRewrites determines the new ID and parentID (a "TableRewrite")
// for each table in sqlDescs and returns a mapping from old ID to said
// TableRewrite. It first validates that the provided sqlDescs can be restored
// into their original database (or the database specified in opst) to avoid
// leaking table IDs if we can be sure the restore would fail.
func allocateTableRewrites(
ctx context.Context,
p sql.PlanHookState,
databasesByID map[sqlbase.ID]*sql.DatabaseDescriptor,
tablesByID map[sqlbase.ID]*sql.TableDescriptor,
restoreDBs []*sqlbase.DatabaseDescriptor,
opts map[string]string,
) (TableRewriteMap, error) {
tableRewrites := make(TableRewriteMap)
overrideDB, renaming := opts[restoreOptIntoDB]
restoreDBNames := make(map[string]*sqlbase.DatabaseDescriptor, len(restoreDBs))
for _, db := range restoreDBs {
restoreDBNames[db.Name] = db
}
if len(restoreDBNames) > 0 && renaming {
return nil, errors.Errorf("cannot use %q option when restoring database(s)", restoreOptIntoDB)
}
// The logic at the end of this function leaks table IDs, so fail fast if
// we can be certain the restore will fail.
// Fail fast if the tables to restore are incompatible with the specified
// options.
for _, table := range tablesByID {
// Check that foreign key targets exist.
for i := range table.OutboundFKs {
fk := &table.OutboundFKs[i]
if _, ok := tablesByID[fk.ReferencedTableID]; !ok {
if _, ok := opts[restoreOptSkipMissingFKs]; !ok {
return nil, errors.Errorf(
"cannot restore table %q without referenced table %d (or %q option)",
table.Name, fk.ReferencedTableID, restoreOptSkipMissingFKs,
)
}
}
}
// Check that referenced sequences exist.
for i := range table.Columns {
col := &table.Columns[i]
for _, seqID := range col.UsesSequenceIds {
if _, ok := tablesByID[seqID]; !ok {
if _, ok := opts[restoreOptSkipMissingSequences]; !ok {
return nil, errors.Errorf(
"cannot restore table %q without referenced sequence %d (or %q option)",
table.Name, seqID, restoreOptSkipMissingSequences,
)
}
}
}
}
}
needsNewParentIDs := make(map[string][]sqlbase.ID)
// Fail fast if the necessary databases don't exist or are otherwise
// incompatible with this restore.
if err := p.ExecCfg().DB.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
// Check that any DBs being restored do _not_ exist.
for name := range restoreDBNames {
existingDatabaseID, err := txn.Get(ctx, sqlbase.MakeNameMetadataKey(keys.RootNamespaceID, name))
if err != nil {
return err
}
if existingDatabaseID.Value != nil {
return errors.Errorf("database %q already exists", name)
}
}
for _, table := range tablesByID {
var targetDB string
if renaming {
targetDB = overrideDB
} else {
database, ok := databasesByID[table.ParentID]
if !ok {
return errors.Errorf("no database with ID %d in backup for table %q",
table.ParentID, table.Name)
}
targetDB = database.Name
}
if _, ok := restoreDBNames[targetDB]; ok {
needsNewParentIDs[targetDB] = append(needsNewParentIDs[targetDB], table.ID)
} else {
var parentID sqlbase.ID
{
existingDatabaseID, err := txn.Get(ctx, sqlbase.MakeNameMetadataKey(keys.RootNamespaceID, targetDB))
if err != nil {
return err
}
if existingDatabaseID.Value == nil {
return errors.Errorf("a database named %q needs to exist to restore table %q",
targetDB, table.Name)
}
newParentID, err := existingDatabaseID.Value.GetInt()
if err != nil {
return err
}
parentID = sqlbase.ID(newParentID)
}
// Check that the table name is _not_ in use.
// This would fail the CPut later anyway, but this yields a prettier error.
if err := CheckTableExists(ctx, txn, parentID, table.Name); err != nil {
return err
}
// Check privileges. These will be checked again in the transaction
// that actually writes the new table descriptors.
{
parentDB, err := sqlbase.GetDatabaseDescFromID(ctx, txn, parentID)
if err != nil {
return errors.Wrapf(err,
"failed to lookup parent DB %d", errors.Safe(parentID))
}
if err := p.CheckPrivilege(ctx, parentDB, privilege.CREATE); err != nil {
return err
}
}
// Create the table rewrite with the new parent ID. We've done all the
// up-front validation that we can.
tableRewrites[table.ID] = &jobspb.RestoreDetails_TableRewrite{ParentID: parentID}
}
}
return nil
}); err != nil {
return nil, err
}
// Allocate new IDs for each database and table.
//
// NB: we do this in a standalone transaction, not one that covers the
// entire restore since restarts would be terrible (and our bulk import
// primitive are non-transactional), but this does mean if something fails
// during restore we've "leaked" the IDs, in that the generator will have
// been incremented.
//
// NB: The ordering of the new IDs must be the same as the old ones,
// otherwise the keys may sort differently after they're rekeyed. We could
// handle this by chunking the AddSSTable calls more finely in Import, but
// it would be a big performance hit.
for _, db := range restoreDBs {
newID, err := sql.GenerateUniqueDescID(ctx, p.ExecCfg().DB)
if err != nil {
return nil, err
}
tableRewrites[db.ID] = &jobspb.RestoreDetails_TableRewrite{TableID: newID}
for _, tableID := range needsNewParentIDs[db.Name] {
tableRewrites[tableID] = &jobspb.RestoreDetails_TableRewrite{ParentID: newID}
}
}
tables := make([]*sqlbase.TableDescriptor, 0, len(tablesByID))
for _, table := range tablesByID {
tables = append(tables, table)
}
sort.Sort(sqlbase.TableDescriptors(tables))
for _, table := range tables {
newTableID, err := sql.GenerateUniqueDescID(ctx, p.ExecCfg().DB)
if err != nil {
return nil, err
}
tableRewrites[table.ID].TableID = newTableID
}
return tableRewrites, nil
}
// CheckTableExists returns an error if a table already exists with given
// parent and name.
func CheckTableExists(
ctx context.Context, txn *client.Txn, parentID sqlbase.ID, name string,
) error {
nameKey := sqlbase.MakeNameMetadataKey(parentID, name)
res, err := txn.Get(ctx, nameKey)
if err != nil {
return err
}
if res.Exists() {
return sqlbase.NewRelationAlreadyExistsError(name)
}
return nil
}
// RewriteTableDescs mutates tables to match the ID and privilege specified
// in tableRewrites, as well as adjusting cross-table references to use the
// new IDs. overrideDB can be specified to set database names in views.
func RewriteTableDescs(
tables []*sqlbase.TableDescriptor, tableRewrites TableRewriteMap, overrideDB string,
) error {
for _, table := range tables {
tableRewrite, ok := tableRewrites[table.ID]
if !ok {
return errors.Errorf("missing table rewrite for table %d", table.ID)
}
if table.IsView() && overrideDB != "" {
// restore checks that all dependencies are also being restored, but if
// the restore is overriding the destination database, qualifiers in the
// view query string may be wrong. Since the destination override is
// applied to everything being restored, anything the view query
// references will be in the override DB post-restore, so all database
// qualifiers in the view query should be replaced with overrideDB.
if err := rewriteViewQueryDBNames(table, overrideDB); err != nil {
return err
}
}
table.ID = tableRewrite.TableID
table.ParentID = tableRewrite.ParentID
if err := table.ForeachNonDropIndex(func(index *sqlbase.IndexDescriptor) error {
// Verify that for any interleaved index being restored, the interleave
// parent is also being restored. Otherwise, the interleave entries in the
// restored IndexDescriptors won't have anything to point to.
// TODO(dan): It seems like this restriction could be lifted by restoring
// stub TableDescriptors for the missing interleave parents.
for j, a := range index.Interleave.Ancestors {
ancestorRewrite, ok := tableRewrites[a.TableID]
if !ok {
return errors.Errorf(
"cannot restore table %q without interleave parent %d", table.Name, a.TableID,
)
}
index.Interleave.Ancestors[j].TableID = ancestorRewrite.TableID
}
for j, c := range index.InterleavedBy {
childRewrite, ok := tableRewrites[c.Table]
if !ok {
return errors.Errorf(
"cannot restore table %q without interleave child table %d", table.Name, c.Table,
)
}
index.InterleavedBy[j].Table = childRewrite.TableID
}
return nil
}); err != nil {
return err
}
// TODO(lucy): deal with outbound foreign key mutations here as well.
origFKs := table.OutboundFKs
table.OutboundFKs = nil
for i := range origFKs {
fk := &origFKs[i]
to := fk.ReferencedTableID
if indexRewrite, ok := tableRewrites[to]; ok {
fk.ReferencedTableID = indexRewrite.TableID
fk.OriginTableID = tableRewrite.TableID
// Also update the table ID on the old FK proto that exists for
// validation, if applicable, so that the validation doesn't fail when
// we downgrade the table descriptors for 19.1 nodes.
// TODO(lucy, jordan): Remove this in 20.1.
if fk.LegacyUpgradedFromOriginReference.Table != 0 {
fk.LegacyUpgradedFromOriginReference.Table = indexRewrite.TableID
}
} else {
// If indexRewrite doesn't exist, the user has specified
// restoreOptSkipMissingFKs. Error checking in the case the user hasn't has
// already been done in allocateTableRewrites.
continue
}
// TODO(dt): if there is an existing (i.e. non-restoring) table with
// a db and name matching the one the FK pointed to at backup, should
// we update the FK to point to it?
table.OutboundFKs = append(table.OutboundFKs, *fk)
}
origInboundFks := table.InboundFKs
table.InboundFKs = nil
for i := range origInboundFks {
ref := &origInboundFks[i]
if refRewrite, ok := tableRewrites[ref.OriginTableID]; ok {
ref.ReferencedTableID = tableRewrite.TableID
ref.OriginTableID = refRewrite.TableID
// Also update the table ID on the old FK proto that exists for
// validation, if applicable, so that the validation doesn't fail when
// we downgrade the table descriptors for 19.1 nodes.
// TODO(lucy, jordan): Remove this in 20.1.
if ref.LegacyUpgradedFromReferencedReference.Table != 0 {
ref.LegacyUpgradedFromReferencedReference.Table = refRewrite.TableID
}
table.InboundFKs = append(table.InboundFKs, *ref)
}
}
for i, dest := range table.DependsOn {
if depRewrite, ok := tableRewrites[dest]; ok {
table.DependsOn[i] = depRewrite.TableID
} else {
// Views with missing dependencies should have been filtered out
// or have caused an error in maybeFilterMissingViews().
return errors.AssertionFailedf(
"cannot restore %q because referenced table %d was not found",
table.Name, dest)
}
}
origRefs := table.DependedOnBy
table.DependedOnBy = nil
for _, ref := range origRefs {
if refRewrite, ok := tableRewrites[ref.ID]; ok {
ref.ID = refRewrite.TableID
table.DependedOnBy = append(table.DependedOnBy, ref)
}
}
// Rewrite sequence references in column descriptors.
for idx := range table.Columns {
var newSeqRefs []sqlbase.ID
col := &table.Columns[idx]
for _, seqID := range col.UsesSequenceIds {
if rewrite, ok := tableRewrites[seqID]; ok {
newSeqRefs = append(newSeqRefs, rewrite.TableID)
} else {
// The referenced sequence isn't being restored.
// Strip the DEFAULT expression and sequence references.
// To get here, the user must have specified 'skip_missing_sequences' --
// otherwise, would have errored out in allocateTableRewrites.
newSeqRefs = []sqlbase.ID{}
col.DefaultExpr = nil
break
}
}
col.UsesSequenceIds = newSeqRefs
}
// since this is a "new" table in eyes of new cluster, any leftover change
// lease is obviously bogus (plus the nodeID is relative to backup cluster).
table.Lease = nil
}
return nil
}
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
request
)
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.ExportStorage
file BackupDescriptor_File
// Only set if entryType is request
files []roachpb.ImportRequest_File
// for progress tracking we assign the spans numbers as they can be executed
// out-of-order based on splitAndScatter's scheduling.
progressIdx int
}
func errOnMissingRange(span intervalccl.Range, start, end hlc.Timestamp) error {
return errors.Errorf(
"no backup covers time [%s,%s) for range [%s,%s) (or backups out of order)",
start, end, roachpb.Key(span.Start), roachpb.Key(span.End),
)
}
// 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 /file3, 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 []BackupDescriptor,
backupLocalityInfo []jobspb.RestoreDetails_BackupLocalityInfo,
lowWaterMark roachpb.Key,
onMissing func(span intervalccl.Range, start, end hlc.Timestamp) error,
) ([]importEntry, 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 := intervalccl.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 intervalccl.Covering
for _, span := range tableSpans {
tableSpanCovering = append(tableSpanCovering, intervalccl.Range{
Start: span.Key,
End: span.EndKey,
Payload: importEntry{
Span: span,
entryType: tableSpan,
},
})
}
backupCoverings := []intervalccl.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 intervalccl.Covering
for _, s := range b.IntroducedSpans {
backupNewSpanCovering = append(backupNewSpanCovering, intervalccl.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 intervalccl.Covering
for _, s := range b.Spans {
backupSpanCovering = append(backupSpanCovering, intervalccl.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 intervalccl.Covering
var storesByLocalityKV map[string]roachpb.ExportStorage
if backupLocalityInfo != nil && backupLocalityInfo[i].URIsByOriginalLocalityKV != nil {
storesByLocalityKV = make(map[string]roachpb.ExportStorage)
for kv, uri := range backupLocalityInfo[i].URIsByOriginalLocalityKV {
conf, err := storageccl.ExportStorageConfFromURI(uri)
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, intervalccl.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 := intervalccl.OverlapCoveringMerge(backupCoverings)
// Translate the output of OverlapCoveringMerge into requests.
var requestEntries []importEntry
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, importEntry{
Span: roachpb.Span{Key: importRange.Start, EndKey: importRange.End},
entryType: request,
files: files,
})
}
}
return requestEntries, maxEndTime, nil
}
// splitAndScatter creates new ranges for importSpans and scatters replicas and
// leaseholders to be as evenly balanced as possible. It does this with some
// amount of parallelism but also staying as close to the order in importSpans
// as possible (the more out of order, the more work is done if a RESTORE job
// loses its lease and has to be restarted).
//
// At a high level, this is accomplished by splitting and scattering large
// "chunks" from the front of importEntries in one goroutine, each of which are
// in turn passed to one of many worker goroutines that split and scatter the
// individual entries.
//
// importEntries are sent to readyForImportCh as they are scattered, so letting
// that channel send block can be used for backpressure on the splits and
// scatters.
//
// TODO(dan): This logic is largely tuned by running BenchmarkRestore2TB. See if
// there's some way to test it without running an O(hour) long benchmark.
func splitAndScatter(
restoreCtx context.Context,
settings *cluster.Settings,
db *client.DB,
kr *storageccl.KeyRewriter,
numClusterNodes int,
importSpans []importEntry,
readyForImportCh chan<- importEntry,
) error {
var span opentracing.Span
ctx, span := tracing.ChildSpan(restoreCtx, "presplit-scatter")
defer tracing.FinishSpan(span)
g := ctxgroup.WithContext(ctx)
// 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([][]importEntry, 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
}
importSpanChunksCh := make(chan []importEntry)
// TODO(jeffreyxiao): Remove this check in 20.1.
// If the cluster supports sticky bits, then we should use the sticky bit to
// ensure that the splits are not automatically split by the merge queue. If
// the cluster does not support sticky bits, we disable the merge queue via
// gossip, so we can just set the split to expire immediately.
stickyBitEnabled := settings.Version.IsActive(cluster.VersionStickyBit)
expirationTime := hlc.Timestamp{}
if stickyBitEnabled {
expirationTime = db.Clock().Now().Add(time.Hour.Nanoseconds(), 0)
}
g.GoCtx(func(ctx context.Context) error {
defer close(importSpanChunksCh)
for idx, importSpanChunk := range importSpanChunks {
// TODO(dan): The structure between this and the below are very
// similar. Dedup.
chunkKey, err := rewriteBackupSpanKey(kr, importSpanChunk[0].Key)
if err != nil {
return err
}
// TODO(dan): Really, this should be splitting the Key of the first
// entry in the _next_ chunk.
log.VEventf(restoreCtx, 1, "presplitting chunk %d of %d", idx, len(importSpanChunks))
if err := db.AdminSplit(ctx, chunkKey, chunkKey, expirationTime); err != nil {
return err
}
log.VEventf(restoreCtx, 1, "scattering chunk %d of %d", idx, len(importSpanChunks))
scatterReq := &roachpb.AdminScatterRequest{
RequestHeader: roachpb.RequestHeaderFromSpan(roachpb.Span{
Key: chunkKey,
EndKey: chunkKey.Next(),
}),
// TODO(dan): This is a bit of a hack, but it seems to be an effective
// one (see the PR that added it for graphs). As of the commit that
// added this, scatter is not very good at actually balancing leases.
// This is likely for two reasons: 1) there's almost certainly some
// regression in scatter's behavior, it used to work much better and 2)
// scatter has to operate by balancing leases for all ranges in a
// cluster, but in RESTORE, we really just want it to be balancing the
// span being restored into.
RandomizeLeases: true,
}
if _, pErr := client.SendWrapped(ctx, db.NonTransactionalSender(), scatterReq); pErr != nil {
// TODO(dan): Unfortunately, Scatter is still too unreliable to
// fail the RESTORE when Scatter fails. I'm uncomfortable that
// this could break entirely and not start failing the tests,
// but on the bright side, it doesn't affect correctness, only
// throughput.
log.Errorf(ctx, "failed to scatter chunk %d: %s", idx, pErr.GoError())
}
select {
case <-ctx.Done():
return ctx.Err()
case importSpanChunksCh <- importSpanChunk:
}
}
return nil
})
// TODO(dan): This tries to cover for a bad scatter by having 2 * the number
// of nodes in the cluster. Is it necessary?
splitScatterWorkers := numClusterNodes * 2
var splitScatterStarted uint64 // Only access using atomic.
for worker := 0; worker < splitScatterWorkers; worker++ {
g.GoCtx(func(ctx context.Context) error {
for importSpanChunk := range importSpanChunksCh {
for _, importSpan := range importSpanChunk {
idx := atomic.AddUint64(&splitScatterStarted, 1)
newSpanKey, err := rewriteBackupSpanKey(kr, importSpan.Span.Key)
if err != nil {
return err
}
// TODO(dan): Really, this should be splitting the Key of