-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
lease.go
1944 lines (1796 loc) · 66.7 KB
/
lease.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.
//
// 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 sql
import (
"bytes"
"context"
"fmt"
"math/rand"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/gossip"
"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/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/quotapool"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/syncutil/singleflight"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
)
var errRenewLease = errors.New("renew lease on id")
var errReadOlderTableVersion = errors.New("read older table version from store")
// A lease stored in system.lease.
type storedTableLease struct {
id sqlbase.ID
version int
expiration tree.DTimestamp
}
// tableVersionState holds the state for a table version. This includes
// the lease information for a table version.
// TODO(vivek): A node only needs to manage lease information on what it
// thinks is the latest version for a table descriptor.
type tableVersionState struct {
// This descriptor is immutable and can be shared by many goroutines.
// Care must be taken to not modify it.
sqlbase.ImmutableTableDescriptor
// The expiration time for the table version. A transaction with
// timestamp T can use this table descriptor version iff
// TableDescriptor.ModificationTime <= T < expiration
//
// The expiration time is either the expiration time of the lease
// when a lease is associated with the table version, or the
// ModificationTime of the next version when the table version
// isn't associated with a lease.
expiration hlc.Timestamp
mu struct {
syncutil.Mutex
refcount int
// Set if the node has a lease on this descriptor version.
// Leases can only be held for the two latest versions of
// a table descriptor. The latest version known to a node
// (can be different than the current latest version in the store)
// is always associated with a lease. The previous version known to
// a node might not necessarily be associated with a lease.
lease *storedTableLease
}
}
func (s *tableVersionState) String() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.stringLocked()
}
// stringLocked reads mu.refcount and thus needs to have mu held.
func (s *tableVersionState) stringLocked() string {
return fmt.Sprintf("%d(%q) ver=%d:%s, refcount=%d", s.ID, s.Name, s.Version, s.expiration, s.mu.refcount)
}
// hasExpired checks if the table is too old to be used (by a txn operating)
// at the given timestamp
func (s *tableVersionState) hasExpired(timestamp hlc.Timestamp) bool {
return s.expiration.LessEq(timestamp)
}
// hasValidExpiration checks that this table have a larger expiration than
// the existing one it is replacing. This can be used to check the
// monotonicity of the expiration times on a table at a particular version.
// The version is not explicitly checked here.
func (s *tableVersionState) hasValidExpiration(existing *tableVersionState) bool {
return existing.expiration.Less(s.expiration)
}
func (s *tableVersionState) incRefcount() {
s.mu.Lock()
s.incRefcountLocked()
s.mu.Unlock()
}
func (s *tableVersionState) incRefcountLocked() {
s.mu.refcount++
if log.V(2) {
log.VEventf(context.TODO(), 2, "tableVersionState.incRef: %s", s.stringLocked())
}
}
// The lease expiration stored in the database is of a different type.
// We've decided that it's too much work to change the type to
// hlc.Timestamp, so we're using this method to give us the stored
// type: tree.DTimestamp.
func storedLeaseExpiration(expiration hlc.Timestamp) tree.DTimestamp {
return tree.DTimestamp{Time: timeutil.Unix(0, expiration.WallTime).Round(time.Microsecond)}
}
// LeaseStore implements the operations for acquiring and releasing leases and
// publishing a new version of a descriptor. Exported only for testing.
type LeaseStore struct {
nodeIDContainer *base.NodeIDContainer
db *kv.DB
clock *hlc.Clock
internalExecutor sqlutil.InternalExecutor
settings *cluster.Settings
// group is used for all calls made to acquireNodeLease to prevent
// concurrent lease acquisitions from the store.
group *singleflight.Group
// leaseDuration is the mean duration a lease will be acquired for. The
// actual duration is jittered using leaseJitterFraction. Jittering is done to
// prevent multiple leases from being renewed simultaneously if they were all
// acquired simultaneously.
leaseDuration time.Duration
// leaseJitterFraction is the factor that we use to randomly jitter the lease
// duration when acquiring a new lease and the lease renewal timeout. The
// range of the actual lease duration will be
// [(1-leaseJitterFraction) * leaseDuration, (1+leaseJitterFraction) * leaseDuration]
leaseJitterFraction float64
// leaseRenewalTimeout is the time before a lease expires when
// acquisition to renew the lease begins.
leaseRenewalTimeout time.Duration
testingKnobs LeaseStoreTestingKnobs
}
// jitteredLeaseDuration returns a randomly jittered duration from the interval
// [(1-leaseJitterFraction) * leaseDuration, (1+leaseJitterFraction) * leaseDuration].
func (s LeaseStore) jitteredLeaseDuration() time.Duration {
return time.Duration(float64(s.leaseDuration) * (1 - s.leaseJitterFraction +
2*s.leaseJitterFraction*rand.Float64()))
}
// acquire a lease on the most recent version of a table descriptor.
// If the lease cannot be obtained because the descriptor is in the process of
// being dropped or offline, the error will be of type inactiveTableError.
// The expiration time set for the lease > minExpiration.
func (s LeaseStore) acquire(
ctx context.Context, minExpiration hlc.Timestamp, tableID sqlbase.ID,
) (*tableVersionState, error) {
var table *tableVersionState
err := s.db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
expiration := txn.ReadTimestamp()
expiration.WallTime += int64(s.jitteredLeaseDuration())
if expiration.LessEq(minExpiration) {
// In the rare circumstances where expiration <= minExpiration
// use an expiration based on the minExpiration to guarantee
// a monotonically increasing expiration.
expiration = minExpiration.Add(int64(time.Millisecond), 0)
}
tableDesc, err := sqlbase.GetTableDescFromID(ctx, txn, tableID)
if err != nil {
return err
}
if err := FilterTableState(tableDesc); err != nil {
return err
}
if err := tableDesc.MaybeFillInDescriptor(ctx, txn); err != nil {
return err
}
// Once the descriptor is set it is immutable and care must be taken
// to not modify it.
storedLease := &storedTableLease{
id: tableDesc.ID,
version: int(tableDesc.Version),
expiration: storedLeaseExpiration(expiration),
}
table = &tableVersionState{
ImmutableTableDescriptor: *sqlbase.NewImmutableTableDescriptor(*tableDesc),
expiration: expiration,
}
table.mu.lease = storedLease
// ValidateTable instead of Validate, even though we have a txn available,
// so we don't block reads waiting for this table version.
if err := table.ValidateTable(); err != nil {
return err
}
nodeID := s.nodeIDContainer.Get()
if nodeID == 0 {
panic("zero nodeID")
}
// We use string interpolation here, instead of passing the arguments to
// InternalExecutor.Exec() because we don't want to pay for preparing the
// statement (which would happen if we'd pass arguments). Besides the
// general cost of preparing, preparing this statement always requires a
// read from the database for the special descriptor of a system table
// (#23937).
insertLease := fmt.Sprintf(
`INSERT INTO system.public.lease ("descID", version, "nodeID", expiration) VALUES (%d, %d, %d, %s)`,
storedLease.id, storedLease.version, nodeID, &storedLease.expiration,
)
count, err := s.internalExecutor.Exec(ctx, "lease-insert", txn, insertLease)
if err != nil {
return err
}
if count != 1 {
return errors.Errorf("%s: expected 1 result, found %d", insertLease, count)
}
return nil
})
if err == nil && s.testingKnobs.LeaseAcquiredEvent != nil {
s.testingKnobs.LeaseAcquiredEvent(table.TableDescriptor, nil)
}
return table, err
}
// Release a previously acquired table descriptor. Never let this method
// read a table descriptor because it can be called while modifying a
// descriptor through a schema change before the schema change has committed
// that can result in a deadlock.
func (s LeaseStore) release(ctx context.Context, stopper *stop.Stopper, lease *storedTableLease) {
retryOptions := base.DefaultRetryOptions()
retryOptions.Closer = stopper.ShouldQuiesce()
firstAttempt := true
// This transaction is idempotent; the retry was put in place because of
// NodeUnavailableErrors.
for r := retry.Start(retryOptions); r.Next(); {
log.VEventf(ctx, 2, "LeaseStore releasing lease %+v", lease)
nodeID := s.nodeIDContainer.Get()
if nodeID == 0 {
panic("zero nodeID")
}
const deleteLease = `DELETE FROM system.public.lease ` +
`WHERE ("descID", version, "nodeID", expiration) = ($1, $2, $3, $4)`
count, err := s.internalExecutor.Exec(
ctx,
"lease-release",
nil, /* txn */
deleteLease,
lease.id, lease.version, nodeID, &lease.expiration,
)
if err != nil {
log.Warningf(ctx, "error releasing lease %q: %s", lease, err)
firstAttempt = false
continue
}
// We allow count == 0 after the first attempt.
if count > 1 || (count == 0 && firstAttempt) {
log.Warningf(ctx, "unexpected results while deleting lease %+v: "+
"expected 1 result, found %d", lease, count)
}
if s.testingKnobs.LeaseReleasedEvent != nil {
s.testingKnobs.LeaseReleasedEvent(
lease.id, sqlbase.DescriptorVersion(lease.version), err)
}
break
}
}
// WaitForOneVersion returns once there are no unexpired leases on the
// previous version of the table descriptor. It returns the current version.
// After returning there can only be versions of the descriptor >= to the
// returned version. Lease acquisition (see acquire()) maintains the
// invariant that no new leases for desc.Version-1 will be granted once
// desc.Version exists.
func (s LeaseStore) WaitForOneVersion(
ctx context.Context, tableID sqlbase.ID, retryOpts retry.Options,
) (sqlbase.DescriptorVersion, error) {
var tableDesc *sqlbase.TableDescriptor
var err error
for lastCount, r := 0, retry.Start(retryOpts); r.Next(); {
// Get the current version of the table descriptor non-transactionally.
//
// TODO(pmattis): Do an inconsistent read here?
tableDesc, err = sqlbase.GetTableDescFromID(ctx, s.db, tableID)
if err != nil {
return 0, err
}
// Check to see if there are any leases that still exist on the previous
// version of the descriptor.
now := s.clock.Now()
tables := []IDVersion{NewIDVersionPrev(tableDesc)}
count, err := CountLeases(ctx, s.internalExecutor, tables, now)
if err != nil {
return 0, err
}
if count == 0 {
break
}
if count != lastCount {
lastCount = count
log.Infof(ctx, "waiting for %d leases to expire: desc=%v", count, tables)
}
}
return tableDesc.Version, nil
}
var errDidntUpdateDescriptor = errors.New("didn't update the table descriptor")
// PublishMultiple updates multiple table descriptors, maintaining the invariant
// that there are at most two versions of each descriptor out in the wild at any
// time by first waiting for all nodes to be on the current (pre-update) version
// of the table desc.
//
// The update closure for all tables is called after the wait. The argument to
// the closure is a map of the table descriptors with the IDs given in tableIDs,
// and the closure mutates those descriptors.
//
// The closure may be called multiple times if retries occur; make sure it does
// not have side effects.
//
// Returns the updated versions of the descriptors.
func (s LeaseStore) PublishMultiple(
ctx context.Context,
tableIDs []sqlbase.ID,
update func(map[sqlbase.ID]*sqlbase.MutableTableDescriptor) error,
logEvent func(*kv.Txn) error,
) (map[sqlbase.ID]*sqlbase.ImmutableTableDescriptor, error) {
errLeaseVersionChanged := errors.New("lease version changed")
// Retry while getting errLeaseVersionChanged.
for r := retry.Start(base.DefaultRetryOptions()); r.Next(); {
// Wait until there are no unexpired leases on the previous versions
// of the tables.
expectedVersions := make(map[sqlbase.ID]sqlbase.DescriptorVersion)
for _, id := range tableIDs {
expected, err := s.WaitForOneVersion(ctx, id, base.DefaultRetryOptions())
if err != nil {
return nil, err
}
expectedVersions[id] = expected
}
tableDescs := make(map[sqlbase.ID]*sqlbase.MutableTableDescriptor)
// There should be only one version of the descriptor, but it's
// a race now to update to the next version.
err := s.db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
versions := make(map[sqlbase.ID]sqlbase.DescriptorVersion)
descsToUpdate := make(map[sqlbase.ID]*sqlbase.MutableTableDescriptor)
for _, id := range tableIDs {
// Re-read the current versions of the table descriptor, this time
// transactionally.
var err error
descsToUpdate[id], err = sqlbase.GetMutableTableDescFromID(ctx, txn, id)
if err != nil {
return err
}
if expectedVersions[id] != descsToUpdate[id].Version {
// The version changed out from under us. Someone else must be
// performing a schema change operation.
if log.V(3) {
log.Infof(ctx, "publish (version changed): %d != %d", expectedVersions[id], descsToUpdate[id].Version)
}
return errLeaseVersionChanged
}
versions[id] = descsToUpdate[id].Version
}
// Run the update closure.
if err := update(descsToUpdate); err != nil {
return err
}
for _, id := range tableIDs {
if versions[id] != descsToUpdate[id].Version {
return errors.Errorf("updated version to: %d, expected: %d",
descsToUpdate[id].Version, versions[id])
}
if err := descsToUpdate[id].MaybeIncrementVersion(ctx, txn, s.settings); err != nil {
return err
}
if err := descsToUpdate[id].ValidateTable(); err != nil {
return err
}
tableDescs[id] = descsToUpdate[id]
}
// Write the updated descriptors.
if err := txn.SetSystemConfigTrigger(); err != nil {
return err
}
b := txn.NewBatch()
for tableID, tableDesc := range tableDescs {
if err := writeDescToBatch(ctx, false /* kvTrace */, s.settings, b, tableID, tableDesc.TableDesc()); err != nil {
return err
}
}
if logEvent != nil {
// If an event log is required for this update, ensure that the
// descriptor change occurs first in the transaction. This is
// necessary to ensure that the System configuration change is
// gossiped. See the documentation for
// transaction.SetSystemConfigTrigger() for more information.
if err := txn.Run(ctx, b); err != nil {
return err
}
if err := logEvent(txn); err != nil {
return err
}
return txn.Commit(ctx)
}
// More efficient batching can be used if no event log message
// is required.
return txn.CommitInBatch(ctx, b)
})
switch err {
case nil, errDidntUpdateDescriptor:
immutTableDescs := make(map[sqlbase.ID]*ImmutableTableDescriptor)
for id, tableDesc := range tableDescs {
immutTableDescs[id] = sqlbase.NewImmutableTableDescriptor(tableDesc.TableDescriptor)
}
return immutTableDescs, nil
case errLeaseVersionChanged:
// will loop around to retry
default:
return nil, err
}
}
panic("not reached")
}
// Publish updates a table descriptor. It also maintains the invariant that
// there are at most two versions of the descriptor out in the wild at any time
// by first waiting for all nodes to be on the current (pre-update) version of
// the table desc.
//
// The update closure is called after the wait, and it provides the new version
// of the descriptor to be written. In a multi-step schema operation, this
// update should perform a single step.
//
// The closure may be called multiple times if retries occur; make sure it does
// not have side effects.
//
// Returns the updated version of the descriptor.
func (s LeaseStore) Publish(
ctx context.Context,
tableID sqlbase.ID,
update func(*sqlbase.MutableTableDescriptor) error,
logEvent func(*kv.Txn) error,
) (*sqlbase.ImmutableTableDescriptor, error) {
tableIDs := []sqlbase.ID{tableID}
updates := func(descs map[sqlbase.ID]*sqlbase.MutableTableDescriptor) error {
desc, ok := descs[tableID]
if !ok {
return errors.AssertionFailedf("required table with ID %d not provided to update closure", tableID)
}
return update(desc)
}
results, err := s.PublishMultiple(ctx, tableIDs, updates, logEvent)
if err != nil {
return nil, err
}
return results[tableID], nil
}
// IDVersion represents a descriptor ID, version pair that are
// meant to map to a single immutable descriptor.
type IDVersion struct {
// name only provided for pretty printing.
name string
id sqlbase.ID
version sqlbase.DescriptorVersion
}
// NewIDVersionPrev returns an initialized IDVersion with the
// previous version of the descriptor.
func NewIDVersionPrev(desc *sqlbase.TableDescriptor) IDVersion {
return IDVersion{name: desc.Name, id: desc.ID, version: desc.Version - 1}
}
// CountLeases returns the number of unexpired leases for a number of tables
// each at a particular version at a particular time.
func CountLeases(
ctx context.Context, executor sqlutil.InternalExecutor, tables []IDVersion, at hlc.Timestamp,
) (int, error) {
var whereClauses []string
for _, t := range tables {
whereClauses = append(whereClauses,
fmt.Sprintf(`("descID" = %d AND version = %d AND expiration > $1)`,
t.id, t.version),
)
}
stmt := fmt.Sprintf(`SELECT count(1) FROM system.public.lease AS OF SYSTEM TIME %s WHERE `,
at.AsOfSystemTime()) +
strings.Join(whereClauses, " OR ")
values, err := executor.QueryRowEx(
ctx, "count-leases", nil, /* txn */
sqlbase.InternalExecutorSessionDataOverride{User: security.RootUser},
stmt, at.GoTime(),
)
if err != nil {
return 0, err
}
count := int(tree.MustBeDInt(values[0]))
return count, nil
}
// Get the table descriptor valid for the expiration time from the store.
// We use a timestamp that is just less than the expiration time to read
// a version of the table descriptor. A tableVersionState with the
// expiration time set to expiration is returned.
//
// This returns an error when Replica.checkTSAboveGCThresholdRLocked()
// returns an error when the expiration timestamp is less than the storage
// layer GC threshold.
func (s LeaseStore) getForExpiration(
ctx context.Context, expiration hlc.Timestamp, id sqlbase.ID,
) (*tableVersionState, error) {
var table *tableVersionState
err := s.db.Txn(ctx, func(ctx context.Context, txn *kv.Txn) error {
descKey := sqlbase.MakeDescMetadataKey(id)
prevTimestamp := expiration.Prev()
txn.SetFixedTimestamp(ctx, prevTimestamp)
var desc sqlbase.Descriptor
ts, err := txn.GetProtoTs(ctx, descKey, &desc)
if err != nil {
return err
}
tableDesc := desc.Table(ts)
if tableDesc == nil {
return sqlbase.ErrDescriptorNotFound
}
if prevTimestamp.LessEq(tableDesc.ModificationTime) {
return errors.AssertionFailedf("unable to read table= (%d, %s)", id, expiration)
}
if err := tableDesc.MaybeFillInDescriptor(ctx, txn); err != nil {
return err
}
// Create a tableVersionState with the table and without a lease.
table = &tableVersionState{
ImmutableTableDescriptor: *sqlbase.NewImmutableTableDescriptor(*tableDesc),
expiration: expiration,
}
return nil
})
return table, err
}
// leaseToken is an opaque token representing a lease. It's distinct from a
// lease to define restricted capabilities and prevent improper use of a lease
// where we instead have leaseTokens.
type leaseToken *tableVersionState
// tableSet maintains an ordered set of tableVersionState objects sorted
// by version. It supports addition and removal of elements, finding the
// table for a particular version, or finding the most recent table version.
// The order is maintained by insert and remove and there can only be a
// unique entry for a version. Only the last two versions can be leased,
// with the last one being the latest one which is always leased.
//
// Each entry represents a time span [ModificationTime, expiration)
// and can be used by a transaction iif:
// ModificationTime <= transaction.Timestamp < expiration.
type tableSet struct {
data []*tableVersionState
}
func (l *tableSet) String() string {
var buf bytes.Buffer
for i, s := range l.data {
if i > 0 {
buf.WriteString(" ")
}
buf.WriteString(fmt.Sprintf("%d:%d", s.Version, s.expiration.WallTime))
}
return buf.String()
}
func (l *tableSet) insert(s *tableVersionState) {
i, match := l.findIndex(s.Version)
if match {
panic("unable to insert duplicate lease")
}
if i == len(l.data) {
l.data = append(l.data, s)
return
}
l.data = append(l.data, nil)
copy(l.data[i+1:], l.data[i:])
l.data[i] = s
}
func (l *tableSet) remove(s *tableVersionState) {
i, match := l.findIndex(s.Version)
if !match {
panic(fmt.Sprintf("can't find lease to remove: %s", s))
}
l.data = append(l.data[:i], l.data[i+1:]...)
}
func (l *tableSet) find(version sqlbase.DescriptorVersion) *tableVersionState {
if i, match := l.findIndex(version); match {
return l.data[i]
}
return nil
}
func (l *tableSet) findIndex(version sqlbase.DescriptorVersion) (int, bool) {
i := sort.Search(len(l.data), func(i int) bool {
s := l.data[i]
return s.Version >= version
})
if i < len(l.data) {
s := l.data[i]
if s.Version == version {
return i, true
}
}
return i, false
}
func (l *tableSet) findNewest() *tableVersionState {
if len(l.data) == 0 {
return nil
}
return l.data[len(l.data)-1]
}
func (l *tableSet) findVersion(version sqlbase.DescriptorVersion) *tableVersionState {
if len(l.data) == 0 {
return nil
}
// Find the index of the first lease with version > targetVersion.
i := sort.Search(len(l.data), func(i int) bool {
return l.data[i].Version > version
})
if i == 0 {
return nil
}
// i-1 is the index of the newest lease for the previous version (the version
// we're looking for).
s := l.data[i-1]
if s.Version == version {
return s
}
return nil
}
type tableState struct {
id sqlbase.ID
stopper *stop.Stopper
// renewalInProgress is an atomic indicator for when a renewal for a
// lease has begun. This is atomic to prevent multiple routines from
// entering renewal initialization.
renewalInProgress int32
mu struct {
syncutil.Mutex
// table descriptors sorted by increasing version. This set always
// contains a table descriptor version with a lease as the latest
// entry. There may be more than one active lease when the system is
// transitioning from one version of the descriptor to another or
// when the node preemptively acquires a new lease for a version
// when the old lease has not yet expired. In the latter case, a new
// entry is created with the expiration time of the new lease and
// the older entry is removed.
active tableSet
// Indicates that the table has been dropped, or is being dropped.
// If set, leases are released from the store as soon as their
// refcount drops to 0, as opposed to waiting until they expire.
dropped bool
}
}
// ensureVersion ensures that the latest version >= minVersion. It will
// check if the latest known version meets the criterion, or attempt to
// acquire a lease at the latest version with the hope that it meets
// the criterion.
func ensureVersion(
ctx context.Context, tableID sqlbase.ID, minVersion sqlbase.DescriptorVersion, m *LeaseManager,
) error {
if s := m.findNewest(tableID); s != nil && minVersion <= s.Version {
return nil
}
if err := m.AcquireFreshestFromStore(ctx, tableID); err != nil {
return err
}
if s := m.findNewest(tableID); s != nil && s.Version < minVersion {
return errors.Errorf("version %d for table %s does not exist yet", minVersion, s.Name)
}
return nil
}
// findForTimestamp finds a table descriptor valid for the timestamp.
// In the most common case the timestamp passed to this method is close
// to the current time and in all likelihood the latest version of a
// table descriptor if valid is returned.
//
// This returns errRenewLease when there is no table descriptor cached
// or the latest descriptor version's ModificationTime satisfies the
// timestamp while it's expiration time doesn't satisfy the timestamp.
// This is an optimistic strategy betting that in all likelihood a
// higher layer renewing the lease on the descriptor and populating
// tableState will satisfy the timestamp on a subsequent call.
//
// In all other circumstances where a descriptor cannot be found for the
// timestamp errOlderReadTableVersion is returned requesting a higher layer
// to populate the tableState with a valid older version of the descriptor
// before calling.
//
// The refcount for the returned tableVersionState is incremented.
// It returns true if the descriptor returned is the known latest version
// of the descriptor.
func (t *tableState) findForTimestamp(
ctx context.Context, timestamp hlc.Timestamp,
) (*tableVersionState, bool, error) {
t.mu.Lock()
defer t.mu.Unlock()
// Acquire a lease if no table descriptor exists in the cache.
if len(t.mu.active.data) == 0 {
return nil, false, errRenewLease
}
// Walk back the versions to find one that is valid for the timestamp.
for i := len(t.mu.active.data) - 1; i >= 0; i-- {
// Check to see if the ModificationTime is valid.
if table := t.mu.active.data[i]; table.ModificationTime.LessEq(timestamp) {
latest := i+1 == len(t.mu.active.data)
if !table.hasExpired(timestamp) {
// Existing valid table version.
table.incRefcount()
return table, latest, nil
}
if latest {
// Renew the lease if the lease has expired
// The latest descriptor always has a lease.
return nil, false, errRenewLease
}
break
}
}
return nil, false, errReadOlderTableVersion
}
// Read an older table descriptor version for the particular timestamp
// from the store. We unfortunately need to read more than one table
// version just so that we can set the expiration time on the descriptor
// properly.
//
// TODO(vivek): Future work:
// 1. Read multiple versions of a descriptor through one kv call.
// 2. Translate multiple simultaneous calls to this method into a single call
// as is done for acquireNodeLease().
// 3. Figure out a sane policy on when these descriptors should be purged.
// They are currently purged in PurgeOldVersions.
func (m *LeaseManager) readOlderVersionForTimestamp(
ctx context.Context, tableID sqlbase.ID, timestamp hlc.Timestamp,
) ([]*tableVersionState, error) {
expiration, done := func() (hlc.Timestamp, bool) {
t := m.findTableState(tableID, false /* create */)
t.mu.Lock()
defer t.mu.Unlock()
afterIdx := 0
// Walk back the versions to find one that is valid for the timestamp.
for i := len(t.mu.active.data) - 1; i >= 0; i-- {
// Check to see if the ModificationTime is valid.
if table := t.mu.active.data[i]; table.ModificationTime.LessEq(timestamp) {
if timestamp.Less(table.expiration) {
// Existing valid table version.
return table.expiration, true
}
// We need a version after data[i], but before data[i+1].
// We could very well use the timestamp to read the table
// descriptor, but unfortunately we will not be able to assign
// it a proper expiration time. Therefore, we read table
// descriptors versions one by one from afterIdx back into the
// past until we find a valid one.
afterIdx = i + 1
break
}
}
if afterIdx == len(t.mu.active.data) {
return hlc.Timestamp{}, true
}
// Read table descriptor versions one by one into the past until we
// find a valid one. Every version is assigned an expiration time that
// is the ModificationTime of the previous one read.
return t.mu.active.data[afterIdx].ModificationTime, false
}()
if done {
return nil, nil
}
// Read descriptors from the store.
var versions []*tableVersionState
for {
table, err := m.LeaseStore.getForExpiration(ctx, expiration, tableID)
if err != nil {
return nil, err
}
versions = append(versions, table)
if table.ModificationTime.LessEq(timestamp) {
break
}
// Set the expiration time for the next table.
expiration = table.ModificationTime
}
return versions, nil
}
// Insert table versions. The versions provided are not in
// any particular order.
func (m *LeaseManager) insertTableVersions(tableID sqlbase.ID, versions []*tableVersionState) {
t := m.findTableState(tableID, false /* create */)
t.mu.Lock()
defer t.mu.Unlock()
for _, tableVersion := range versions {
// Since we gave up the lock while reading the versions from
// the store we have to ensure that no one else inserted the
// same table version.
table := t.mu.active.findVersion(tableVersion.Version)
if table == nil {
t.mu.active.insert(tableVersion)
}
}
}
// AcquireFreshestFromStore acquires a new lease from the store and
// inserts it into the active set. It guarantees that the lease returned is
// the one acquired after the call is made. Use this if the lease we want to
// get needs to see some descriptor updates that we know happened recently.
func (m *LeaseManager) AcquireFreshestFromStore(ctx context.Context, tableID sqlbase.ID) error {
// Create tableState if needed.
_ = m.findTableState(tableID, true /* create */)
// We need to acquire a lease on a "fresh" descriptor, meaning that joining
// a potential in-progress lease acquisition is generally not good enough.
// If we are to join an in-progress acquisition, it needs to be an acquisition
// initiated after this point.
// So, we handle two cases:
// 1. The first DoChan() call tells us that we didn't join an in-progress
// acquisition. Great, the lease that's being acquired is good.
// 2. The first DoChan() call tells us that we did join an in-progress acq.
// We have to wait this acquisition out; it's not good for us. But any
// future acquisition is good, so the next time around the loop it doesn't
// matter if we initiate a request or join an in-progress one.
// In both cases, we need to check if the lease we want is still valid because
// lease acquisition is done without holding the tableState lock, so anything
// can happen in between lease acquisition and us getting control again.
attemptsMade := 0
for {
// Acquire a fresh table lease.
didAcquire, err := acquireNodeLease(ctx, m, tableID)
if m.testingKnobs.LeaseStoreTestingKnobs.LeaseAcquireResultBlockEvent != nil {
m.testingKnobs.LeaseStoreTestingKnobs.LeaseAcquireResultBlockEvent(LeaseAcquireFreshestBlock)
}
if err != nil {
return err
}
if didAcquire {
// Case 1: we didn't join an in-progress call and the lease is still
// valid.
break
} else if attemptsMade > 1 {
// Case 2: more than one acquisition has happened and the lease is still
// valid.
break
}
attemptsMade++
}
return nil
}
// upsertLocked inserts a lease for a particular table version.
// If an existing lease exists for the table version it replaces
// it and returns it.
func (t *tableState) upsertLocked(
ctx context.Context, table *tableVersionState,
) (*storedTableLease, error) {
s := t.mu.active.find(table.Version)
if s == nil {
if t.mu.active.findNewest() != nil {
log.Infof(ctx, "new lease: %s", table)
}
t.mu.active.insert(table)
return nil, nil
}
// The table is replacing an existing one at the same version.
if !table.hasValidExpiration(s) {
// This is a violation of an invariant and can actually not
// happen. We return an error here to aid in further investigations.
return nil, errors.Errorf("lease expiration monotonicity violation, (%s) vs (%s)", s, table)
}
s.mu.Lock()
table.mu.Lock()
// subsume the refcount of the older lease. This is permitted because
// the new lease has a greater expiration than the older lease and
// any transaction using the older lease can safely use a deadline set
// to the older lease's expiration even though the older lease is
// released! This is because the new lease is valid at the same table
// version at a greater expiration.
table.mu.refcount += s.mu.refcount
s.mu.refcount = 0
l := s.mu.lease
s.mu.lease = nil
if log.V(2) {
log.VEventf(ctx, 2, "replaced lease: %s with %s", s.stringLocked(), table.stringLocked())
}
table.mu.Unlock()
s.mu.Unlock()
t.mu.active.remove(s)
t.mu.active.insert(table)
return l, nil
}
// removeInactiveVersions removes inactive versions in t.mu.active.data with refcount 0.
// t.mu must be locked. It returns table version state that need to be released.
func (t *tableState) removeInactiveVersions() []*storedTableLease {
var leases []*storedTableLease
// A copy of t.mu.active.data must be made since t.mu.active.data will be changed
// within the loop.
for _, table := range append([]*tableVersionState(nil), t.mu.active.data...) {
func() {
table.mu.Lock()
defer table.mu.Unlock()
if table.mu.refcount == 0 {
t.mu.active.remove(table)
if l := table.mu.lease; l != nil {
table.mu.lease = nil
leases = append(leases, l)
}
}
}()
}
return leases
}
// If the lease cannot be obtained because the descriptor is in the process of
// being dropped or offline, the error will be of type inactiveTableError.
// The boolean returned is true if this call was actually responsible for the
// lease acquisition.
func acquireNodeLease(ctx context.Context, m *LeaseManager, id sqlbase.ID) (bool, error) {
var toRelease *storedTableLease
resultChan, didAcquire := m.group.DoChan(fmt.Sprintf("acquire%d", id), func() (interface{}, error) {
// Note that we use a new `context` here to avoid a situation where a cancellation
// of the first context cancels other callers to the `acquireNodeLease()` method,
// because of its use of `singleflight.Group`. See issue #41780 for how this has
// happened.
newCtx, cancel := m.stopper.WithCancelOnQuiesce(logtags.WithTags(context.Background(), logtags.FromContext(ctx)))
defer cancel()
if m.isDraining() {
return nil, errors.New("cannot acquire lease when draining")
}
newest := m.findNewest(id)
var minExpiration hlc.Timestamp
if newest != nil {