-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathlease_test.go
4061 lines (3654 loc) · 131 KB
/
lease_test.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.
// Note that there's also lease_internal_test.go, in package lease.
package lease_test
import (
"bytes"
"context"
gosql "database/sql"
"fmt"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"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/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/server/settingswatcher"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descbuilder"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/desctestutils"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/lease"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/regions"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc/keyside"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc/valueside"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scexec"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scop"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scplan"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlinstance/instancestorage"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness/slbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness/slprovider"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/lib/pq"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type leaseTest struct {
testing.TB
cluster serverutils.TestClusterInterface
server serverutils.ApplicationLayerInterface
db *gosql.DB
kvDB *kv.DB
nodes map[uint32]*lease.Manager
leaseManagerTestingKnobs lease.ManagerTestingKnobs
}
func init() {
lease.MoveTablePrimaryIndexIDtoTarget = func(
ctx context.Context, t *testing.T, s serverutils.ApplicationLayerInterface, id descpb.ID, indexID descpb.IndexID,
) {
require.NoError(t, sql.TestingDescsTxn(ctx, s, func(ctx context.Context, txn isql.Txn, col *descs.Collection) error {
t, err := col.MutableByID(txn.KV()).Table(ctx, id)
if err != nil {
return err
}
t.PrimaryIndex.ID = indexID
t.NextIndexID = indexID + 1
return col.WriteDesc(ctx, false /* kvTrace */, t, txn.KV())
}))
}
}
func newLeaseTest(tb testing.TB, params base.TestClusterArgs) *leaseTest {
if params.ServerArgs.Settings == nil {
params.ServerArgs.Settings = cluster.MakeTestingClusterSettings()
}
lease.LeaseEnableSessionBasedLeasing.Override(context.Background(), ¶ms.ServerArgs.Settings.SV, lease.SessionBasedDualWrite)
c := serverutils.StartCluster(tb, 3, params)
s := c.Server(0).ApplicationLayer()
lt := &leaseTest{
TB: tb,
cluster: c,
server: s,
db: s.SQLConn(tb, serverutils.DBName("")),
kvDB: s.DB(),
nodes: map[uint32]*lease.Manager{},
}
if params.ServerArgs.Knobs.SQLLeaseManager != nil {
lt.leaseManagerTestingKnobs =
*params.ServerArgs.Knobs.SQLLeaseManager.(*lease.ManagerTestingKnobs)
}
return lt
}
func (t *leaseTest) cleanup() {
t.cluster.Stopper().Stop(context.Background())
}
func (t *leaseTest) getLeases(descID descpb.ID) string {
const sql = `
SELECT version, sql_instance_id as "nodeID"
FROM "".crdb_internal.kv_session_based_leases
WHERE "desc_id" = $1 AND "sql_instance_id" > $2
ORDER BY version, "nodeID";
`
rows, err := t.db.Query(sql, descID, baseIDForLeaseTest)
if err != nil {
t.Fatal(err)
}
var buf bytes.Buffer
var prefix string
for rows.Next() {
var (
version int
instanceID int
)
if err := rows.Scan(&version, &instanceID); err != nil {
t.Fatal(err)
}
fmt.Fprintf(&buf, "%s/%d/%d", prefix, version, instanceID-baseIDForLeaseTest)
prefix = " "
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
return buf.String()
}
func (t *leaseTest) expectLeases(descID descpb.ID, expected string) {
testutils.SucceedsSoon(t, func() error {
leases := t.getLeases(descID)
if expected != leases {
return errors.Errorf("expected %s, but found %s", expected, leases)
}
return nil
})
}
func (t *leaseTest) acquire(nodeID uint32, descID descpb.ID) (lease.LeasedDescriptor, error) {
return t.node(nodeID).Acquire(context.Background(), t.server.Clock().Now(), descID)
}
func (t *leaseTest) acquireMinVersion(
nodeID uint32, descID descpb.ID, minVersion descpb.DescriptorVersion,
) (lease.LeasedDescriptor, error) {
return t.node(nodeID).TestingAcquireAndAssertMinVersion(
context.Background(), t.server.Clock().Now(), descID, minVersion)
}
func (t *leaseTest) mustAcquire(nodeID uint32, descID descpb.ID) lease.LeasedDescriptor {
ld, err := t.acquire(nodeID, descID)
if err != nil {
t.Fatal(err)
}
return ld
}
func (t *leaseTest) mustAcquireMinVersion(
nodeID uint32, descID descpb.ID, minVersion descpb.DescriptorVersion,
) lease.LeasedDescriptor {
desc, err := t.acquireMinVersion(nodeID, descID, minVersion)
if err != nil {
t.Fatal(err)
}
return desc
}
func (t *leaseTest) release(nodeID uint32, desc lease.LeasedDescriptor) error {
desc.Release(context.Background())
return nil
}
// If leaseRemovalTracker is not nil, it will be used to block until the lease is
// released from the store. If the lease is not supposed to be released from the
// store (i.e. it's not expired and it's not for an old descriptor version),
// this shouldn't be set.
func (t *leaseTest) mustRelease(
nodeID uint32, desc lease.LeasedDescriptor, leaseRemovalTracker *lease.LeaseRemovalTracker,
) {
var tracker lease.RemovalTracker
if leaseRemovalTracker != nil {
tracker = leaseRemovalTracker.TrackRemoval(desc.Underlying())
}
desc.Release(context.Background())
if leaseRemovalTracker != nil {
if err := tracker.WaitForRemoval(); err != nil {
t.Fatal(err)
}
}
}
func (t *leaseTest) publish(ctx context.Context, nodeID uint32, descID descpb.ID) error {
_, err := t.node(nodeID).Publish(ctx, descID, func(catalog.MutableDescriptor) error {
return nil
}, nil)
return err
}
func (t *leaseTest) mustPublish(ctx context.Context, nodeID uint32, descID descpb.ID) {
if err := t.publish(ctx, nodeID, descID); err != nil {
t.Fatal(err)
}
}
const baseIDForLeaseTest = 1000
// node gets a Manager corresponding to a mock node. A new lease
// manager is initialized for each node. This allows for more complex
// inter-node lease testing.
func (t *leaseTest) node(nodeID uint32) *lease.Manager {
nodeID += baseIDForLeaseTest
mgr := t.nodes[nodeID]
if mgr == nil {
var c base.NodeIDContainer
c.Set(context.Background(), roachpb.NodeID(nodeID))
nc := base.NewSQLIDContainerForNode(&c)
// Note: we create a fresh AmbientContext here, instead of using
// t.server.AmbientCtx(), because we want the lease manager to
// pretend to be a mock node with its own node ID.
ambientCtx := log.MakeTestingAmbientCtxWithNewTracer()
ambientCtx.AddLogTag("n", nc)
// Hack the ExecutorConfig that we pass to the Manager to have a
// different node id.
cfgCpy := t.server.ExecutorConfig().(sql.ExecutorConfig)
cfgCpy.NodeInfo.NodeID = nc
// Create a new liveness provider for each node and start it up
cfgCpy.SQLLiveness = slprovider.New(
cfgCpy.AmbientCtx,
t.server.AppStopper(), t.server.Clock(), cfgCpy.DB, t.server.Codec(), cfgCpy.Settings, t.server.SettingsWatcher().(*settingswatcher.SettingsWatcher), nil, nil,
)
cfgCpy.SQLLiveness.Start(context.Background(), nil)
mgr = lease.NewLeaseManager(
ambientCtx,
nc,
cfgCpy.InternalDB,
cfgCpy.Clock,
cfgCpy.Settings,
t.server.SettingsWatcher().(*settingswatcher.SettingsWatcher),
cfgCpy.SQLLiveness,
cfgCpy.Codec,
t.leaseManagerTestingKnobs,
t.server.AppStopper(),
cfgCpy.RangeFeedFactory,
)
ctx := logtags.AddTag(context.Background(), "leasemgr", nodeID)
mgr.RunBackgroundLeasingTask(ctx)
t.nodes[nodeID] = mgr
}
return mgr
}
func TestLeaseManager(testingT *testing.T) {
defer leaktest.AfterTest(testingT)()
defer log.Scope(testingT).Close(testingT)
removalTracker := lease.NewLeaseRemovalTracker()
var params base.TestClusterArgs
params.ServerArgs.Knobs = base.TestingKnobs{
SQLLeaseManager: &lease.ManagerTestingKnobs{
LeaseStoreTestingKnobs: lease.StorageTestingKnobs{
LeaseReleasedEvent: removalTracker.LeaseRemovedNotification,
},
},
}
t := newLeaseTest(testingT, params)
defer t.cleanup()
descID := t.makeTableForTest()
ctx := context.Background()
// We can't acquire a lease on a non-existent table.
expected := "descriptor not found"
if _, err := t.acquire(1, 10000); !testutils.IsError(err, expected) {
t.Fatalf("expected %s, but found %v", expected, err)
}
// Acquire 2 leases from the same node. They should return the same
// table and expiration.
l1 := t.mustAcquire(1, descID)
l2 := t.mustAcquire(1, descID)
if l1.Underlying().GetID() != l2.Underlying().GetID() {
t.Fatalf("expected same lease, but found %v != %v", l1, l2)
} else if e1, e2 := l1.Expiration(ctx), l2.Expiration(ctx); e1 != e2 {
t.Fatalf("expected same lease timestamps, but found %v != %v", e1, e2)
}
t.expectLeases(descID, "/1/1")
t.mustRelease(1, l1, nil)
t.mustRelease(1, l2, nil)
t.expectLeases(descID, "/1/1")
// It is an error to acquire a lease for a specific version that doesn't
// exist yet.
expected = "version 2 for descriptor foo does not exist yet"
if _, err := t.acquireMinVersion(1, descID, 2); !testutils.IsError(err, expected) {
t.Fatalf("expected %s, but found %v", expected, err)
}
t.expectLeases(descID, "/1/1")
// Publish a new version and explicitly acquire it.
l2 = t.mustAcquire(1, descID)
t.mustPublish(ctx, 1, descID)
l3 := t.mustAcquireMinVersion(1, descID, 2)
t.expectLeases(descID, "/1/1 /2/1")
// When the last local reference on the new version is released we don't
// release the node lease.
t.mustRelease(1, l3, nil)
t.expectLeases(descID, "/1/1 /2/1")
// We can still acquire a local reference on the old version since it hasn't
// expired.
l4 := t.mustAcquireMinVersion(1, descID, 1)
t.mustRelease(1, l4, nil)
t.expectLeases(descID, "/1/1 /2/1")
// When the last local reference on the old version is released the node
// lease is also released.
t.mustRelease(1, l2, removalTracker)
t.expectLeases(descID, "/2/1")
// Acquire 2 node leases on version 2.
l5 := t.mustAcquireMinVersion(1, descID, 2)
l6 := t.mustAcquireMinVersion(2, descID, 2)
// Publish version 3. This will succeed immediately.
t.mustPublish(ctx, 3, descID)
// Start a goroutine to publish version 4 which will block until the version
// 2 leases are released.
var wg sync.WaitGroup
wg.Add(1)
go func() {
t.mustPublish(ctx, 3, descID)
wg.Done()
}()
// Force both nodes ahead to version 3.
l7 := t.mustAcquireMinVersion(1, descID, 3)
l8 := t.mustAcquireMinVersion(2, descID, 3)
t.expectLeases(descID, "/2/1 /2/2 /3/1 /3/2")
t.mustRelease(1, l5, removalTracker)
t.expectLeases(descID, "/2/2 /3/1 /3/2")
t.mustRelease(2, l6, removalTracker)
t.expectLeases(descID, "/3/1 /3/2")
// Wait for version 4 to be published.
wg.Wait()
l9 := t.mustAcquireMinVersion(1, descID, 4)
t.mustRelease(1, l7, removalTracker)
t.mustRelease(2, l8, nil)
t.expectLeases(descID, "/3/2 /4/1")
t.mustRelease(1, l9, nil)
t.expectLeases(descID, "/3/2 /4/1")
}
func (t *leaseTest) makeTableForTest() descpb.ID {
tdb := sqlutils.MakeSQLRunner(t.db)
tdb.Exec(t, "CREATE TABLE foo (i INT PRIMARY KEY)")
var descID descpb.ID
tdb.QueryRow(t, "SELECT 'foo'::regclass::int").Scan(&descID)
return descID
}
func TestLeaseManagerReacquire(testingT *testing.T) {
defer leaktest.AfterTest(testingT)()
defer log.Scope(testingT).Close(testingT)
ctx := context.Background()
var params base.TestClusterArgs
params.ServerArgs.DefaultTestTenant = base.TestDoesNotWorkWithSharedProcessModeButWeDontKnowWhyYet(
base.TestTenantProbabilistic, 112957,
)
params.ServerArgs.Settings = cluster.MakeTestingClusterSettings()
// Set the lease duration such that the next lease acquisition will
// require the lease to be reacquired.
lease.LeaseDuration.Override(ctx, ¶ms.ServerArgs.Settings.SV, 0)
removalTracker := lease.NewLeaseRemovalTracker()
params.ServerArgs.Knobs = base.TestingKnobs{
SQLLeaseManager: &lease.ManagerTestingKnobs{
LeaseStoreTestingKnobs: lease.StorageTestingKnobs{
LeaseReleasedEvent: removalTracker.LeaseRemovedNotification,
},
},
}
t := newLeaseTest(testingT, params)
defer t.cleanup()
descID := t.makeTableForTest()
l1 := t.mustAcquire(1, descID)
t.expectLeases(descID, "/1/1")
e1 := l1.Expiration(ctx)
// Another lease acquisition from the same node will result in a new lease.
rt := removalTracker.TrackRemoval(l1.Underlying())
l3 := t.mustAcquire(1, descID)
e3 := l3.Expiration(ctx)
if l1.Underlying().GetID() == l3.Underlying().GetID() && e3.WallTime == e1.WallTime {
t.Fatalf("expected different leases, but found %v", l1)
}
if e3.WallTime < e1.WallTime {
t.Fatalf("expected new lease expiration (%s) to be after old lease expiration (%s)",
e3, e1)
}
// In acquiring the new lease the older lease is released.
if err := rt.WaitForRemoval(); err != nil {
t.Fatal(err)
}
// Only one actual lease.
t.expectLeases(descID, "/1/1")
t.mustRelease(1, l1, nil)
t.mustRelease(1, l3, nil)
}
func TestLeaseManagerPublishVersionChanged(testingT *testing.T) {
defer leaktest.AfterTest(testingT)()
defer log.Scope(testingT).Close(testingT)
t := newLeaseTest(testingT, base.TestClusterArgs{})
defer t.cleanup()
descID := t.makeTableForTest()
// Start two goroutines that are concurrently trying to publish a new version
// of the descriptor. The first goroutine progresses to the update function
// and then signals the second goroutine to start which is allowed to proceed
// through completion. The first goroutine is then signaled and when it
// attempts to publish the new version it will encounter an update error and
// retry the transaction. Upon retry it will see that the descriptor version
// has changed and have to proceed to its outer retry loop and wait for the
// number of leases on the previous version to drop to 0.
n1 := t.node(1)
n2 := t.node(2)
n1update := make(chan struct{})
n2start := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
go func(n1update, n2start chan struct{}) {
_, err := n1.Publish(context.Background(), descID, func(catalog.MutableDescriptor) error {
if n2start != nil {
// Signal node 2 to start.
close(n2start)
n2start = nil
}
// Wait for node 2 signal indicating that node 2 finished publication of
// a new version.
<-n1update
return nil
}, nil)
if err != nil {
panic(err)
}
wg.Done()
}(n1update, n2start)
go func(n1update, n2start chan struct{}) {
// Wait for node 1 signal indicating that node 1 is in its update()
// function.
<-n2start
_, err := n2.Publish(context.Background(), descID, func(catalog.MutableDescriptor) error {
return nil
}, nil)
if err != nil {
panic(err)
}
close(n1update)
wg.Done()
}(n1update, n2start)
wg.Wait()
t.mustAcquire(1, descID)
t.expectLeases(descID, "/3/1")
}
func TestLeaseManagerPublishIllegalVersionChange(testingT *testing.T) {
defer leaktest.AfterTest(testingT)()
defer log.Scope(testingT).Close(testingT)
t := newLeaseTest(testingT, base.TestClusterArgs{})
defer t.cleanup()
if _, err := t.node(1).Publish(
context.Background(), keys.LeaseTableID, func(desc catalog.MutableDescriptor) error {
table := desc.(*tabledesc.Mutable)
table.Version++
return nil
}, nil); !testutils.IsError(err, "updated version") {
t.Fatalf("unexpected error: %+v", err)
}
if _, err := t.node(1).Publish(
context.Background(), keys.LeaseTableID, func(desc catalog.MutableDescriptor) error {
table := desc.(*tabledesc.Mutable)
table.Version--
return nil
}, nil); !testutils.IsError(err, "updated version") {
t.Fatalf("unexpected error: %+v", err)
}
}
func TestLeaseManagerDrain(testingT *testing.T) {
defer leaktest.AfterTest(testingT)()
defer log.Scope(testingT).Close(testingT)
var params base.TestClusterArgs
leaseRemovalTracker := lease.NewLeaseRemovalTracker()
params.ServerArgs.Knobs = base.TestingKnobs{
SQLLeaseManager: &lease.ManagerTestingKnobs{
LeaseStoreTestingKnobs: lease.StorageTestingKnobs{
LeaseReleasedEvent: leaseRemovalTracker.LeaseRemovedNotification,
},
},
}
t := newLeaseTest(testingT, params)
defer t.cleanup()
ctx := context.Background()
descID := t.makeTableForTest()
{
l1 := t.mustAcquire(1, descID)
l2 := t.mustAcquire(2, descID)
t.mustRelease(1, l1, nil)
t.expectLeases(descID, "/1/1 /1/2")
// Removal tracker to track for node 1's lease removal once the node
// starts draining.
l1RemovalTracker := leaseRemovalTracker.TrackRemoval(l1.Underlying())
t.node(1).SetDraining(ctx, true, nil /* reporter */)
t.node(2).SetDraining(ctx, true, nil /* reporter */)
// Leases cannot be acquired when in draining mode.
if _, err := t.acquire(1, descID); !testutils.IsError(err, "cannot acquire lease when draining") {
t.Fatalf("unexpected error: %v", err)
}
// Node 1's lease has a refcount of 0 and should therefore be removed from
// the store.
if err := l1RemovalTracker.WaitForRemoval(); err != nil {
t.Fatal(err)
}
t.expectLeases(descID, "/1/2")
// Once node 2's lease is released, the lease should be removed from the
// store.
t.mustRelease(2, l2, leaseRemovalTracker)
t.expectLeases(descID, "")
}
{
// Check that leases with a refcount of 0 are correctly kept in the
// store once the drain mode has been exited.
t.node(1).SetDraining(ctx, false, nil /* reporter */)
l1 := t.mustAcquire(1, descID)
t.mustRelease(1, l1, nil)
t.expectLeases(descID, "/1/1")
}
}
// Test that we fail to lease a table that was marked for deletion.
func TestCantLeaseDeletedTable(testingT *testing.T) {
defer leaktest.AfterTest(testingT)()
defer log.Scope(testingT).Close(testingT)
var mu syncutil.Mutex
clearSchemaChangers := false
var params base.TestClusterArgs
params.ServerArgs.Knobs = base.TestingKnobs{
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
SchemaChangeJobNoOp: func() bool {
mu.Lock()
defer mu.Unlock()
return clearSchemaChangers
},
},
// Disable GC job.
GCJob: &sql.GCJobTestingKnobs{RunBeforeResume: func(_ jobspb.JobID) error { select {} }},
}
t := newLeaseTest(testingT, params)
defer t.cleanup()
_, err := t.db.Exec(`SET CLUSTER SETTING sql.defaults.use_declarative_schema_changer = 'off';`)
if err != nil {
t.Fatal(err)
}
_, err = t.db.Exec(`SET use_declarative_schema_changer = 'off';`)
if err != nil {
t.Fatal(err)
}
sql := `
CREATE DATABASE test;
CREATE TABLE test.t(a INT PRIMARY KEY);
`
_, err = t.db.Exec(sql)
if err != nil {
t.Fatal(err)
}
tableDesc := desctestutils.TestingGetPublicTableDescriptor(t.kvDB, t.server.Codec(), "test", "t")
// Block schema changers so that the table we're about to DROP is not actually
// dropped; it will be left in a "deleted" state.
mu.Lock()
clearSchemaChangers = true
mu.Unlock()
// DROP the table
_, err = t.db.Exec(`DROP TABLE test.t`)
if err != nil {
t.Fatal(err)
}
// Make sure we can't get a lease on the descriptor.
// try to acquire at a bogus version to make sure we don't get back a lease we
// already had.
_, err = t.acquireMinVersion(1, tableDesc.GetID(), tableDesc.GetVersion()+123)
if !testutils.IsError(err, "descriptor is being dropped") {
t.Fatalf("got a different error than expected: %v", err)
}
}
func acquire(
ctx context.Context, s serverutils.ApplicationLayerInterface, descID descpb.ID,
) (lease.LeasedDescriptor, error) {
return s.LeaseManager().(*lease.Manager).Acquire(ctx, s.Clock().Now(), descID)
}
// Test that once a table is marked as deleted, a lease's refcount dropping to 0
// means the lease is released immediately, as opposed to being released only
// when it expires.
func TestLeasesOnDeletedTableAreReleasedImmediately(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
var mu syncutil.Mutex
clearSchemaChangers := false
var waitTableID descpb.ID
deleted := make(chan bool)
var params base.TestServerArgs
params.Knobs = base.TestingKnobs{
SQLLeaseManager: &lease.ManagerTestingKnobs{
TestingDescriptorRefreshedEvent: func(descriptor *descpb.Descriptor) {
mu.Lock()
defer mu.Unlock()
id, _, _, state, err := descpb.GetDescriptorMetadata(descriptor)
if err != nil {
t.Fatal(err)
}
if waitTableID != id {
return
}
if state == descpb.DescriptorState_DROP {
close(deleted)
waitTableID = 0
}
},
},
SQLSchemaChanger: &sql.SchemaChangerTestingKnobs{
SchemaChangeJobNoOp: func() bool {
mu.Lock()
defer mu.Unlock()
return clearSchemaChangers
},
},
// Disable GC job.
GCJob: &sql.GCJobTestingKnobs{RunBeforeResume: func(_ jobspb.JobID) error { select {} }},
}
srv, db, kvDB := serverutils.StartServer(t, params)
defer srv.Stopper().Stop(context.Background())
s := srv.ApplicationLayer()
_, err := db.Exec(`SET CLUSTER SETTING sql.defaults.use_declarative_schema_changer = 'off'`)
if err != nil {
t.Fatal(err)
}
_, err = db.Exec(`SET use_declarative_schema_changer = 'off';`)
if err != nil {
t.Fatal(err)
}
stmt := `
CREATE DATABASE test;
CREATE TABLE test.t(a INT PRIMARY KEY);
`
_, err = db.Exec(stmt)
if err != nil {
t.Fatal(err)
}
tableDesc := desctestutils.TestingGetPublicTableDescriptor(kvDB, s.Codec(), "test", "t")
ctx := context.Background()
lease1, err := acquire(ctx, s, tableDesc.GetID())
if err != nil {
t.Fatal(err)
}
lease2, err := acquire(ctx, s, tableDesc.GetID())
if err != nil {
t.Fatal(err)
}
// Block schema changers so that the table we're about to DROP is not actually
// dropped; it will be left in a "deleted" state.
// Also install a way to wait for the config update to be processed.
mu.Lock()
clearSchemaChangers = true
waitTableID = tableDesc.GetID()
mu.Unlock()
// DROP the table
_, err = db.Exec(`DROP TABLE test.t`)
if err != nil {
t.Fatal(err)
}
// Block until the Manager has processed the gossip update.
<-deleted
// We should still be able to acquire, because we have an active lease.
lease3, err := acquire(ctx, s, tableDesc.GetID())
if err != nil {
t.Fatal(err)
}
// Release everything.
lease1.Release(ctx)
lease2.Release(ctx)
lease3.Release(ctx)
// Now we shouldn't be able to acquire any more.
_, err = acquire(ctx, s, tableDesc.GetID())
if !testutils.IsError(err, "descriptor is being dropped") {
t.Fatalf("got a different error than expected: %v", err)
}
}
// TestSubqueryLeases tests that all leases acquired by a subquery are
// properly tracked and released.
func TestSubqueryLeases(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
fooRelease := make(chan struct{}, 10)
fooAcquiredCount := int32(0)
fooReleaseCount := int32(0)
var tableID int64
var params base.TestServerArgs
params.Knobs = base.TestingKnobs{
SQLLeaseManager: &lease.ManagerTestingKnobs{
LeaseStoreTestingKnobs: lease.StorageTestingKnobs{
RemoveOnceDereferenced: true,
LeaseAcquiredEvent: func(desc catalog.Descriptor, _ error) {
if desc.GetName() == "foo" {
atomic.AddInt32(&fooAcquiredCount, 1)
}
},
LeaseReleasedEvent: func(id descpb.ID, _ descpb.DescriptorVersion, _ error) {
if int64(id) == atomic.LoadInt64(&tableID) {
// Note: we don't use close(fooRelease) here because the
// lease on "foo" may be re-acquired (and re-released)
// multiple times, at least once for the first
// CREATE/SELECT pair and one for the finalf DROP.
atomic.AddInt32(&fooReleaseCount, 1)
fooRelease <- struct{}{}
}
},
},
},
}
srv, sqlDB, kvDB := serverutils.StartServer(t, params)
defer srv.Stopper().Stop(context.Background())
s := srv.ApplicationLayer()
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.foo (v INT);
`); err != nil {
t.Fatal(err)
}
if atomic.LoadInt32(&fooAcquiredCount) > 0 {
t.Fatalf("CREATE TABLE has acquired a lease: got %d, expected 0", atomic.LoadInt32(&fooAcquiredCount))
}
tableDesc := desctestutils.TestingGetPublicTableDescriptor(kvDB, s.Codec(), "t", "foo")
atomic.StoreInt64(&tableID, int64(tableDesc.GetID()))
if _, err := sqlDB.Exec(`
SELECT * FROM t.foo;
`); err != nil {
t.Fatal(err)
}
prev := atomic.LoadInt32(&fooAcquiredCount)
if prev == 0 {
t.Fatal("plain SELECT did not get lease; got 0, expected > 0")
}
if _, err := sqlDB.Exec(`
SELECT EXISTS(SELECT * FROM t.foo);
`); err != nil {
t.Fatal(err)
}
if atomic.LoadInt32(&fooAcquiredCount) == prev {
t.Fatalf("subquery has not acquired a lease")
}
// Now wait for the release to happen. We use a local timer
// to make the test fail faster if it needs to fail.
timeout := time.After(5 * time.Second)
select {
case <-timeout:
t.Fatal("lease from sub-query was not released")
case <-fooRelease:
}
}
// Test that an AS OF SYSTEM TIME query uses the table cache.
func TestAsOfSystemTimeUsesCache(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
fooAcquiredCount := int32(0)
var params base.TestServerArgs
params.Knobs = base.TestingKnobs{
SQLLeaseManager: &lease.ManagerTestingKnobs{
LeaseStoreTestingKnobs: lease.StorageTestingKnobs{
RemoveOnceDereferenced: true,
LeaseAcquiredEvent: func(desc catalog.Descriptor, _ error) {
if desc.GetName() == "foo" {
atomic.AddInt32(&fooAcquiredCount, 1)
}
},
},
},
}
s, sqlDB, _ := serverutils.StartServer(t, params)
defer s.Stopper().Stop(context.Background())
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.foo (v INT);
`); err != nil {
t.Fatal(err)
}
if atomic.LoadInt32(&fooAcquiredCount) > 0 {
t.Fatalf("CREATE TABLE has acquired a lease: got %d, expected 0", atomic.LoadInt32(&fooAcquiredCount))
}
var tsVal string
if err := sqlDB.QueryRow("SELECT cluster_logical_timestamp()").Scan(&tsVal); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(
fmt.Sprintf(`SELECT * FROM t.foo AS OF SYSTEM TIME %s;`, tsVal),
); err != nil {
t.Fatal(err)
}
count := atomic.LoadInt32(&fooAcquiredCount)
if count == 0 {
t.Fatal("SELECT did not get lease; got 0, expected > 0")
}
}
// TestDescriptorRefreshOnRetry tests that all descriptors acquired by
// a query are properly released before the query is retried.
func TestDescriptorRefreshOnRetry(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
fooAcquiredCount := int32(0)
fooReleaseCount := int32(0)
var tableID int64
var params base.TestServerArgs
params.Knobs = base.TestingKnobs{
SQLLeaseManager: &lease.ManagerTestingKnobs{
LeaseStoreTestingKnobs: lease.StorageTestingKnobs{
// Set this so we observe a release event from the cache
// when the API releases the descriptor.
RemoveOnceDereferenced: true,
LeaseAcquiredEvent: func(desc catalog.Descriptor, _ error) {
if desc.GetName() == "foo" {
atomic.AddInt32(&fooAcquiredCount, 1)
}
},
LeaseReleasedEvent: func(id descpb.ID, _ descpb.DescriptorVersion, _ error) {
if int64(id) == atomic.LoadInt64(&tableID) {
atomic.AddInt32(&fooReleaseCount, 1)
}
},
},
},
}
srv, sqlDB, kvDB := serverutils.StartServer(t, params)
defer srv.Stopper().Stop(context.Background())
s := srv.ApplicationLayer()
// Disable the automatic stats collection, which could interfere with
// the lease acquisition counts in this test.
if _, err := sqlDB.Exec("SET CLUSTER SETTING sql.stats.automatic_collection.enabled = false"); err != nil {
t.Fatal(err)
}
if _, err := sqlDB.Exec(`
CREATE DATABASE t;
CREATE TABLE t.foo (v INT);
`); err != nil {
t.Fatal(err)
}
if atomic.LoadInt32(&fooAcquiredCount) > 0 {
t.Fatalf("CREATE TABLE has acquired a descriptor")
}
tableDesc := desctestutils.TestingGetPublicTableDescriptor(kvDB, s.Codec(), "t", "foo")
atomic.StoreInt64(&tableID, int64(tableDesc.GetID()))
tx, err := sqlDB.Begin()
if err != nil {
t.Fatal(err)
}
_, err = tx.Exec("SAVEPOINT cockroach_restart")
require.NoError(t, err)
// This will acquire a descriptor. We'll check that it gets released before we retry.
if _, err := tx.Exec(`
SELECT * FROM t.foo;
`); err != nil {
t.Fatal(err)
}
// Descriptor has been acquired one more time than it has been released.
aCount, rCount := atomic.LoadInt32(&fooAcquiredCount), atomic.LoadInt32(&fooReleaseCount)
if aCount != rCount+1 {
t.Fatalf("invalid descriptor acquisition counts = %d, %d", aCount, rCount)
}
if _, err := tx.Exec(
"SELECT crdb_internal.force_retry('100s':::INTERVAL)"); !testutils.IsError(
err, `forced by crdb_internal\.force_retry\(\)`) {
t.Fatal(err)
}