store.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package cache
  15. import (
  16. "errors"
  17. "sync"
  18. "time"
  19. "github.com/karlseguin/ccache"
  20. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  21. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  22. "github.com/coreos/etcd/pkg/adt"
  23. )
  24. var (
  25. DefaultMaxEntries = 2048
  26. ErrCompacted = rpctypes.ErrGRPCCompacted
  27. )
  28. const defaultHistoricTTL = time.Hour
  29. const defaultCurrentTTL = time.Minute
  30. type Cache interface {
  31. Add(req *pb.RangeRequest, resp *pb.RangeResponse)
  32. Get(req *pb.RangeRequest) (*pb.RangeResponse, error)
  33. Compact(revision int64)
  34. Invalidate(key []byte, endkey []byte)
  35. }
  36. // keyFunc returns the key of an request, which is used to look up in the cache for it's caching response.
  37. func keyFunc(req *pb.RangeRequest) string {
  38. // TODO: use marshalTo to reduce allocation
  39. b, err := req.Marshal()
  40. if err != nil {
  41. panic(err)
  42. }
  43. return string(b)
  44. }
  45. func NewCache(maxCacheEntries int) Cache {
  46. return &cache{
  47. lru: ccache.New(ccache.Configure().MaxSize(int64(maxCacheEntries))),
  48. compactedRev: -1,
  49. }
  50. }
  51. // cache implements Cache
  52. type cache struct {
  53. mu sync.RWMutex
  54. lru *ccache.Cache
  55. // a reverse index for cache invalidation
  56. cachedRanges adt.IntervalTree
  57. compactedRev int64
  58. }
  59. // Add adds the response of a request to the cache if its revision is larger than the compacted revision of the cache.
  60. func (c *cache) Add(req *pb.RangeRequest, resp *pb.RangeResponse) {
  61. key := keyFunc(req)
  62. c.mu.Lock()
  63. defer c.mu.Unlock()
  64. if req.Revision > c.compactedRev {
  65. if req.Revision == 0 {
  66. c.lru.Set(key, resp, defaultCurrentTTL)
  67. } else {
  68. c.lru.Set(key, resp, defaultHistoricTTL)
  69. }
  70. }
  71. // we do not need to invalidate a request with a revision specified.
  72. // so we do not need to add it into the reverse index.
  73. if req.Revision != 0 {
  74. return
  75. }
  76. var (
  77. iv *adt.IntervalValue
  78. ivl adt.Interval
  79. )
  80. if len(req.RangeEnd) != 0 {
  81. ivl = adt.NewStringAffineInterval(string(req.Key), string(req.RangeEnd))
  82. } else {
  83. ivl = adt.NewStringAffinePoint(string(req.Key))
  84. }
  85. iv = c.cachedRanges.Find(ivl)
  86. if iv == nil {
  87. c.cachedRanges.Insert(ivl, []string{key})
  88. } else {
  89. iv.Val = append(iv.Val.([]string), key)
  90. }
  91. }
  92. // Get looks up the caching response for a given request.
  93. // Get is also responsible for lazy eviction when accessing compacted entries.
  94. func (c *cache) Get(req *pb.RangeRequest) (*pb.RangeResponse, error) {
  95. key := keyFunc(req)
  96. c.mu.RLock()
  97. defer c.mu.RUnlock()
  98. if req.Revision < c.compactedRev {
  99. c.lru.Delete(key)
  100. return nil, ErrCompacted
  101. }
  102. if item := c.lru.Get(key); item != nil {
  103. return item.Value().(*pb.RangeResponse), nil
  104. }
  105. return nil, errors.New("not exist")
  106. }
  107. // Invalidate invalidates the cache entries that intersecting with the given range from key to endkey.
  108. func (c *cache) Invalidate(key, endkey []byte) {
  109. c.mu.Lock()
  110. defer c.mu.Unlock()
  111. var (
  112. ivs []*adt.IntervalValue
  113. ivl adt.Interval
  114. )
  115. if len(endkey) == 0 {
  116. ivl = adt.NewStringAffinePoint(string(key))
  117. } else {
  118. ivl = adt.NewStringAffineInterval(string(key), string(endkey))
  119. }
  120. ivs = c.cachedRanges.Stab(ivl)
  121. for _, iv := range ivs {
  122. keys := iv.Val.([]string)
  123. for _, key := range keys {
  124. c.lru.Delete(key)
  125. }
  126. }
  127. // delete after removing all keys since it is destructive to 'ivs'
  128. c.cachedRanges.Delete(ivl)
  129. }
  130. // Compact invalidate all caching response before the given rev.
  131. // Replace with the invalidation is lazy. The actual removal happens when the entries is accessed.
  132. func (c *cache) Compact(revision int64) {
  133. c.mu.Lock()
  134. defer c.mu.Unlock()
  135. if revision > c.compactedRev {
  136. c.compactedRev = revision
  137. }
  138. }