kv.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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 grpcproxy
  15. import (
  16. "github.com/coreos/etcd/clientv3"
  17. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  18. "github.com/coreos/etcd/proxy/grpcproxy/cache"
  19. "golang.org/x/net/context"
  20. )
  21. type kvProxy struct {
  22. kv clientv3.KV
  23. cache cache.Cache
  24. }
  25. func NewKvProxy(c *clientv3.Client) (pb.KVServer, <-chan struct{}) {
  26. kv := &kvProxy{
  27. kv: c.KV,
  28. cache: cache.NewCache(cache.DefaultMaxEntries),
  29. }
  30. donec := make(chan struct{})
  31. close(donec)
  32. return kv, donec
  33. }
  34. func (p *kvProxy) Range(ctx context.Context, r *pb.RangeRequest) (*pb.RangeResponse, error) {
  35. if r.Serializable {
  36. resp, err := p.cache.Get(r)
  37. switch err {
  38. case nil:
  39. cacheHits.Inc()
  40. return resp, nil
  41. case cache.ErrCompacted:
  42. cacheHits.Inc()
  43. return nil, err
  44. }
  45. }
  46. cachedMisses.Inc()
  47. resp, err := p.kv.Do(ctx, RangeRequestToOp(r))
  48. if err != nil {
  49. return nil, err
  50. }
  51. // cache linearizable as serializable
  52. req := *r
  53. req.Serializable = true
  54. gresp := (*pb.RangeResponse)(resp.Get())
  55. p.cache.Add(&req, gresp)
  56. cacheKeys.Set(float64(p.cache.Size()))
  57. return gresp, nil
  58. }
  59. func (p *kvProxy) Put(ctx context.Context, r *pb.PutRequest) (*pb.PutResponse, error) {
  60. p.cache.Invalidate(r.Key, nil)
  61. cacheKeys.Set(float64(p.cache.Size()))
  62. resp, err := p.kv.Do(ctx, PutRequestToOp(r))
  63. return (*pb.PutResponse)(resp.Put()), err
  64. }
  65. func (p *kvProxy) DeleteRange(ctx context.Context, r *pb.DeleteRangeRequest) (*pb.DeleteRangeResponse, error) {
  66. p.cache.Invalidate(r.Key, r.RangeEnd)
  67. cacheKeys.Set(float64(p.cache.Size()))
  68. resp, err := p.kv.Do(ctx, DelRequestToOp(r))
  69. return (*pb.DeleteRangeResponse)(resp.Del()), err
  70. }
  71. func (p *kvProxy) txnToCache(reqs []*pb.RequestOp, resps []*pb.ResponseOp) {
  72. for i := range resps {
  73. switch tv := resps[i].Response.(type) {
  74. case *pb.ResponseOp_ResponsePut:
  75. p.cache.Invalidate(reqs[i].GetRequestPut().Key, nil)
  76. case *pb.ResponseOp_ResponseDeleteRange:
  77. rdr := reqs[i].GetRequestDeleteRange()
  78. p.cache.Invalidate(rdr.Key, rdr.RangeEnd)
  79. case *pb.ResponseOp_ResponseRange:
  80. req := *(reqs[i].GetRequestRange())
  81. req.Serializable = true
  82. p.cache.Add(&req, tv.ResponseRange)
  83. }
  84. }
  85. }
  86. func (p *kvProxy) Txn(ctx context.Context, r *pb.TxnRequest) (*pb.TxnResponse, error) {
  87. txn := p.kv.Txn(ctx)
  88. cmps := make([]clientv3.Cmp, len(r.Compare))
  89. thenops := make([]clientv3.Op, len(r.Success))
  90. elseops := make([]clientv3.Op, len(r.Failure))
  91. for i := range r.Compare {
  92. cmps[i] = (clientv3.Cmp)(*r.Compare[i])
  93. }
  94. for i := range r.Success {
  95. thenops[i] = requestOpToOp(r.Success[i])
  96. }
  97. for i := range r.Failure {
  98. elseops[i] = requestOpToOp(r.Failure[i])
  99. }
  100. resp, err := txn.If(cmps...).Then(thenops...).Else(elseops...).Commit()
  101. if err != nil {
  102. return nil, err
  103. }
  104. // txn may claim an outdated key is updated; be safe and invalidate
  105. for _, cmp := range r.Compare {
  106. p.cache.Invalidate(cmp.Key, nil)
  107. }
  108. // update any fetched keys
  109. if resp.Succeeded {
  110. p.txnToCache(r.Success, resp.Responses)
  111. } else {
  112. p.txnToCache(r.Failure, resp.Responses)
  113. }
  114. cacheKeys.Set(float64(p.cache.Size()))
  115. return (*pb.TxnResponse)(resp), nil
  116. }
  117. func (p *kvProxy) Compact(ctx context.Context, r *pb.CompactionRequest) (*pb.CompactionResponse, error) {
  118. var opts []clientv3.CompactOption
  119. if r.Physical {
  120. opts = append(opts, clientv3.WithCompactPhysical())
  121. }
  122. resp, err := p.kv.Compact(ctx, r.Revision, opts...)
  123. if err == nil {
  124. p.cache.Compact(r.Revision)
  125. }
  126. cacheKeys.Set(float64(p.cache.Size()))
  127. return (*pb.CompactionResponse)(resp), err
  128. }
  129. func requestOpToOp(union *pb.RequestOp) clientv3.Op {
  130. switch tv := union.Request.(type) {
  131. case *pb.RequestOp_RequestRange:
  132. if tv.RequestRange != nil {
  133. return RangeRequestToOp(tv.RequestRange)
  134. }
  135. case *pb.RequestOp_RequestPut:
  136. if tv.RequestPut != nil {
  137. return PutRequestToOp(tv.RequestPut)
  138. }
  139. case *pb.RequestOp_RequestDeleteRange:
  140. if tv.RequestDeleteRange != nil {
  141. return DelRequestToOp(tv.RequestDeleteRange)
  142. }
  143. }
  144. panic("unknown request")
  145. }
  146. func RangeRequestToOp(r *pb.RangeRequest) clientv3.Op {
  147. opts := []clientv3.OpOption{}
  148. if len(r.RangeEnd) != 0 {
  149. opts = append(opts, clientv3.WithRange(string(r.RangeEnd)))
  150. }
  151. opts = append(opts, clientv3.WithRev(r.Revision))
  152. opts = append(opts, clientv3.WithLimit(r.Limit))
  153. opts = append(opts, clientv3.WithSort(
  154. clientv3.SortTarget(r.SortTarget),
  155. clientv3.SortOrder(r.SortOrder)),
  156. )
  157. opts = append(opts, clientv3.WithMaxCreateRev(r.MaxCreateRevision))
  158. opts = append(opts, clientv3.WithMinCreateRev(r.MinCreateRevision))
  159. opts = append(opts, clientv3.WithMaxModRev(r.MaxModRevision))
  160. opts = append(opts, clientv3.WithMinModRev(r.MinModRevision))
  161. if r.CountOnly {
  162. opts = append(opts, clientv3.WithCountOnly())
  163. }
  164. if r.KeysOnly {
  165. opts = append(opts, clientv3.WithKeysOnly())
  166. }
  167. if r.Serializable {
  168. opts = append(opts, clientv3.WithSerializable())
  169. }
  170. return clientv3.OpGet(string(r.Key), opts...)
  171. }
  172. func PutRequestToOp(r *pb.PutRequest) clientv3.Op {
  173. opts := []clientv3.OpOption{}
  174. opts = append(opts, clientv3.WithLease(clientv3.LeaseID(r.Lease)))
  175. if r.IgnoreValue {
  176. opts = append(opts, clientv3.WithIgnoreValue())
  177. }
  178. if r.IgnoreLease {
  179. opts = append(opts, clientv3.WithIgnoreLease())
  180. }
  181. if r.PrevKv {
  182. opts = append(opts, clientv3.WithPrevKV())
  183. }
  184. return clientv3.OpPut(string(r.Key), string(r.Value), opts...)
  185. }
  186. func DelRequestToOp(r *pb.DeleteRangeRequest) clientv3.Op {
  187. opts := []clientv3.OpOption{}
  188. if len(r.RangeEnd) != 0 {
  189. opts = append(opts, clientv3.WithRange(string(r.RangeEnd)))
  190. }
  191. if r.PrevKv {
  192. opts = append(opts, clientv3.WithPrevKV())
  193. }
  194. return clientv3.OpDelete(string(r.Key), opts...)
  195. }