store.go 4.0 KB

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