kv.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // Copyright 2015 CoreOS, Inc.
  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 clientv3
  15. import (
  16. "sync"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  19. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  20. )
  21. type (
  22. PutResponse pb.PutResponse
  23. GetResponse pb.RangeResponse
  24. DeleteResponse pb.DeleteRangeResponse
  25. TxnResponse pb.TxnResponse
  26. )
  27. type KV interface {
  28. // Put puts a key-value pair into etcd.
  29. // Note that key,value can be plain bytes array and string is
  30. // an immutable representation of that bytes array.
  31. // To get a string of bytes, do string([]byte(0x10, 0x20)).
  32. Put(ctx context.Context, key, val string, opts ...OpOption) (*PutResponse, error)
  33. // Get retrieves keys.
  34. // By default, Get will return the value for "key", if any.
  35. // When passed WithRange(end), Get will return the keys in the range [key, end).
  36. // When passed WithFromKey(), Get returns keys greater than or equal to key.
  37. // When passed WithRev(rev) with rev > 0, Get retrieves keys at the given revision;
  38. // if the required revision is compacted, the request will fail with ErrCompacted .
  39. // When passed WithLimit(limit), the number of returned keys is bounded by limit.
  40. // When passed WithSort(), the keys will be sorted.
  41. Get(ctx context.Context, key string, opts ...OpOption) (*GetResponse, error)
  42. // Delete deletes a key, or optionally using WithRange(end), [key, end).
  43. Delete(ctx context.Context, key string, opts ...OpOption) (*DeleteResponse, error)
  44. // Compact compacts etcd KV history before the given rev.
  45. Compact(ctx context.Context, rev int64) error
  46. // Do applies a single Op on KV without a transaction.
  47. // Do is useful when declaring operations to be issued at a later time
  48. // whereas Get/Put/Delete are for better suited for when the operation
  49. // should be immediately issued at time of declaration.
  50. // Do applies a single Op on KV without a transaction.
  51. // Do is useful when creating arbitrary operations to be issued at a
  52. // later time; the user can range over the operations, calling Do to
  53. // execute them. Get/Put/Delete, on the other hand, are best suited
  54. // for when the operation should be issued at the time of declaration.
  55. Do(ctx context.Context, op Op) (OpResponse, error)
  56. // Txn creates a transaction.
  57. Txn(ctx context.Context) Txn
  58. }
  59. type OpResponse struct {
  60. put *PutResponse
  61. get *GetResponse
  62. del *DeleteResponse
  63. }
  64. type kv struct {
  65. c *Client
  66. mu sync.Mutex // guards all fields
  67. conn *grpc.ClientConn // conn in-use
  68. remote pb.KVClient
  69. }
  70. func NewKV(c *Client) KV {
  71. conn := c.ActiveConnection()
  72. remote := pb.NewKVClient(conn)
  73. return &kv{
  74. conn: c.ActiveConnection(),
  75. remote: remote,
  76. c: c,
  77. }
  78. }
  79. func (kv *kv) Put(ctx context.Context, key, val string, opts ...OpOption) (*PutResponse, error) {
  80. r, err := kv.Do(ctx, OpPut(key, val, opts...))
  81. return r.put, err
  82. }
  83. func (kv *kv) Get(ctx context.Context, key string, opts ...OpOption) (*GetResponse, error) {
  84. r, err := kv.Do(ctx, OpGet(key, opts...))
  85. return r.get, err
  86. }
  87. func (kv *kv) Delete(ctx context.Context, key string, opts ...OpOption) (*DeleteResponse, error) {
  88. r, err := kv.Do(ctx, OpDelete(key, opts...))
  89. return r.del, err
  90. }
  91. func (kv *kv) Compact(ctx context.Context, rev int64) error {
  92. r := &pb.CompactionRequest{Revision: rev}
  93. _, err := kv.getRemote().Compact(ctx, r)
  94. if err == nil {
  95. return nil
  96. }
  97. if isHalted(ctx, err) {
  98. return err
  99. }
  100. go kv.switchRemote(err)
  101. return err
  102. }
  103. func (kv *kv) Txn(ctx context.Context) Txn {
  104. return &txn{
  105. kv: kv,
  106. ctx: ctx,
  107. }
  108. }
  109. func (kv *kv) Do(ctx context.Context, op Op) (OpResponse, error) {
  110. for {
  111. var err error
  112. switch op.t {
  113. // TODO: handle other ops
  114. case tRange:
  115. var resp *pb.RangeResponse
  116. r := &pb.RangeRequest{Key: op.key, RangeEnd: op.end, Limit: op.limit, Revision: op.rev}
  117. if op.sort != nil {
  118. r.SortOrder = pb.RangeRequest_SortOrder(op.sort.Order)
  119. r.SortTarget = pb.RangeRequest_SortTarget(op.sort.Target)
  120. }
  121. resp, err = kv.getRemote().Range(ctx, r)
  122. if err == nil {
  123. return OpResponse{get: (*GetResponse)(resp)}, nil
  124. }
  125. case tPut:
  126. var resp *pb.PutResponse
  127. r := &pb.PutRequest{Key: op.key, Value: op.val, Lease: int64(op.leaseID)}
  128. resp, err = kv.getRemote().Put(ctx, r)
  129. if err == nil {
  130. return OpResponse{put: (*PutResponse)(resp)}, nil
  131. }
  132. case tDeleteRange:
  133. var resp *pb.DeleteRangeResponse
  134. r := &pb.DeleteRangeRequest{Key: op.key, RangeEnd: op.end}
  135. resp, err = kv.getRemote().DeleteRange(ctx, r)
  136. if err == nil {
  137. return OpResponse{del: (*DeleteResponse)(resp)}, nil
  138. }
  139. default:
  140. panic("Unknown op")
  141. }
  142. if isHalted(ctx, err) {
  143. return OpResponse{}, err
  144. }
  145. // do not retry on modifications
  146. if op.isWrite() {
  147. go kv.switchRemote(err)
  148. return OpResponse{}, err
  149. }
  150. if nerr := kv.switchRemote(err); nerr != nil {
  151. return OpResponse{}, nerr
  152. }
  153. }
  154. }
  155. func (kv *kv) switchRemote(prevErr error) error {
  156. newConn, err := kv.c.retryConnection(kv.conn, prevErr)
  157. if err != nil {
  158. return err
  159. }
  160. kv.mu.Lock()
  161. defer kv.mu.Unlock()
  162. kv.conn = newConn
  163. kv.remote = pb.NewKVClient(kv.conn)
  164. return nil
  165. }
  166. func (kv *kv) getRemote() pb.KVClient {
  167. kv.mu.Lock()
  168. defer kv.mu.Unlock()
  169. return kv.remote
  170. }