store.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 exports functionality for efficiently caching and mapping
  15. // `RangeRequest`s to corresponding `RangeResponse`s.
  16. package cache
  17. import (
  18. "errors"
  19. "sync"
  20. "github.com/golang/groupcache/lru"
  21. "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  22. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  23. "go.etcd.io/etcd/pkg/adt"
  24. )
  25. var (
  26. DefaultMaxEntries = 2048
  27. ErrCompacted = rpctypes.ErrGRPCCompacted
  28. )
  29. type Cache interface {
  30. Add(req *pb.RangeRequest, resp *pb.RangeResponse)
  31. Get(req *pb.RangeRequest) (*pb.RangeResponse, error)
  32. Compact(revision int64)
  33. Invalidate(key []byte, endkey []byte)
  34. Size() int
  35. Close()
  36. }
  37. // keyFunc returns the key of a request, which is used to look up its caching response in the cache.
  38. func keyFunc(req *pb.RangeRequest) string {
  39. // TODO: use marshalTo to reduce allocation
  40. b, err := req.Marshal()
  41. if err != nil {
  42. panic(err)
  43. }
  44. return string(b)
  45. }
  46. func NewCache(maxCacheEntries int) Cache {
  47. return &cache{
  48. lru: lru.New(maxCacheEntries),
  49. cachedRanges: adt.NewIntervalTree(),
  50. compactedRev: -1,
  51. }
  52. }
  53. func (c *cache) Close() {}
  54. // cache implements Cache
  55. type cache struct {
  56. mu sync.RWMutex
  57. lru *lru.Cache
  58. // a reverse index for cache invalidation
  59. cachedRanges adt.IntervalTree
  60. compactedRev int64
  61. }
  62. // Add adds the response of a request to the cache if its revision is larger than the compacted revision of the cache.
  63. func (c *cache) Add(req *pb.RangeRequest, resp *pb.RangeResponse) {
  64. key := keyFunc(req)
  65. c.mu.Lock()
  66. defer c.mu.Unlock()
  67. if req.Revision > c.compactedRev {
  68. c.lru.Add(key, resp)
  69. }
  70. // we do not need to invalidate a request with a revision specified.
  71. // so we do not need to add it into the reverse index.
  72. if req.Revision != 0 {
  73. return
  74. }
  75. var (
  76. iv *adt.IntervalValue
  77. ivl adt.Interval
  78. )
  79. if len(req.RangeEnd) != 0 {
  80. ivl = adt.NewStringAffineInterval(string(req.Key), string(req.RangeEnd))
  81. } else {
  82. ivl = adt.NewStringAffinePoint(string(req.Key))
  83. }
  84. iv = c.cachedRanges.Find(ivl)
  85. if iv == nil {
  86. val := map[string]struct{}{key: {}}
  87. c.cachedRanges.Insert(ivl, val)
  88. } else {
  89. val := iv.Val.(map[string]struct{})
  90. val[key] = struct{}{}
  91. iv.Val = val
  92. }
  93. }
  94. // Get looks up the caching response for a given request.
  95. // Get is also responsible for lazy eviction when accessing compacted entries.
  96. func (c *cache) Get(req *pb.RangeRequest) (*pb.RangeResponse, error) {
  97. key := keyFunc(req)
  98. c.mu.Lock()
  99. defer c.mu.Unlock()
  100. if req.Revision > 0 && req.Revision < c.compactedRev {
  101. c.lru.Remove(key)
  102. return nil, ErrCompacted
  103. }
  104. if resp, ok := c.lru.Get(key); ok {
  105. return resp.(*pb.RangeResponse), nil
  106. }
  107. return nil, errors.New("not exist")
  108. }
  109. // Invalidate invalidates the cache entries that intersecting with the given range from key to endkey.
  110. func (c *cache) Invalidate(key, endkey []byte) {
  111. c.mu.Lock()
  112. defer c.mu.Unlock()
  113. var (
  114. ivs []*adt.IntervalValue
  115. ivl adt.Interval
  116. )
  117. if len(endkey) == 0 {
  118. ivl = adt.NewStringAffinePoint(string(key))
  119. } else {
  120. ivl = adt.NewStringAffineInterval(string(key), string(endkey))
  121. }
  122. ivs = c.cachedRanges.Stab(ivl)
  123. for _, iv := range ivs {
  124. keys := iv.Val.(map[string]struct{})
  125. for key := range keys {
  126. c.lru.Remove(key)
  127. }
  128. }
  129. // delete after removing all keys since it is destructive to 'ivs'
  130. c.cachedRanges.Delete(ivl)
  131. }
  132. // Compact invalidate all caching response before the given rev.
  133. // Replace with the invalidation is lazy. The actual removal happens when the entries is accessed.
  134. func (c *cache) Compact(revision int64) {
  135. c.mu.Lock()
  136. defer c.mu.Unlock()
  137. if revision > c.compactedRev {
  138. c.compactedRev = revision
  139. }
  140. }
  141. func (c *cache) Size() int {
  142. c.mu.RLock()
  143. defer c.mu.RUnlock()
  144. return c.lru.Len()
  145. }