-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
schema_changer.go
2061 lines (1863 loc) · 67.5 KB
/
schema_changer.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 2015 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package sql
import (
"context"
"fmt"
"math"
"math/rand"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/config"
"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/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/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/grpcutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/logtags"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/pkg/errors"
)
var schemaChangeLeaseDuration = settings.RegisterNonNegativeDurationSetting(
"schemachanger.lease.duration",
"the duration of a schema change lease",
time.Minute*5,
)
var schemaChangeLeaseRenewFraction = settings.RegisterFloatSetting(
"schemachanger.lease.renew_fraction",
"the fraction of schemachanger.lease_duration remaining to trigger a renew of the lease",
0.5,
)
// This is a delay [0.9 * asyncSchemaChangeDelay, 1.1 * asyncSchemaChangeDelay)
// added to an attempt to run a schema change via the asynchronous path.
// This delay allows the synchronous path to execute the schema change
// in all likelihood. We'd like the synchronous path to execute
// the schema change so that it doesn't have to poll and wait for
// another node to execute the schema change. Polling can add a polling
// delay to the normal execution of a schema change. This interval is also
// used to reattempt execution of a schema change. We don't want this to
// be too low because once a node has started executing a schema change
// the other nodes should not cause a storm by rapidly try to grab the
// schema change lease.
//
// TODO(mjibson): Refine the job coordinator to elect a new job coordinator
// on coordinator failure without causing a storm of polling requests
// attempting to become the job coordinator.
const asyncSchemaChangeDelay = 1 * time.Minute
const (
// RunningStatusDrainingNames is for jobs that are currently in progress and
// are draining names.
RunningStatusDrainingNames jobs.RunningStatus = "draining names"
// RunningStatusWaitingGC is for jobs that are currently in progress and
// are waiting for the GC interval to expire
RunningStatusWaitingGC jobs.RunningStatus = "waiting for GC TTL"
// RunningStatusCompaction is for jobs that are currently in progress and
// undergoing RocksDB compaction
RunningStatusCompaction jobs.RunningStatus = "RocksDB compaction"
// RunningStatusDeleteOnly is for jobs that are currently waiting on
// the cluster to converge to seeing the schema element in the DELETE_ONLY
// state.
RunningStatusDeleteOnly jobs.RunningStatus = "waiting in DELETE-ONLY"
// RunningStatusDeleteAndWriteOnly is for jobs that are currently waiting on
// the cluster to converge to seeing the schema element in the
// DELETE_AND_WRITE_ONLY state.
RunningStatusDeleteAndWriteOnly jobs.RunningStatus = "waiting in DELETE-AND-WRITE_ONLY"
// RunningStatusBackfill is for jobs that are currently running a backfill
// for a schema element.
RunningStatusBackfill jobs.RunningStatus = "populating schema"
// RunningStatusValidation is for jobs that are currently validating
// a schema element.
RunningStatusValidation jobs.RunningStatus = "validating schema"
)
type droppedIndex struct {
indexID sqlbase.IndexID
dropTime int64
deadline int64
}
// SchemaChanger is used to change the schema on a table.
type SchemaChanger struct {
tableID sqlbase.ID
mutationID sqlbase.MutationID
nodeID roachpb.NodeID
db *client.DB
leaseMgr *LeaseManager
// The SchemaChangeManager can attempt to execute this schema
// changer after this time.
execAfter time.Time
// table.DropTime.
dropTime int64
dropIndexTimes []droppedIndex
testingKnobs *SchemaChangerTestingKnobs
distSQLPlanner *DistSQLPlanner
jobRegistry *jobs.Registry
// Keep a reference to the job related to this schema change
// so that we don't need to read the job again while updating
// the status of the job. This job can be one of two jobs: the
// original schema change job for the sql command, or the
// rollback job for the rollback of the schema change.
job *jobs.Job
// Caches updated by DistSQL.
rangeDescriptorCache *kv.RangeDescriptorCache
leaseHolderCache *kv.LeaseHolderCache
clock *hlc.Clock
settings *cluster.Settings
execCfg *ExecutorConfig
ieFactory sqlutil.SessionBoundInternalExecutorFactory
}
// NewSchemaChangerForTesting only for tests.
func NewSchemaChangerForTesting(
tableID sqlbase.ID,
mutationID sqlbase.MutationID,
nodeID roachpb.NodeID,
db client.DB,
leaseMgr *LeaseManager,
jobRegistry *jobs.Registry,
execCfg *ExecutorConfig,
settings *cluster.Settings,
) SchemaChanger {
return SchemaChanger{
tableID: tableID,
mutationID: mutationID,
nodeID: nodeID,
db: &db,
leaseMgr: leaseMgr,
jobRegistry: jobRegistry,
settings: settings,
execCfg: execCfg,
}
}
func (sc *SchemaChanger) createSchemaChangeLease() sqlbase.TableDescriptor_SchemaChangeLease {
return sqlbase.TableDescriptor_SchemaChangeLease{
NodeID: sc.nodeID,
ExpirationTime: timeutil.Now().Add(
schemaChangeLeaseDuration.Get(&sc.settings.SV),
).UnixNano(),
}
}
// isPermanentSchemaChangeError returns true if the error results in
// a permanent failure of a schema change. This function is a whitelist
// instead of a blacklist: only known safe errors are confirmed to not be
// permanent errors. Anything unknown is assumed to be permanent.
func isPermanentSchemaChangeError(err error) bool {
if err == nil {
return false
}
err = errors.Cause(err)
if grpcutil.IsClosedConnection(err) {
return false
}
// Ignore error thrown because of a read at a very old timestamp.
// The Backfill will grab a new timestamp to read at for the rest
// of the backfill.
if strings.Contains(err.Error(), "must be after replica GC threshold") {
return false
}
if pgerror.IsSQLRetryableError(err) {
return false
}
switch err {
case
context.Canceled,
context.DeadlineExceeded,
errExistingSchemaChangeLease,
errExpiredSchemaChangeLease,
errNotHitGCTTLDeadline,
errSchemaChangeDuringDrain,
errSchemaChangeNotFirstInLine:
return false
}
switch err := err.(type) {
case errTableVersionMismatch:
return false
case *pgerror.Error:
switch err.Code {
case pgerror.CodeSerializationFailureError, pgerror.CodeConnectionFailureError:
return false
case pgerror.CodeInternalError:
if strings.Contains(err.Message, context.DeadlineExceeded.Error()) {
return false
}
}
}
return true
}
var (
errExistingSchemaChangeLease = pgerror.Newf(pgerror.CodeDataExceptionError, "an outstanding schema change lease exists")
errExpiredSchemaChangeLease = pgerror.Newf(pgerror.CodeDataExceptionError, "the schema change lease has expired")
errSchemaChangeNotFirstInLine = pgerror.Newf(pgerror.CodeDataExceptionError, "schema change not first in line")
errNotHitGCTTLDeadline = pgerror.Newf(pgerror.CodeDataExceptionError, "not hit gc ttl deadline")
errSchemaChangeDuringDrain = pgerror.Newf(pgerror.CodeDataExceptionError, "a schema change ran during the drain phase, re-increment")
)
func shouldLogSchemaChangeError(err error) bool {
return err != errExistingSchemaChangeLease &&
err != errSchemaChangeNotFirstInLine &&
err != errNotHitGCTTLDeadline
}
type errTableVersionMismatch struct {
version sqlbase.DescriptorVersion
expected sqlbase.DescriptorVersion
}
func makeErrTableVersionMismatch(version, expected sqlbase.DescriptorVersion) error {
return errors.WithStack(errTableVersionMismatch{
version: version,
expected: expected,
})
}
func (e errTableVersionMismatch) Error() string {
return fmt.Sprintf("table version mismatch: %d, expected: %d", e.version, e.expected)
}
// AcquireLease acquires a schema change lease on the table if
// an unexpired lease doesn't exist. It returns the lease.
func (sc *SchemaChanger) AcquireLease(
ctx context.Context,
) (sqlbase.TableDescriptor_SchemaChangeLease, error) {
var lease sqlbase.TableDescriptor_SchemaChangeLease
err := sc.db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
if err := txn.SetSystemConfigTrigger(); err != nil {
return err
}
tableDesc, err := sqlbase.GetTableDescFromID(ctx, txn, sc.tableID)
if err != nil {
return err
}
// A second to deal with the time uncertainty across nodes.
// It is perfectly valid for two or more goroutines to hold a valid
// lease and execute a schema change in parallel, because schema
// changes are executed using transactions that run sequentially.
// This just reduces the probability of a write collision.
expirationTimeUncertainty := time.Second
if tableDesc.Lease != nil {
if timeutil.Unix(0, tableDesc.Lease.ExpirationTime).Add(expirationTimeUncertainty).After(timeutil.Now()) {
return errExistingSchemaChangeLease
}
log.Infof(ctx, "Overriding existing expired lease %v", tableDesc.Lease)
}
lease = sc.createSchemaChangeLease()
tableDesc.Lease = &lease
return txn.Put(ctx, sqlbase.MakeDescMetadataKey(tableDesc.ID), sqlbase.WrapDescriptor(tableDesc))
})
return lease, err
}
func (sc *SchemaChanger) findTableWithLease(
ctx context.Context, txn *client.Txn, lease sqlbase.TableDescriptor_SchemaChangeLease,
) (*sqlbase.TableDescriptor, error) {
tableDesc, err := sqlbase.GetTableDescFromID(ctx, txn, sc.tableID)
if err != nil {
return nil, err
}
if tableDesc.Lease == nil {
return nil, pgerror.AssertionFailedf("no lease present for tableID: %d", log.Safe(sc.tableID))
}
if *tableDesc.Lease != lease {
log.Errorf(ctx, "table: %d has lease: %v, expected: %v", sc.tableID, tableDesc.Lease, lease)
return nil, errExpiredSchemaChangeLease
}
return tableDesc, nil
}
// ReleaseLease releases the table lease if it is the one registered with
// the table descriptor.
func (sc *SchemaChanger) ReleaseLease(
ctx context.Context, lease sqlbase.TableDescriptor_SchemaChangeLease,
) error {
return sc.db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
tableDesc, err := sc.findTableWithLease(ctx, txn, lease)
if err != nil {
return err
}
tableDesc.Lease = nil
if err := txn.SetSystemConfigTrigger(); err != nil {
return err
}
return txn.Put(ctx, sqlbase.MakeDescMetadataKey(tableDesc.ID), sqlbase.WrapDescriptor(tableDesc))
})
}
// ExtendLease for the current leaser. This needs to be called often while
// doing a schema change to prevent more than one node attempting to apply a
// schema change (which is still safe, but unwise). It updates existingLease
// with the new lease.
func (sc *SchemaChanger) ExtendLease(
ctx context.Context, existingLease *sqlbase.TableDescriptor_SchemaChangeLease,
) error {
// Check if there is still time on this lease.
minDuration := time.Duration(float64(schemaChangeLeaseDuration.Get(&sc.settings.SV)) *
schemaChangeLeaseRenewFraction.Get(&sc.settings.SV))
if timeutil.Unix(0, existingLease.ExpirationTime).After(timeutil.Now().Add(minDuration)) {
return nil
}
// Update lease.
var lease sqlbase.TableDescriptor_SchemaChangeLease
if err := sc.db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
tableDesc, err := sc.findTableWithLease(ctx, txn, *existingLease)
if err != nil {
return err
}
lease = sc.createSchemaChangeLease()
tableDesc.Lease = &lease
if err := txn.SetSystemConfigTrigger(); err != nil {
return err
}
return txn.Put(ctx, sqlbase.MakeDescMetadataKey(tableDesc.ID), sqlbase.WrapDescriptor(tableDesc))
}); err != nil {
return err
}
*existingLease = lease
return nil
}
func (sc *SchemaChanger) canClearRangeForDrop(index *sqlbase.IndexDescriptor) bool {
return sc.execCfg.Settings.Version.IsActive(cluster.VersionClearRange) && !index.IsInterleaved()
}
// DropTableDesc removes a descriptor from the KV database.
func (sc *SchemaChanger) DropTableDesc(
ctx context.Context, tableDesc *sqlbase.TableDescriptor, traceKV bool,
) error {
descKey := sqlbase.MakeDescMetadataKey(tableDesc.ID)
zoneKeyPrefix := config.MakeZoneKeyPrefix(uint32(tableDesc.ID))
// Finished deleting all the table data, now delete the table meta data.
return sc.db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
// Delete table descriptor
b := &client.Batch{}
if traceKV {
log.VEventf(ctx, 2, "Del %s", descKey)
log.VEventf(ctx, 2, "DelRange %s", zoneKeyPrefix)
}
// Delete the descriptor.
b.Del(descKey)
// Delete the zone config entry for this table.
b.DelRange(zoneKeyPrefix, zoneKeyPrefix.PrefixEnd(), false /* returnKeys */)
if err := txn.SetSystemConfigTrigger(); err != nil {
return err
}
if tableDesc.GetDropJobID() != 0 {
if err := sc.updateDropTableJob(
ctx,
txn,
tableDesc.GetDropJobID(),
tableDesc.ID,
jobspb.Status_DONE,
func(ctx context.Context, txn *client.Txn, job *jobs.Job) error {
// Delete the zone config entry for the dropped database associated
// with the job, if it exists.
details := job.Details().(jobspb.SchemaChangeDetails)
if details.DroppedDatabaseID == sqlbase.InvalidID {
return nil
}
dbZoneKeyPrefix := config.MakeZoneKeyPrefix(uint32(details.DroppedDatabaseID))
if traceKV {
log.VEventf(ctx, 2, "DelRange %s", zoneKeyPrefix)
}
b.DelRange(dbZoneKeyPrefix, dbZoneKeyPrefix.PrefixEnd(), false /* returnKeys */)
return nil
}); err != nil {
return pgerror.NewAssertionErrorWithWrappedErrf(err,
"failed to update job %d", log.Safe(tableDesc.GetDropJobID()))
}
}
return txn.Run(ctx, b)
})
}
// truncateTable deletes all of the data in the specified table.
func (sc *SchemaChanger) truncateTable(
ctx context.Context,
lease *sqlbase.TableDescriptor_SchemaChangeLease,
table *sqlbase.TableDescriptor,
evalCtx *extendedEvalContext,
) error {
// If DropTime isn't set, assume this drop request is from a version
// 1.1 server and invoke legacy code that uses DeleteRange and range GC.
if table.DropTime == 0 {
return truncateTableInChunks(ctx, table, sc.db, false /* traceKV */)
}
tableKey := roachpb.RKey(keys.MakeTablePrefix(uint32(table.ID)))
tableSpan := roachpb.RSpan{Key: tableKey, EndKey: tableKey.PrefixEnd()}
// ClearRange requests lays down RocksDB range deletion tombstones that have
// serious performance implications (#24029). The logic below attempts to
// bound the number of tombstones in one store by sending the ClearRange
// requests to each range in the table in small, sequential batches rather
// than letting DistSender send them all in parallel, to hopefully give the
// compaction queue time to compact the range tombstones away in between
// requests.
//
// As written, this approach has several deficiencies. It does not actually
// wait for the compaction queue to compact the tombstones away before
// sending the next request. It is likely insufficient if multiple DROP
// TABLEs are in flight at once. It does not save its progress in case the
// coordinator goes down. These deficiences could be addressed, but this code
// was originally a stopgap to avoid the range tombstone performance hit. The
// RocksDB range tombstone implementation has since been improved and the
// performance implications of many range tombstones has been reduced
// dramatically making this simplistic throttling sufficient.
// These numbers were chosen empirically for the clearrange roachtest and
// could certainly use more tuning.
const batchSize = 100
const waitTime = 500 * time.Millisecond
var n int
lastKey := tableSpan.Key
ri := kv.NewRangeIterator(sc.execCfg.DistSender)
for ri.Seek(ctx, tableSpan.Key, kv.Ascending); ; ri.Next(ctx) {
if !ri.Valid() {
return ri.Error().GoError()
}
// This call is a no-op unless the lease is nearly expired.
if err := sc.ExtendLease(ctx, lease); err != nil {
return err
}
if n++; n >= batchSize || !ri.NeedAnother(tableSpan) {
endKey := ri.Desc().EndKey
if tableSpan.EndKey.Less(endKey) {
endKey = tableSpan.EndKey
}
var b client.Batch
b.AddRawRequest(&roachpb.ClearRangeRequest{
RequestHeader: roachpb.RequestHeader{
Key: lastKey.AsRawKey(),
EndKey: endKey.AsRawKey(),
},
})
log.VEventf(ctx, 2, "ClearRange %s - %s", lastKey, endKey)
if err := sc.db.Run(ctx, &b); err != nil {
return err
}
n = 0
lastKey = endKey
time.Sleep(waitTime)
}
if !ri.NeedAnother(tableSpan) {
break
}
}
return nil
}
// maybe Drop a table. Return nil if successfully dropped.
func (sc *SchemaChanger) maybeDropTable(
ctx context.Context, inSession bool, table *sqlbase.TableDescriptor, evalCtx *extendedEvalContext,
) error {
if !table.Dropped() || inSession {
return nil
}
// This can happen if a change other than the drop originally
// scheduled the changer for this table. If that's the case,
// we still need to wait for the deadline to expire.
if table.DropTime != 0 {
var timeRemaining time.Duration
if err := sc.db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
timeRemaining = 0
_, zoneCfg, _, err := GetZoneConfigInTxn(ctx, txn, uint32(table.ID),
&sqlbase.IndexDescriptor{}, "", false /* getInheritedDefault */)
if err != nil {
return err
}
deadline := table.DropTime + int64(zoneCfg.GC.TTLSeconds)*time.Second.Nanoseconds()
timeRemaining = timeutil.Since(timeutil.Unix(0, deadline))
return nil
}); err != nil {
return err
}
if timeRemaining < 0 {
return errNotHitGCTTLDeadline
}
}
// Acquire lease.
lease, err := sc.AcquireLease(ctx)
if err != nil {
return err
}
needRelease := true
// Always try to release lease.
defer func() {
// If the schema changer deleted the descriptor, there's no longer a lease to be
// released.
if !needRelease {
return
}
if err := sc.ReleaseLease(ctx, lease); err != nil {
log.Warning(ctx, err)
}
}()
// Do all the hard work of deleting the table data and the table ID.
if err := sc.truncateTable(ctx, &lease, table, evalCtx); err != nil {
return err
}
if err := sc.DropTableDesc(ctx, table, false /* traceKV */); err != nil {
return err
}
// The descriptor was deleted.
needRelease = false
return nil
}
// maybe make a table PUBLIC if it's in the ADD state.
func (sc *SchemaChanger) maybeMakeAddTablePublic(
ctx context.Context, table *sqlbase.TableDescriptor,
) error {
if table.Adding() {
fks, err := table.AllActiveAndInactiveForeignKeys()
if err != nil {
return err
}
for _, fk := range fks {
if err := sc.waitToUpdateLeases(ctx, fk.Table); err != nil {
return err
}
}
if _, err := sc.leaseMgr.Publish(
ctx,
table.ID,
func(tbl *sqlbase.MutableTableDescriptor) error {
if !tbl.Adding() {
return errDidntUpdateDescriptor
}
tbl.State = sqlbase.TableDescriptor_PUBLIC
return nil
},
func(txn *client.Txn) error { return nil },
); err != nil {
return err
}
}
return nil
}
func (sc *SchemaChanger) maybeGCMutations(
ctx context.Context, inSession bool, table *sqlbase.TableDescriptor,
) error {
if inSession || len(table.GCMutations) == 0 || len(sc.dropIndexTimes) == 0 {
return nil
}
// Don't perform GC work if there are non-GC mutations waiting.
if len(table.Mutations) > 0 {
return nil
}
// Find dropped index with earliest GC deadline.
dropped := sc.dropIndexTimes[0]
for i := 1; i < len(sc.dropIndexTimes); i++ {
if other := sc.dropIndexTimes[i]; other.deadline < dropped.deadline {
dropped = other
}
}
var mutation sqlbase.TableDescriptor_GCDescriptorMutation
found := false
for _, gcm := range table.GCMutations {
if gcm.IndexID == sc.dropIndexTimes[0].indexID {
found = true
mutation = gcm
break
}
}
if !found {
return pgerror.AssertionFailedf("no GC mutation for index %d", log.Safe(sc.dropIndexTimes[0].indexID))
}
// Check if the deadline for GC'd dropped index expired because
// a change other than the drop could have scheduled the changer
// for this table.
timeRemaining := timeutil.Since(timeutil.Unix(0, dropped.deadline))
if timeRemaining < 0 {
// Return nil to allow other any mutations to make progress.
return nil
}
// Acquire lease.
lease, err := sc.AcquireLease(ctx)
if err != nil {
return err
}
// Always try to release lease.
defer func() {
if err := sc.ReleaseLease(ctx, lease); err != nil {
log.Warning(ctx, err)
}
}()
if err := sc.truncateIndexes(ctx, &lease, table.Version, []sqlbase.IndexDescriptor{{ID: mutation.IndexID}}); err != nil {
return err
}
_, err = sc.leaseMgr.Publish(
ctx,
table.ID,
func(tbl *sqlbase.MutableTableDescriptor) error {
found := false
for i := 0; i < len(tbl.GCMutations); i++ {
if other := tbl.GCMutations[i]; other.IndexID == mutation.IndexID {
tbl.GCMutations = append(tbl.GCMutations[:i], tbl.GCMutations[i+1:]...)
found = true
break
}
}
if !found {
return errDidntUpdateDescriptor
}
return nil
},
func(txn *client.Txn) error {
job, err := sc.jobRegistry.LoadJobWithTxn(ctx, mutation.JobID, txn)
if err != nil {
return err
}
return job.WithTxn(txn).Succeeded(ctx, jobs.NoopFn)
},
)
return err
}
func (sc *SchemaChanger) updateDropTableJob(
ctx context.Context,
txn *client.Txn,
jobID int64,
tableID sqlbase.ID,
status jobspb.Status,
onSuccess func(context.Context, *client.Txn, *jobs.Job) error,
) error {
job, err := sc.jobRegistry.LoadJobWithTxn(ctx, jobID, txn)
if err != nil {
return err
}
schemaDetails, ok := job.Details().(jobspb.SchemaChangeDetails)
if !ok {
return pgerror.AssertionFailedf("unexpected details for job %d: %T", log.Safe(*job.ID()), job.Details())
}
lowestStatus := jobspb.Status_DONE
for i := range schemaDetails.DroppedTables {
if tableID == schemaDetails.DroppedTables[i].ID {
schemaDetails.DroppedTables[i].Status = status
}
if lowestStatus > schemaDetails.DroppedTables[i].Status {
lowestStatus = schemaDetails.DroppedTables[i].Status
}
}
var runningStatus jobs.RunningStatus
switch lowestStatus {
case jobspb.Status_DRAINING_NAMES:
runningStatus = RunningStatusDrainingNames
case jobspb.Status_WAIT_FOR_GC_INTERVAL:
runningStatus = RunningStatusWaitingGC
case jobspb.Status_ROCKSDB_COMPACTION:
runningStatus = RunningStatusCompaction
case jobspb.Status_DONE:
return job.WithTxn(txn).Succeeded(ctx, func(ctx context.Context, txn *client.Txn) error {
return onSuccess(ctx, txn, job)
})
default:
return pgerror.AssertionFailedf("unexpected dropped table status %d", log.Safe(lowestStatus))
}
if err := job.WithTxn(txn).SetDetails(ctx, schemaDetails); err != nil {
return err
}
return job.WithTxn(txn).RunningStatus(ctx, func(ctx context.Context, _ jobspb.Details) (jobs.RunningStatus, error) {
return runningStatus, nil
})
}
// Drain old names from the cluster.
func (sc *SchemaChanger) drainNames(ctx context.Context) error {
// Publish a new version with all the names drained after everyone
// has seen the version with the new name. All the draining names
// can be reused henceforth.
var namesToReclaim []sqlbase.TableDescriptor_NameInfo
var dropJobID int64
_, err := sc.leaseMgr.Publish(
ctx,
sc.tableID,
func(desc *sqlbase.MutableTableDescriptor) error {
if sc.testingKnobs.OldNamesDrainedNotification != nil {
sc.testingKnobs.OldNamesDrainedNotification()
}
// Free up the old name(s) for reuse.
namesToReclaim = desc.DrainingNames
desc.DrainingNames = nil
dropJobID = desc.GetDropJobID()
return nil
},
// Reclaim all the old names.
func(txn *client.Txn) error {
b := txn.NewBatch()
for _, drain := range namesToReclaim {
tbKey := tableKey{drain.ParentID, drain.Name}.Key()
b.Del(tbKey)
}
if dropJobID != 0 {
if err := sc.updateDropTableJob(
ctx, txn, dropJobID, sc.tableID, jobspb.Status_WAIT_FOR_GC_INTERVAL,
func(context.Context, *client.Txn, *jobs.Job) error {
return nil
}); err != nil {
return err
}
}
return txn.Run(ctx, b)
},
)
return err
}
// Execute the entire schema change in steps.
// inSession is set to false when this is called from the asynchronous
// schema change execution path.
//
// If the txn that queued the schema changer did not commit, this will be a
// no-op, as we'll fail to find the job for our mutation in the jobs registry.
func (sc *SchemaChanger) exec(
ctx context.Context, inSession bool, evalCtx *extendedEvalContext,
) error {
ctx = logtags.AddTag(ctx, "scExec", nil)
if log.V(2) {
log.Infof(ctx, "exec pending schema change; table: %d, mutation: %d",
sc.tableID, sc.mutationID)
}
tableDesc, notFirst, err := sc.notFirstInLine(ctx)
if err != nil {
return err
}
if notFirst {
return errSchemaChangeNotFirstInLine
}
if tableDesc.HasDrainingNames() {
if err := sc.drainNames(ctx); err != nil {
return err
}
}
// Delete dropped table data if possible.
if err := sc.maybeDropTable(ctx, inSession, tableDesc, evalCtx); err != nil {
return err
}
if err := sc.maybeMakeAddTablePublic(ctx, tableDesc); err != nil {
return err
}
if err := sc.maybeGCMutations(ctx, inSession, tableDesc); err != nil {
return err
}
// Wait for the schema change to propagate to all nodes after this function
// returns, so that the new schema is live everywhere. This is not needed for
// correctness but is done to make the UI experience/tests predictable.
waitToUpdateLeases := func(refreshStats bool) {
if err := sc.waitToUpdateLeases(ctx, sc.tableID); err != nil {
log.Warning(ctx, err)
}
// We wait to trigger a stats refresh until we know the leases have been
// updated.
if refreshStats {
sc.refreshStats()
}
}
if sc.mutationID == sqlbase.InvalidMutationID {
// Nothing more to do.
waitToUpdateLeases(false /* refreshStats */)
return nil
}
// Acquire lease.
lease, err := sc.AcquireLease(ctx)
if err != nil {
return err
}
// Always try to release lease.
defer func() {
if err := sc.ReleaseLease(ctx, lease); err != nil {
log.Warning(ctx, err)
}
}()
// Find our job.
foundJobID := false
for _, g := range tableDesc.MutationJobs {
if g.MutationID == sc.mutationID {
job, err := sc.jobRegistry.LoadJob(ctx, g.JobID)
if err != nil {
return err
}
sc.job = job
foundJobID = true
break
}
}
if !foundJobID {
// No job means we've already run and completed this schema change
// successfully, so we can just exit.
return nil
}
if err := sc.job.Started(ctx); err != nil {
if log.V(2) {
log.Infof(ctx, "Failed to mark job %d as started: %v", *sc.job.ID(), err)
}
}
if err := sc.initJobRunningStatus(ctx); err != nil {
if log.V(2) {
log.Infof(ctx, "Failed to update job %d running status: %v", *sc.job.ID(), err)
}
}
// Run through mutation state machine and backfill.
err = sc.runStateMachineAndBackfill(ctx, &lease, evalCtx)
defer waitToUpdateLeases(err == nil /* refreshStats */)
// Purge the mutations if the application of the mutations failed due to
// a permanent error. All other errors are transient errors that are
// resolved by retrying the backfill.
if isPermanentSchemaChangeError(err) {
if err := sc.rollbackSchemaChange(ctx, err, &lease, evalCtx); err != nil {
return err
}
}
return err
}
// initialize the job running status.
func (sc *SchemaChanger) initJobRunningStatus(ctx context.Context) error {
return sc.db.Txn(ctx, func(ctx context.Context, txn *client.Txn) error {
desc, err := sqlbase.GetTableDescFromID(ctx, txn, sc.tableID)
if err != nil {
return err
}
var runStatus jobs.RunningStatus
for _, mutation := range desc.Mutations {
if mutation.MutationID != sc.mutationID {
// Mutations are applied in a FIFO order. Only apply the first set of
// mutations if they have the mutation ID we're looking for.
break
}
switch mutation.Direction {
case sqlbase.DescriptorMutation_ADD:
switch mutation.State {
case sqlbase.DescriptorMutation_DELETE_ONLY:
runStatus = RunningStatusDeleteOnly
}
case sqlbase.DescriptorMutation_DROP:
switch mutation.State {
case sqlbase.DescriptorMutation_DELETE_AND_WRITE_ONLY:
runStatus = RunningStatusDeleteAndWriteOnly
}
}
}
if runStatus != "" && !desc.Dropped() {
if err := sc.job.WithTxn(txn).RunningStatus(
ctx, func(ctx context.Context, details jobspb.Details) (jobs.RunningStatus, error) {
return runStatus, nil
}); err != nil {
return pgerror.NewAssertionErrorWithWrappedErrf(err,
"failed to update running status of job %d", log.Safe(*sc.job.ID()))
}
}
return nil
})
}
func (sc *SchemaChanger) rollbackSchemaChange(
ctx context.Context,
err error,
lease *sqlbase.TableDescriptor_SchemaChangeLease,
evalCtx *extendedEvalContext,
) error {
log.Warningf(ctx, "reversing schema change %d due to irrecoverable error: %s", *sc.job.ID(), err)
if errReverse := sc.reverseMutations(ctx, err); errReverse != nil {
// Although the backfill did hit an integrity constraint violation
// and made a decision to reverse the mutations,
// reverseMutations() failed. If exec() is called again the entire
// schema change will be retried.
return errReverse
}
// After this point the schema change has been reversed and any retry
// of the schema change will act upon the reversed schema change.
if errPurge := sc.runStateMachineAndBackfill(ctx, lease, evalCtx); errPurge != nil {
// Don't return this error because we do want the caller to know
// that an integrity constraint was violated with the original
// schema change. The reversed schema change will be
// retried via the async schema change manager.
log.Warningf(ctx, "error purging mutation: %s, after error: %s", errPurge, err)
}
return nil
}
// RunStateMachineBeforeBackfill moves the state machine forward
// and wait to ensure that all nodes are seeing the latest version
// of the table.
func (sc *SchemaChanger) RunStateMachineBeforeBackfill(ctx context.Context) error {
var runStatus jobs.RunningStatus
if _, err := sc.leaseMgr.Publish(ctx, sc.tableID, func(desc *sqlbase.MutableTableDescriptor) error {
runStatus = ""
// Apply mutations belonging to the same version.
for i, mutation := range desc.Mutations {
if mutation.MutationID != sc.mutationID {
// Mutations are applied in a FIFO order. Only apply the first set of
// mutations if they have the mutation ID we're looking for.
break
}
switch mutation.Direction {
case sqlbase.DescriptorMutation_ADD:
switch mutation.State {
case sqlbase.DescriptorMutation_DELETE_ONLY:
// TODO(vivek): while moving up the state is appropriate,