-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathmigrations.go
1904 lines (1782 loc) · 70.2 KB
/
migrations.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.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sqlmigrations
import (
"context"
"fmt"
"sort"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"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/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkv"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sqlmigrations/leasemanager"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
)
var (
leaseDuration = time.Minute
leaseRefreshInterval = leaseDuration / 5
)
// MigrationManagerTestingKnobs contains testing knobs.
type MigrationManagerTestingKnobs struct {
// DisableBackfillMigrations stops applying migrations once
// a migration with 'doesBackfill == true' is encountered.
// TODO(mberhault): we could skip only backfill migrations and dependencies
// if we had some concept of migration dependencies.
DisableBackfillMigrations bool
AfterJobMigration func()
// AlwaysRunJobMigration controls whether to always run the schema change job
// migration regardless of whether it has been marked as complete.
AlwaysRunJobMigration bool
}
// ModuleTestingKnobs is part of the base.ModuleTestingKnobs interface.
func (*MigrationManagerTestingKnobs) ModuleTestingKnobs() {}
var _ base.ModuleTestingKnobs = &MigrationManagerTestingKnobs{}
// backwardCompatibleMigrations is a hard-coded list of migrations to be run on
// startup. They will always be run from top-to-bottom, and because they are
// assumed to be backward-compatible, they will be run regardless of what other
// node versions are currently running within the cluster.
// Migrations must be idempotent: a migration may run successfully but not be
// recorded as completed, causing a second run.
//
// Attention: If a migration is creating new tables, it should also be added to
// the metadata schema written by bootstrap (see addSystemDatabaseToSchema())
// and it should have the includedInBootstrap field set (see comments on that
// field too).
var backwardCompatibleMigrations = []migrationDescriptor{
{
// Introduced in v1.0. Baked into v2.0.
name: "default UniqueID to uuid_v4 in system.eventlog",
},
{
// Introduced in v1.0. Baked into v2.0.
name: "create system.jobs table",
},
{
// Introduced in v1.0. Baked into v2.0.
name: "create system.settings table",
},
{
// Introduced in v1.0. Permanent migration.
name: "enable diagnostics reporting",
workFn: optInToDiagnosticsStatReporting,
clusterWide: true,
},
{
// Introduced in v1.1. Baked into v2.0.
name: "establish conservative dependencies for views #17280 #17269 #17306",
},
{
// Introduced in v1.1. Baked into v2.0.
name: "create system.sessions table",
},
{
// Introduced in v1.1. Permanent migration.
name: "populate initial version cluster setting table entry",
workFn: populateVersionSetting,
clusterWide: true,
},
{
// Introduced in v2.0. Baked into v2.1.
name: "create system.table_statistics table",
newDescriptorIDs: staticIDs(keys.TableStatisticsTableID),
},
{
// Introduced in v2.0. Permanent migration.
name: "add root user",
workFn: addRootUser,
},
{
// Introduced in v2.0. Baked into v2.1.
name: "create system.locations table",
newDescriptorIDs: staticIDs(keys.LocationsTableID),
},
{
// Introduced in v2.0. Baked into v2.1.
name: "add default .meta and .liveness zone configs",
},
{
// Introduced in v2.0. Baked into v2.1.
name: "create system.role_members table",
newDescriptorIDs: staticIDs(keys.RoleMembersTableID),
},
{
// Introduced in v2.0. Permanent migration.
name: "add system.users isRole column and create admin role",
workFn: addAdminRole,
},
{
// Introduced in v2.0, replaced by "ensure admin role privileges in all descriptors"
name: "grant superuser privileges on all objects to the admin role",
},
{
// Introduced in v2.0. Permanent migration.
name: "make root a member of the admin role",
workFn: addRootToAdminRole,
},
{
// Introduced in v2.0. Baked into v2.1.
name: "upgrade table descs to interleaved format version",
},
{
// Introduced in v2.0 alphas then folded into `retiredSettings`.
name: "remove cluster setting `kv.gc.batch_size`",
},
{
// Introduced in v2.0 alphas then folded into `retiredSettings`.
name: "remove cluster setting `kv.transaction.max_intents`",
},
{
// Introduced in v2.0. Baked into v2.1.
name: "add default system.jobs zone config",
},
{
// Introduced in v2.0. Permanent migration.
name: "initialize cluster.secret",
workFn: initializeClusterSecret,
clusterWide: true,
},
{
// Introduced in v2.0. Repeated in v2.1 below.
name: "ensure admin role privileges in all descriptors",
},
{
// Introduced in v2.1, repeat of 2.0 migration to catch mixed-version issues.
// TODO(mberhault): bake into v19.1.
name: "repeat: ensure admin role privileges in all descriptors",
},
{
// Introduced in v2.1.
// TODO(mberhault): bake into v19.1.
name: "disallow public user or role name",
workFn: disallowPublicUserOrRole,
},
{
// Introduced in v2.1.
// TODO(knz): bake this migration into v19.1.
name: "create default databases",
workFn: createDefaultDbs,
newDescriptorIDs: databaseIDs(sqlbase.DefaultDatabaseName, sqlbase.PgDatabaseName),
},
{
// Introduced in v2.1. Baked into 20.1.
name: "add progress to system.jobs",
},
{
// Introduced in v19.1.
// TODO(knz): bake this migration into v19.2
name: "create system.comment table",
workFn: createCommentTable,
// This migration has been introduced some time before 19.2.
includedInBootstrap: clusterversion.VersionByKey(clusterversion.Version19_2),
newDescriptorIDs: staticIDs(keys.CommentsTableID),
},
{
name: "create system.replication_constraint_stats table",
workFn: createReplicationConstraintStatsTable,
// This migration has been introduced some time before 19.2.
includedInBootstrap: clusterversion.VersionByKey(clusterversion.Version19_2),
newDescriptorIDs: staticIDs(keys.ReplicationConstraintStatsTableID),
},
{
name: "create system.replication_critical_localities table",
workFn: createReplicationCriticalLocalitiesTable,
// This migration has been introduced some time before 19.2.
includedInBootstrap: clusterversion.VersionByKey(clusterversion.Version19_2),
newDescriptorIDs: staticIDs(keys.ReplicationCriticalLocalitiesTableID),
},
{
name: "create system.reports_meta table",
workFn: createReportsMetaTable,
// This migration has been introduced some time before 19.2.
includedInBootstrap: clusterversion.VersionByKey(clusterversion.Version19_2),
newDescriptorIDs: staticIDs(keys.ReportsMetaTableID),
},
{
name: "create system.replication_stats table",
workFn: createReplicationStatsTable,
// This migration has been introduced some time before 19.2.
includedInBootstrap: clusterversion.VersionByKey(clusterversion.Version19_2),
newDescriptorIDs: staticIDs(keys.ReplicationStatsTableID),
},
{
// Introduced in v19.1.
// TODO(knz): bake this migration into v19.2.
name: "propagate the ts purge interval to the new setting names",
workFn: retireOldTsPurgeIntervalSettings,
clusterWide: true,
},
{
// Introduced in v19.2.
name: "update system.locations with default location data",
workFn: updateSystemLocationData,
},
{
// Introduced in v19.2, baked into v20.1.
name: "change reports fields from timestamp to timestamptz",
includedInBootstrap: clusterversion.VersionByKey(clusterversion.Version19_2),
},
{
// Introduced in v20.1.
// TODO(ajwerner): Bake this migration into v20.2.
name: "create system.protected_ts_meta table",
workFn: createProtectedTimestampsMetaTable,
includedInBootstrap: clusterversion.VersionByKey(clusterversion.VersionProtectedTimestamps),
newDescriptorIDs: staticIDs(keys.ProtectedTimestampsMetaTableID),
},
{
// Introduced in v20.1.
// TODO(ajwerner): Bake this migration into v20.2.
name: "create system.protected_ts_records table",
workFn: createProtectedTimestampsRecordsTable,
includedInBootstrap: clusterversion.VersionByKey(clusterversion.VersionProtectedTimestamps),
newDescriptorIDs: staticIDs(keys.ProtectedTimestampsRecordsTableID),
},
{
// Introduced in v20.1. Note that this migration
// has v2 appended to it because in 20.1 betas, the migration edited the old
// system.namespace descriptor to change its Name. This wrought havoc,
// causing #47167, which caused 19.2 nodes to fail to be able to read
// system.namespace from SQL queries. However, without changing the old
// descriptor's Name, backup would fail, since backup requires that no two
// descriptors have the same Name. So, in v2 of this migration, we edit
// the name of the new table's Descriptor, calling it
// namespace2, and re-edit the old descriptor's Name to
// be just "namespace" again, to try to help clusters that might have
// upgraded to the 20.1 betas with the problem.
name: "create new system.namespace table v2",
workFn: createNewSystemNamespaceDescriptor,
includedInBootstrap: clusterversion.VersionByKey(clusterversion.VersionNamespaceTableWithSchemas),
newDescriptorIDs: staticIDs(keys.NamespaceTableID),
},
{
// Introduced in v20.10. Replaced in v20.1.1 and v20.2 by the
// StartSystemNamespaceMigration post-finalization-style migration.
name: "migrate system.namespace_deprecated entries into system.namespace",
// workFn: migrateSystemNamespace,
includedInBootstrap: clusterversion.VersionByKey(clusterversion.VersionNamespaceTableWithSchemas),
},
{
// Introduced in v20.1.
name: "create system.role_options table",
workFn: createRoleOptionsTable,
includedInBootstrap: clusterversion.VersionByKey(clusterversion.VersionCreateRolePrivilege),
newDescriptorIDs: staticIDs(keys.RoleOptionsTableID),
},
{
// Introduced in v20.1.
// TODO(andrei): Bake this migration into v20.2.
name: "create statement_diagnostics_requests, statement_diagnostics and " +
"system.statement_bundle_chunks tables",
workFn: createStatementInfoSystemTables,
includedInBootstrap: clusterversion.VersionByKey(clusterversion.VersionStatementDiagnosticsSystemTables),
newDescriptorIDs: staticIDs(keys.StatementBundleChunksTableID,
keys.StatementDiagnosticsRequestsTableID, keys.StatementDiagnosticsTableID),
},
{
// Introduced in v20.1.
name: "remove public permissions on system.comments",
includedInBootstrap: clusterversion.VersionByKey(clusterversion.VersionSchemaChangeJob),
workFn: depublicizeSystemComments,
},
{
// Introduced in v20.1.
name: "add CREATEROLE privilege to admin/root",
workFn: func(ctx context.Context, r runner) error { return addOptionToAdminAndRoot(ctx, r, "CREATEROLE") },
},
{
// Introduced in v20.2.
name: "add created_by columns to system.jobs",
workFn: alterSystemJobsAddCreatedByColumns,
includedInBootstrap: clusterversion.VersionByKey(
clusterversion.VersionAlterSystemJobsAddCreatedByColumns),
},
{
// Introduced in v20.2.
name: "create new system.scheduled_jobs table",
workFn: createScheduledJobsTable,
includedInBootstrap: clusterversion.VersionByKey(clusterversion.VersionAddScheduledJobsTable),
newDescriptorIDs: staticIDs(keys.ScheduledJobsTableID),
},
{
// Introduced in v20.2.
name: "add SETPASSWORD privilege to admin/root",
workFn: func(ctx context.Context, r runner) error { return addOptionToAdminAndRoot(ctx, r, "SETPASSWORD") },
},
}
func staticIDs(
ids ...sqlbase.ID,
) func(ctx context.Context, db db, codec keys.SQLCodec) ([]sqlbase.ID, error) {
return func(ctx context.Context, db db, codec keys.SQLCodec) ([]sqlbase.ID, error) { return ids, nil }
}
func databaseIDs(
names ...string,
) func(ctx context.Context, db db, codec keys.SQLCodec) ([]sqlbase.ID, error) {
return func(ctx context.Context, db db, codec keys.SQLCodec) ([]sqlbase.ID, error) {
var ids []sqlbase.ID
for _, name := range names {
// This runs as part of an older migration (introduced in 2.1). We use
// the DeprecatedDatabaseKey, and let the 20.1 migration handle moving
// from the old namespace table into the new one.
kv, err := db.Get(ctx, sqlbase.NewDeprecatedDatabaseKey(name).Key(codec))
if err != nil {
return nil, err
}
ids = append(ids, sqlbase.ID(kv.ValueInt()))
}
return ids, nil
}
}
// migrationDescriptor describes a single migration hook that's used to modify
// some part of the cluster state when the CockroachDB version is upgraded.
// See docs/RFCs/cluster_upgrade_tool.md for details.
type migrationDescriptor struct {
// name must be unique amongst all hard-coded migrations.
// ATTENTION: A migration's name can never be changed. It is included in a key
// marking a migration as completed.
name string
// workFn must be idempotent so that we can safely re-run it if a node failed
// while running it. nil if the migration has been "backed in" and is no
// longer to be performed at cluster startup.
workFn func(context.Context, runner) error
// includedInBootstrap is set for migrations that need to be performed for
// updating old clusters, but are also covered by the MetadataSchema that gets
// created by hand for a new cluster when it bootstraps itself. This kind of
// duplication between a migration and the MetadataSchema is useful for
// migrations that create system descriptor - for new clusters (particularly
// for tests) we want to create these tables by hand so that a corresponding
// range is created at bootstrap time. Otherwise, we'd have the split queue
// asynchronously creating some ranges which is annoying for tests.
//
// Generally when setting this field you'll want to introduce a new cluster
// version.
includedInBootstrap roachpb.Version
// doesBackfill should be set to true if the migration triggers a backfill.
doesBackfill bool
// clusterWide migrations are only run by the system tenant. All other
// migrations are run by each individual tenant. clusterWide migrations
// typically have to do with cluster settings, which is a cluster-wide
// concept.
clusterWide bool
// newDescriptorIDs is a function that returns the IDs of any additional
// descriptors that were added by this migration. This is needed to automate
// certain tests, which check the number of ranges/descriptors present on
// server bootup.
newDescriptorIDs func(ctx context.Context, db db, codec keys.SQLCodec) ([]sqlbase.ID, error)
}
func init() {
// Ensure that all migrations have unique names.
names := make(map[string]struct{}, len(backwardCompatibleMigrations))
for _, migration := range backwardCompatibleMigrations {
name := migration.name
if _, ok := names[name]; ok {
log.Fatalf(context.Background(), "duplicate sql migration %q", name)
}
names[name] = struct{}{}
}
}
type runner struct {
db db
codec keys.SQLCodec
sqlExecutor *sql.InternalExecutor
settings *cluster.Settings
}
func (r runner) execAsRoot(ctx context.Context, opName, stmt string, qargs ...interface{}) error {
_, err := r.sqlExecutor.ExecEx(ctx, opName, nil, /* txn */
sqlbase.InternalExecutorSessionDataOverride{
User: security.RootUser,
},
stmt, qargs...)
return err
}
func (r runner) execAsRootWithRetry(
ctx context.Context, opName string, stmt string, qargs ...interface{},
) error {
// Retry a limited number of times because returning an error and letting
// the node kill itself is better than holding the migration lease for an
// arbitrarily long time.
var err error
for retry := retry.Start(retry.Options{MaxRetries: 5}); retry.Next(); {
err := r.execAsRoot(ctx, opName, stmt, qargs...)
if err == nil {
break
}
log.Warningf(ctx, "failed to run %s: %v", stmt, err)
}
return err
}
// leaseManager is defined just to allow us to use a fake client.LeaseManager
// when testing this package.
type leaseManager interface {
AcquireLease(ctx context.Context, key roachpb.Key) (*leasemanager.Lease, error)
ExtendLease(ctx context.Context, l *leasemanager.Lease) error
ReleaseLease(ctx context.Context, l *leasemanager.Lease) error
TimeRemaining(l *leasemanager.Lease) time.Duration
}
// db is defined just to allow us to use a fake client.DB when testing this
// package.
type db interface {
Scan(ctx context.Context, begin, end interface{}, maxRows int64) ([]kv.KeyValue, error)
Get(ctx context.Context, key interface{}) (kv.KeyValue, error)
Put(ctx context.Context, key, value interface{}) error
Txn(ctx context.Context, retryable func(ctx context.Context, txn *kv.Txn) error) error
}
// Manager encapsulates the necessary functionality for handling migrations
// of data in the cluster.
type Manager struct {
stopper *stop.Stopper
leaseManager leaseManager
db db
codec keys.SQLCodec
sqlExecutor *sql.InternalExecutor
testingKnobs MigrationManagerTestingKnobs
settings *cluster.Settings
jobRegistry *jobs.Registry
}
// NewManager initializes and returns a new Manager object.
func NewManager(
stopper *stop.Stopper,
db *kv.DB,
codec keys.SQLCodec,
executor *sql.InternalExecutor,
clock *hlc.Clock,
testingKnobs MigrationManagerTestingKnobs,
clientID string,
settings *cluster.Settings,
registry *jobs.Registry,
) *Manager {
opts := leasemanager.Options{
ClientID: clientID,
LeaseDuration: leaseDuration,
}
return &Manager{
stopper: stopper,
leaseManager: leasemanager.New(db, clock, opts),
db: db,
codec: codec,
sqlExecutor: executor,
testingKnobs: testingKnobs,
settings: settings,
jobRegistry: registry,
}
}
// ExpectedDescriptorIDs returns the list of all expected system descriptor IDs,
// including those added by completed migrations. This is needed for certain
// tests, which check the number of ranges and system tables at node startup.
//
// NOTE: This value may be out-of-date if another node is actively running
// migrations, and so should only be used in test code where the migration
// lifecycle is tightly controlled.
func ExpectedDescriptorIDs(
ctx context.Context,
db db,
codec keys.SQLCodec,
defaultZoneConfig *zonepb.ZoneConfig,
defaultSystemZoneConfig *zonepb.ZoneConfig,
) (sqlbase.IDs, error) {
completedMigrations, err := getCompletedMigrations(ctx, db, codec)
if err != nil {
return nil, err
}
descriptorIDs := sqlbase.MakeMetadataSchema(codec, defaultZoneConfig, defaultSystemZoneConfig).DescriptorIDs()
for _, migration := range backwardCompatibleMigrations {
// Is the migration not creating descriptors?
if migration.newDescriptorIDs == nil ||
// Is the migration included in the metadata schema considered above?
(migration.includedInBootstrap != roachpb.Version{}) {
continue
}
if _, ok := completedMigrations[string(migrationKey(codec, migration))]; ok {
newIDs, err := migration.newDescriptorIDs(ctx, db, codec)
if err != nil {
return nil, err
}
descriptorIDs = append(descriptorIDs, newIDs...)
}
}
sort.Sort(descriptorIDs)
return descriptorIDs, nil
}
// EnsureMigrations should be run during node startup to ensure that all
// required migrations have been run (and running all those that are definitely
// safe to run).
func (m *Manager) EnsureMigrations(ctx context.Context, bootstrapVersion roachpb.Version) error {
// First, check whether there are any migrations that need to be run.
completedMigrations, err := getCompletedMigrations(ctx, m.db, m.codec)
if err != nil {
return err
}
allMigrationsCompleted := true
for _, migration := range backwardCompatibleMigrations {
if !m.shouldRunMigration(migration, bootstrapVersion) {
continue
}
if m.testingKnobs.DisableBackfillMigrations && migration.doesBackfill {
log.Infof(ctx, "ignoring migrations after (and including) %s due to testing knob",
migration.name)
break
}
key := migrationKey(m.codec, migration)
if _, ok := completedMigrations[string(key)]; !ok {
allMigrationsCompleted = false
}
}
if allMigrationsCompleted {
return nil
}
// If there are any, grab the migration lease to ensure that only one
// node is ever doing migrations at a time.
// Note that we shouldn't ever let client.LeaseNotAvailableErrors cause us
// to stop trying, because if we return an error the server will be shut down,
// and this server being down may prevent the leaseholder from finishing.
var lease *leasemanager.Lease
if log.V(1) {
log.Info(ctx, "trying to acquire lease")
}
for r := retry.StartWithCtx(ctx, base.DefaultRetryOptions()); r.Next(); {
lease, err = m.leaseManager.AcquireLease(ctx, m.codec.MigrationLeaseKey())
if err == nil {
break
}
log.Infof(ctx, "failed attempt to acquire migration lease: %s", err)
}
if err != nil {
return errors.Wrapf(err, "failed to acquire lease for running necessary migrations")
}
// Ensure that we hold the lease throughout the migration process and release
// it when we're done.
done := make(chan interface{}, 1)
defer func() {
done <- nil
if log.V(1) {
log.Info(ctx, "trying to release the lease")
}
if err := m.leaseManager.ReleaseLease(ctx, lease); err != nil {
log.Errorf(ctx, "failed to release migration lease: %s", err)
}
}()
if err := m.stopper.RunAsyncTask(ctx, "migrations.Manager: lease watcher",
func(ctx context.Context) {
select {
case <-done:
return
case <-time.After(leaseRefreshInterval):
if err := m.leaseManager.ExtendLease(ctx, lease); err != nil {
log.Warningf(ctx, "unable to extend ownership of expiration lease: %s", err)
}
if m.leaseManager.TimeRemaining(lease) < leaseRefreshInterval {
// Do one last final check of whether we're done - it's possible that
// ReleaseLease can sneak in and execute ahead of ExtendLease even if
// the ExtendLease started first (making for an unexpected value error),
// and doing this final check can avoid unintended shutdowns.
select {
case <-done:
return
default:
// Note that we may be able to do better than this by influencing the
// deadline of migrations' transactions based on the lease expiration
// time, but simply kill the process for now for the sake of simplicity.
log.Fatal(ctx, "not enough time left on migration lease, terminating for safety")
}
}
}
}); err != nil {
return err
}
// Re-get the list of migrations in case any of them were completed between
// our initial check and our grabbing of the lease.
completedMigrations, err = getCompletedMigrations(ctx, m.db, m.codec)
if err != nil {
return err
}
startTime := timeutil.Now().String()
r := runner{
db: m.db,
codec: m.codec,
sqlExecutor: m.sqlExecutor,
settings: m.settings,
}
for _, migration := range backwardCompatibleMigrations {
if !m.shouldRunMigration(migration, bootstrapVersion) {
continue
}
key := migrationKey(m.codec, migration)
if _, ok := completedMigrations[string(key)]; ok {
continue
}
if m.testingKnobs.DisableBackfillMigrations && migration.doesBackfill {
log.Infof(ctx, "ignoring migrations after (and including) %s due to testing knob",
migration.name)
break
}
if log.V(1) {
log.Infof(ctx, "running migration %q", migration.name)
}
if err := migration.workFn(ctx, r); err != nil {
return errors.Wrapf(err, "failed to run migration %q", migration.name)
}
log.VEventf(ctx, 1, "persisting record of completing migration %s", migration.name)
if err := m.db.Put(ctx, key, startTime); err != nil {
return errors.Wrapf(err, "failed to persist record of completing migration %q",
migration.name)
}
}
return nil
}
func (m *Manager) shouldRunMigration(
migration migrationDescriptor, bootstrapVersion roachpb.Version,
) bool {
if migration.workFn == nil {
// The migration has been baked in.
return false
}
minVersion := migration.includedInBootstrap
if minVersion != (roachpb.Version{}) && !bootstrapVersion.Less(minVersion) {
// The migration is unnecessary.
return false
}
if migration.clusterWide && !m.codec.ForSystemTenant() {
// The migration is a cluster-wide migration and we are not the
// system tenant.
return false
}
return true
}
var schemaChangeJobMigrationName = "upgrade schema change job format"
func schemaChangeJobMigrationKey(codec keys.SQLCodec) roachpb.Key {
return append(codec.MigrationKeyPrefix(), roachpb.RKey(schemaChangeJobMigrationName)...)
}
var systemNamespaceMigrationName = "upgrade system.namespace post-20.1-finalization"
func systemNamespaceMigrationKey(codec keys.SQLCodec) roachpb.Key {
return append(codec.MigrationKeyPrefix(), roachpb.RKey(systemNamespaceMigrationName)...)
}
// schemaChangeJobMigrationKeyForTable returns a key prefixed with
// schemaChangeJobMigrationKey for a specific table, to store the completion
// status for adding a new job if the table was being added or needed to drain
// names.
func schemaChangeJobMigrationKeyForTable(codec keys.SQLCodec, tableID sqlbase.ID) roachpb.Key {
return encoding.EncodeUint32Ascending(schemaChangeJobMigrationKey(codec), uint32(tableID))
}
// StartSchemaChangeJobMigration starts an async task to run the migration that
// upgrades 19.2-style jobs to the 20.1 job format, so that the jobs can be
// adopted by the job registry. The task first waits until the upgrade to 20.1
// is finalized before running the migration. The migration is retried until
// it succeeds (on any node).
func (m *Manager) StartSchemaChangeJobMigration(ctx context.Context) error {
migrationKey := schemaChangeJobMigrationKey(m.codec)
return m.stopper.RunAsyncTask(ctx, "run-schema-change-job-migration", func(ctx context.Context) {
log.Info(ctx, "starting wait for upgrade finalization before schema change job migration")
// First wait for the cluster to finalize the upgrade to 20.1. These values
// were chosen to be similar to the retry loop for finalizing the cluster
// upgrade.
waitRetryOpts := retry.Options{
InitialBackoff: 10 * time.Second,
MaxBackoff: 10 * time.Second,
Closer: m.stopper.ShouldQuiesce(),
}
for retry := retry.StartWithCtx(ctx, waitRetryOpts); retry.Next(); {
if m.settings.Version.IsActive(ctx, clusterversion.VersionSchemaChangeJob) {
break
}
}
select {
case <-m.stopper.ShouldQuiesce():
return
default:
}
log.VEventf(ctx, 2, "detected upgrade finalization")
if !m.testingKnobs.AlwaysRunJobMigration {
// Check whether this migration has already been completed.
if kv, err := m.db.Get(ctx, migrationKey); err != nil {
log.Infof(ctx, "error getting record of schema change job migration: %s", err.Error())
} else if kv.Exists() {
log.Infof(ctx, "schema change job migration already complete")
return
}
}
// Now run the migration. This is retried indefinitely until it finishes.
log.Infof(ctx, "starting schema change job migration")
r := runner{
db: m.db,
codec: m.codec,
sqlExecutor: m.sqlExecutor,
settings: m.settings,
}
migrationRetryOpts := retry.Options{
InitialBackoff: 1 * time.Minute,
MaxBackoff: 10 * time.Minute,
Closer: m.stopper.ShouldQuiesce(),
}
startTime := timeutil.Now().String()
for migRetry := retry.Start(migrationRetryOpts); migRetry.Next(); {
migrateCtx, _ := m.stopper.WithCancelOnQuiesce(context.Background())
migrateCtx = logtags.AddTag(migrateCtx, "schema-change-job-migration", nil)
if err := migrateSchemaChangeJobs(migrateCtx, r, m.jobRegistry); err != nil {
log.Errorf(ctx, "error attempting running schema change job migration, will retry: %s %s", err.Error(), startTime)
continue
}
log.Infof(ctx, "schema change job migration completed")
if err := m.db.Put(ctx, migrationKey, startTime); err != nil {
log.Warningf(ctx, "error persisting record of schema change job migration, will retry: %s", err.Error())
}
break
}
if fn := m.testingKnobs.AfterJobMigration; fn != nil {
fn()
}
})
}
var systemNamespaceMigrationEnabled = settings.RegisterBoolSetting(
"testing.system_namespace_migration.enabled",
"internal testing only: disable the system namespace migration",
true,
)
// StartSystemNamespaceMigration starts an async task to run the migration that
// migrates entries from system.namespace (descriptor 2) to system.namespace2
// (descriptor 30). The task first waits until the upgrade to 20.1 is finalized
// before running the migration. The migration is retried until it succeeds (on
// any node).
func (m *Manager) StartSystemNamespaceMigration(
ctx context.Context, bootstrapVersion roachpb.Version,
) error {
if !bootstrapVersion.Less(clusterversion.VersionByKey(clusterversion.VersionNamespaceTableWithSchemas)) {
// Our bootstrap version is equal to or greater than 20.1, where no old
// namespace table is created: we can skip this migration.
return nil
}
return m.stopper.RunAsyncTask(ctx, "run-system-namespace-migration", func(ctx context.Context) {
log.Info(ctx, "starting wait for upgrade finalization before system.namespace migration")
// First wait for the cluster to finalize the upgrade to 20.1. These values
// were chosen to be similar to the retry loop for finalizing the cluster
// upgrade.
waitRetryOpts := retry.Options{
InitialBackoff: 10 * time.Second,
MaxBackoff: 10 * time.Second,
Closer: m.stopper.ShouldQuiesce(),
}
for retry := retry.StartWithCtx(ctx, waitRetryOpts); retry.Next(); {
if !systemNamespaceMigrationEnabled.Get(&m.settings.SV) {
continue
}
if m.settings.Version.IsActive(ctx, clusterversion.VersionNamespaceTableWithSchemas) {
break
}
}
select {
case <-m.stopper.ShouldQuiesce():
return
default:
}
log.VEventf(ctx, 2, "detected upgrade finalization for system.namespace migration")
migrationKey := systemNamespaceMigrationKey(m.codec)
// Check whether this migration has already been completed.
if kv, err := m.db.Get(ctx, migrationKey); err != nil {
log.Infof(ctx, "error getting record of system.namespace migration: %s", err.Error())
} else if kv.Exists() {
log.Infof(ctx, "system.namespace migration already complete")
return
}
// Now run the migration. This is retried indefinitely until it finishes.
log.Infof(ctx, "starting system.namespace migration")
r := runner{
db: m.db,
codec: m.codec,
sqlExecutor: m.sqlExecutor,
settings: m.settings,
}
migrationRetryOpts := retry.Options{
InitialBackoff: 1 * time.Minute,
MaxBackoff: 10 * time.Minute,
Closer: m.stopper.ShouldQuiesce(),
}
startTime := timeutil.Now().String()
for migRetry := retry.Start(migrationRetryOpts); migRetry.Next(); {
if err := m.migrateSystemNamespace(ctx, migrationKey, r, startTime); err != nil {
log.Errorf(ctx, "error attempting running system.namespace migration, will retry: %s %s", err.Error(),
startTime)
continue
}
break
}
})
}
// migrateSystemNamespace migrates entries from the deprecated system.namespace
// table to the new one, which includes a parentSchemaID column. Each database
// entry is copied to the new table along with a corresponding entry for the
// 'public' schema. Each table entry is copied over with the public schema as
// as its parentSchemaID.
//
// Only entries that do not exist in the new table are copied.
//
// New database and table entries continue to be written to the deprecated
// namespace table until VersionNamespaceTableWithSchemas is active. This means
// that an additional migration will be necessary in 20.2 to catch any new
// entries which may have been missed by this one. In the meantime, namespace
// lookups fall back to the deprecated table if a name is not found in the new
// one.
func (m *Manager) migrateSystemNamespace(
ctx context.Context, migrationKey roachpb.Key, r runner, startTime string,
) error {
migrateCtx, cancel := m.stopper.WithCancelOnQuiesce(ctx)
defer cancel()
migrateCtx = logtags.AddTag(migrateCtx, "system-namespace-migration", nil)
// Loop until there's no more work to be done.
workLeft := true
for workLeft {
if err := m.db.Txn(migrateCtx, func(ctx context.Context, txn *kv.Txn) error {
// Check again to see if someone else wrote the migration key.
if kv, err := txn.Get(ctx, migrationKey); err != nil {
log.Infof(ctx, "error getting record of system.namespace migration: %s", err.Error())
// Retry the migration.
return err
} else if kv.Exists() {
// Give up, no work to be done.
log.Infof(ctx, "system.namespace migration already complete")
return nil
}
// Fetch all entries that are not present in the new namespace table. Each
// of these entries will be copied to the new table.
//
// Note that we are very careful to always delete from both namespace tables
// in 20.1, so there's no possibility that we'll be overwriting a deleted
// table that existed in the old table and the new table but was deleted
// from only the new table.
const batchSize = 1000
q := fmt.Sprintf(
`SELECT "parentID", name, id FROM [%d AS namespace_deprecated]
WHERE id NOT IN (SELECT id FROM [%d AS namespace]) LIMIT %d`,
sqlbase.DeprecatedNamespaceTable.ID, sqlbase.NamespaceTable.ID, batchSize+1)
rows, err := r.sqlExecutor.QueryEx(
ctx, "read-deprecated-namespace-table", txn,
sqlbase.InternalExecutorSessionDataOverride{
User: security.RootUser,
},
q)
if err != nil {
return err
}
log.Infof(ctx, "Migrating system.namespace chunk with %d rows", len(rows))
for i, row := range rows {
workLeft = false
// We found some rows from the query, which means that we can't quit
// just yet.
if i >= batchSize {
workLeft = true
// Just process 1000 rows at a time.
break
}
parentID := sqlbase.ID(tree.MustBeDInt(row[0]))
name := string(tree.MustBeDString(row[1]))
id := sqlbase.ID(tree.MustBeDInt(row[2]))
if parentID == keys.RootNamespaceID {
// This row represents a database. Add it to the new namespace table.
databaseKey := sqlbase.NewDatabaseKey(name)
if err := txn.Put(ctx, databaseKey.Key(r.codec), id); err != nil {
return err
}
// Also create a 'public' schema for this database.
schemaKey := sqlbase.NewSchemaKey(id, "public")
log.VEventf(ctx, 2, "Migrating system.namespace entry for database %s", name)
if err := txn.Put(ctx, schemaKey.Key(r.codec), keys.PublicSchemaID); err != nil {
return err
}
} else {
// This row represents a table. Add it to the new namespace table with the
// schema set to 'public'.
if id == keys.DeprecatedNamespaceTableID {
// The namespace table itself was already handled in
// createNewSystemNamespaceDescriptor. Do not overwrite it with the
// deprecated ID.
continue
}
tableKey := sqlbase.NewTableKey(parentID, keys.PublicSchemaID, name)
log.VEventf(ctx, 2, "Migrating system.namespace entry for table %s", name)
if err := txn.Put(ctx, tableKey.Key(r.codec), id); err != nil {
return err
}
}
}
return nil
}); err != nil {
return err
}
}
// No more work to be done.
log.Infof(migrateCtx, "system.namespace migration completed")
if err := m.db.Put(migrateCtx, migrationKey, startTime); err != nil {
log.Warningf(migrateCtx, "error persisting record of system.namespace migration, will retry: %s", err.Error())
return err
}
return nil
}
// migrateSchemaChangeJobs runs the schema change job migration. The migration
// has two steps. In the first step, we scan the jobs table for all
// non-Succeeded jobs; for each job, it looks up the associated table and uses
// the table descriptor state to update the job payload appropriately. For jobs
// that are waiting for GC for dropped tables, indexes, etc., we mark the
// existing job as completed and create a new GC job. In the second step, we
// get all the descriptors and all running jobs, and create a new job for all
// tables that are either in the ADD state or have draining names but which
// have no running jobs, since tables in those states in 19.2 would have been
// processed by the schema changer.
func migrateSchemaChangeJobs(ctx context.Context, r runner, registry *jobs.Registry) error {
// Get all jobs that aren't Succeeded and evaluate whether they need a
// migration. (Jobs that are canceled in 19.2 could still have in-progress
// schema changes.)
rows, err := r.sqlExecutor.QueryEx(
ctx, "jobs-for-migration", nil, /* txn */
sqlbase.InternalExecutorSessionDataOverride{User: security.RootUser},