store.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. compactedRev: -1,
  50. }
  51. }
  52. func (c *cache) Close() {}
  53. // cache implements Cache
  54. type cache struct {
  55. mu sync.RWMutex
  56. lru *lru.Cache
  57. // a reverse index for cache invalidation
  58. cachedRanges adt.IntervalTree
  59. compactedRev int64
  60. }
  61. // Add adds the response of a request to the cache if its revision is larger than the compacted revision of the cache.
  62. func (c *cache) Add(req *pb.RangeRequest, resp *pb.RangeResponse) {
  63. key := keyFunc(req)
  64. c.mu.Lock()
  65. defer c.mu.Unlock()
  66. if req.Revision > c.compactedRev {
  67. c.lru.Add(key, resp)
  68. }
  69. // we do not need to invalidate a request with a revision specified.
  70. // so we do not need to add it into the reverse index.
  71. if req.Revision != 0 {
  72. return
  73. }
  74. var (
  75. iv *adt.IntervalValue
  76. ivl adt.Interval
  77. )
  78. if len(req.RangeEnd) != 0 {
  79. ivl = adt.NewStringAffineInterval(string(req.Key), string(req.RangeEnd))
  80. } else {
  81. ivl = adt.NewStringAffinePoint(string(req.Key))
  82. }
  83. iv = c.cachedRanges.Find(ivl)
  84. if iv == nil {
  85. c.cachedRanges.Insert(ivl, []string{key})
  86. } else {
  87. iv.Val = append(iv.Val.([]string), key)
  88. }
  89. }
  90. // Get looks up the caching response for a given request.
  91. // Get is also responsible for lazy eviction when accessing compacted entries.
  92. func (c *cache) Get(req *pb.RangeRequest) (*pb.RangeResponse, error) {
  93. key := keyFunc(req)
  94. c.mu.Lock()
  95. defer c.mu.Unlock()
  96. if req.Revision > 0 && req.Revision < c.compactedRev {
  97. c.lru.Remove(key)
  98. return nil, ErrCompacted
  99. }
  100. if resp, ok := c.lru.Get(key); ok {
  101. return resp.(*pb.RangeResponse), nil
  102. }
  103. return nil, errors.New("not exist")
  104. }
  105. // Invalidate invalidates the cache entries that intersecting with the given range from key to endkey.
  106. func (c *cache) Invalidate(key, endkey []byte) {
  107. c.mu.Lock()
  108. defer c.mu.Unlock()
  109. var (
  110. ivs []*adt.IntervalValue
  111. ivl adt.Interval
  112. )
  113. if len(endkey) == 0 {
  114. ivl = adt.NewStringAffinePoint(string(key))
  115. } else {
  116. ivl = adt.NewStringAffineInterval(string(key), string(endkey))
  117. }
  118. ivs = c.cachedRanges.Stab(ivl)
  119. for _, iv := range ivs {
  120. keys := iv.Val.([]string)
  121. for _, key := range keys {
  122. c.lru.Remove(key)
  123. }
  124. }
  125. // delete after removing all keys since it is destructive to 'ivs'
  126. c.cachedRanges.Delete(ivl)
  127. }
  128. // Compact invalidate all caching response before the given rev.
  129. // Replace with the invalidation is lazy. The actual removal happens when the entries is accessed.
  130. func (c *cache) Compact(revision int64) {
  131. c.mu.Lock()
  132. defer c.mu.Unlock()
  133. if revision > c.compactedRev {
  134. c.compactedRev = revision
  135. }
  136. }
  137. func (c *cache) Size() int {
  138. c.mu.RLock()
  139. defer c.mu.RUnlock()
  140. return c.lru.Len()
  141. }