kv.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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. go func() {
  32. defer close(donec)
  33. <-c.Ctx().Done()
  34. kv.cache.Close()
  35. }()
  36. return kv, donec
  37. }
  38. func (p *kvProxy) Range(ctx context.Context, r *pb.RangeRequest) (*pb.RangeResponse, error) {
  39. if r.Serializable {
  40. resp, err := p.cache.Get(r)
  41. switch err {
  42. case nil:
  43. cacheHits.Inc()
  44. return resp, nil
  45. case cache.ErrCompacted:
  46. cacheHits.Inc()
  47. return nil, err
  48. }
  49. }
  50. cachedMisses.Inc()
  51. resp, err := p.kv.Do(ctx, RangeRequestToOp(r))
  52. if err != nil {
  53. return nil, err
  54. }
  55. // cache linearizable as serializable
  56. req := *r
  57. req.Serializable = true
  58. gresp := (*pb.RangeResponse)(resp.Get())
  59. p.cache.Add(&req, gresp)
  60. return gresp, nil
  61. }
  62. func (p *kvProxy) Put(ctx context.Context, r *pb.PutRequest) (*pb.PutResponse, error) {
  63. p.cache.Invalidate(r.Key, nil)
  64. resp, err := p.kv.Do(ctx, PutRequestToOp(r))
  65. return (*pb.PutResponse)(resp.Put()), err
  66. }
  67. func (p *kvProxy) DeleteRange(ctx context.Context, r *pb.DeleteRangeRequest) (*pb.DeleteRangeResponse, error) {
  68. p.cache.Invalidate(r.Key, r.RangeEnd)
  69. resp, err := p.kv.Do(ctx, DelRequestToOp(r))
  70. return (*pb.DeleteRangeResponse)(resp.Del()), err
  71. }
  72. func (p *kvProxy) txnToCache(reqs []*pb.RequestOp, resps []*pb.ResponseOp) {
  73. for i := range resps {
  74. switch tv := resps[i].Response.(type) {
  75. case *pb.ResponseOp_ResponsePut:
  76. p.cache.Invalidate(reqs[i].GetRequestPut().Key, nil)
  77. case *pb.ResponseOp_ResponseDeleteRange:
  78. rdr := reqs[i].GetRequestDeleteRange()
  79. p.cache.Invalidate(rdr.Key, rdr.RangeEnd)
  80. case *pb.ResponseOp_ResponseRange:
  81. req := *(reqs[i].GetRequestRange())
  82. req.Serializable = true
  83. p.cache.Add(&req, tv.ResponseRange)
  84. }
  85. }
  86. }
  87. func (p *kvProxy) Txn(ctx context.Context, r *pb.TxnRequest) (*pb.TxnResponse, error) {
  88. txn := p.kv.Txn(ctx)
  89. cmps := make([]clientv3.Cmp, len(r.Compare))
  90. thenops := make([]clientv3.Op, len(r.Success))
  91. elseops := make([]clientv3.Op, len(r.Failure))
  92. for i := range r.Compare {
  93. cmps[i] = (clientv3.Cmp)(*r.Compare[i])
  94. }
  95. for i := range r.Success {
  96. thenops[i] = requestOpToOp(r.Success[i])
  97. }
  98. for i := range r.Failure {
  99. elseops[i] = requestOpToOp(r.Failure[i])
  100. }
  101. resp, err := txn.If(cmps...).Then(thenops...).Else(elseops...).Commit()
  102. if err != nil {
  103. return nil, err
  104. }
  105. // txn may claim an outdated key is updated; be safe and invalidate
  106. for _, cmp := range r.Compare {
  107. p.cache.Invalidate(cmp.Key, nil)
  108. }
  109. // update any fetched keys
  110. if resp.Succeeded {
  111. p.txnToCache(r.Success, resp.Responses)
  112. } else {
  113. p.txnToCache(r.Failure, resp.Responses)
  114. }
  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. return (*pb.CompactionResponse)(resp), err
  127. }
  128. func requestOpToOp(union *pb.RequestOp) clientv3.Op {
  129. switch tv := union.Request.(type) {
  130. case *pb.RequestOp_RequestRange:
  131. if tv.RequestRange != nil {
  132. return RangeRequestToOp(tv.RequestRange)
  133. }
  134. case *pb.RequestOp_RequestPut:
  135. if tv.RequestPut != nil {
  136. return PutRequestToOp(tv.RequestPut)
  137. }
  138. case *pb.RequestOp_RequestDeleteRange:
  139. if tv.RequestDeleteRange != nil {
  140. return DelRequestToOp(tv.RequestDeleteRange)
  141. }
  142. }
  143. panic("unknown request")
  144. }
  145. func RangeRequestToOp(r *pb.RangeRequest) clientv3.Op {
  146. opts := []clientv3.OpOption{}
  147. if len(r.RangeEnd) != 0 {
  148. opts = append(opts, clientv3.WithRange(string(r.RangeEnd)))
  149. }
  150. opts = append(opts, clientv3.WithRev(r.Revision))
  151. opts = append(opts, clientv3.WithLimit(r.Limit))
  152. opts = append(opts, clientv3.WithSort(
  153. clientv3.SortTarget(r.SortTarget),
  154. clientv3.SortOrder(r.SortOrder)),
  155. )
  156. opts = append(opts, clientv3.WithMaxCreateRev(r.MaxCreateRevision))
  157. opts = append(opts, clientv3.WithMinCreateRev(r.MinCreateRevision))
  158. opts = append(opts, clientv3.WithMaxModRev(r.MaxModRevision))
  159. opts = append(opts, clientv3.WithMinModRev(r.MinModRevision))
  160. if r.Serializable {
  161. opts = append(opts, clientv3.WithSerializable())
  162. }
  163. return clientv3.OpGet(string(r.Key), opts...)
  164. }
  165. func PutRequestToOp(r *pb.PutRequest) clientv3.Op {
  166. opts := []clientv3.OpOption{}
  167. opts = append(opts, clientv3.WithLease(clientv3.LeaseID(r.Lease)))
  168. return clientv3.OpPut(string(r.Key), string(r.Value), opts...)
  169. }
  170. func DelRequestToOp(r *pb.DeleteRangeRequest) clientv3.Op {
  171. opts := []clientv3.OpOption{}
  172. if len(r.RangeEnd) != 0 {
  173. opts = append(opts, clientv3.WithRange(string(r.RangeEnd)))
  174. }
  175. if r.PrevKv {
  176. opts = append(opts, clientv3.WithPrevKV())
  177. }
  178. return clientv3.OpDelete(string(r.Key), opts...)
  179. }