github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/kv/kvclient/kvcoord/leaseholder_cache_test.go (about) 1 // Copyright 2015 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package kvcoord 12 13 import ( 14 "context" 15 "testing" 16 17 "github.com/cockroachdb/cockroach/pkg/roachpb" 18 "github.com/cockroachdb/cockroach/pkg/util/leaktest" 19 ) 20 21 func staticSize(size int64) func() int64 { 22 return func() int64 { 23 return size 24 } 25 } 26 27 func TestLeaseHolderCache(t *testing.T) { 28 defer leaktest.AfterTest(t)() 29 ctx := context.Background() 30 cacheSize := (1 << 4) * defaultShards 31 lc := NewLeaseHolderCache(staticSize(int64(cacheSize))) 32 if repStoreID, ok := lc.Lookup(ctx, 12); ok { 33 t.Errorf("lookup of missing key returned: %d", repStoreID) 34 } 35 rangeID := roachpb.RangeID(5) 36 replicaStoreID := roachpb.StoreID(1) 37 lc.Update(ctx, rangeID, replicaStoreID) 38 if repStoreID, ok := lc.Lookup(ctx, rangeID); !ok { 39 t.Fatalf("expected StoreID %d", replicaStoreID) 40 } else if repStoreID != replicaStoreID { 41 t.Errorf("expected StoreID %d, got %d", replicaStoreID, repStoreID) 42 } 43 newReplicaStoreID := roachpb.StoreID(7) 44 lc.Update(ctx, rangeID, newReplicaStoreID) 45 if repStoreID, ok := lc.Lookup(ctx, rangeID); !ok { 46 t.Fatalf("expected StoreID %d", replicaStoreID) 47 } else if repStoreID != newReplicaStoreID { 48 t.Errorf("expected StoreID %d, got %d", newReplicaStoreID, repStoreID) 49 } 50 51 lc.Update(ctx, rangeID, roachpb.StoreID(0)) 52 if repStoreID, ok := lc.Lookup(ctx, rangeID); ok { 53 t.Errorf("lookup of evicted key returned: %d", repStoreID) 54 } 55 56 for i := 10; i < 10+cacheSize+2; i++ { 57 lc.Update(ctx, roachpb.RangeID(i), replicaStoreID) 58 } 59 _, ok11 := lc.Lookup(ctx, 11) 60 _, ok12 := lc.Lookup(ctx, 12) 61 if ok11 || !ok12 { 62 t.Fatalf("unexpected policy used in cache : %v, %v", ok11, ok12) 63 } 64 } 65 66 func BenchmarkLeaseHolderCacheParallel(b *testing.B) { 67 defer leaktest.AfterTest(b)() 68 ctx := context.Background() 69 cacheSize := (1 << 4) * defaultShards 70 lc := NewLeaseHolderCache(staticSize(int64(cacheSize))) 71 numRanges := 2 * len(lc.shards) 72 for i := 1; i <= numRanges; i++ { 73 rangeID := roachpb.RangeID(i) 74 lc.Update(ctx, rangeID, roachpb.StoreID(i)) 75 } 76 b.RunParallel(func(pb *testing.PB) { 77 var n int 78 for pb.Next() { 79 rangeID := roachpb.RangeID(n%numRanges + 1) 80 n++ 81 if _, ok := lc.Lookup(ctx, rangeID); !ok { 82 b.Fatalf("r%d: should be found in the cache", rangeID) 83 } 84 } 85 }) 86 }