store.go 3.8 KB

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