github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/kv/kvserver/lease_history.go (about) 1 // Copyright 2017 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 kvserver 12 13 import ( 14 "github.com/cockroachdb/cockroach/pkg/roachpb" 15 "github.com/cockroachdb/cockroach/pkg/util/envutil" 16 "github.com/cockroachdb/cockroach/pkg/util/syncutil" 17 ) 18 19 // leaseHistoryMaxEntries controls if replica lease histories are enabled and 20 // how much memory they take up when enabled. 21 var leaseHistoryMaxEntries = envutil.EnvOrDefaultInt("COCKROACH_LEASE_HISTORY", 5) 22 23 type leaseHistory struct { 24 syncutil.Mutex 25 index int 26 history []roachpb.Lease // A circular buffer with index. 27 } 28 29 func newLeaseHistory() *leaseHistory { 30 lh := &leaseHistory{ 31 history: make([]roachpb.Lease, 0, leaseHistoryMaxEntries), 32 } 33 return lh 34 } 35 36 func (lh *leaseHistory) add(lease roachpb.Lease) { 37 lh.Lock() 38 defer lh.Unlock() 39 40 // Not through the first pass through the buffer. 41 if lh.index == len(lh.history) { 42 lh.history = append(lh.history, lease) 43 } else { 44 lh.history[lh.index] = lease 45 } 46 lh.index++ 47 if lh.index >= leaseHistoryMaxEntries { 48 lh.index = 0 49 } 50 } 51 52 func (lh *leaseHistory) get() []roachpb.Lease { 53 lh.Lock() 54 defer lh.Unlock() 55 if len(lh.history) == 0 { 56 return nil 57 } 58 if len(lh.history) < leaseHistoryMaxEntries || lh.index == 0 { 59 result := make([]roachpb.Lease, len(lh.history)) 60 copy(result, lh.history) 61 return lh.history 62 } 63 first := lh.history[lh.index:] 64 second := lh.history[:lh.index] 65 result := make([]roachpb.Lease, len(first)+len(second)) 66 copy(result, first) 67 copy(result[len(first):], second) 68 return result 69 }