key.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 recipe
  15. import (
  16. "fmt"
  17. "strings"
  18. "time"
  19. v3 "github.com/coreos/etcd/clientv3"
  20. "github.com/coreos/etcd/clientv3/concurrency"
  21. "golang.org/x/net/context"
  22. )
  23. // RemoteKV is a key/revision pair created by the client and stored on etcd
  24. type RemoteKV struct {
  25. kv v3.KV
  26. key string
  27. rev int64
  28. val string
  29. }
  30. func NewKey(kv v3.KV, key string, leaseID v3.LeaseID) (*RemoteKV, error) {
  31. return NewKV(kv, key, "", leaseID)
  32. }
  33. func NewKV(kv v3.KV, key, val string, leaseID v3.LeaseID) (*RemoteKV, error) {
  34. rev, err := putNewKV(kv, key, val, leaseID)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return &RemoteKV{kv, key, rev, val}, nil
  39. }
  40. func GetRemoteKV(kv v3.KV, key string) (*RemoteKV, error) {
  41. resp, err := kv.Get(context.TODO(), key)
  42. if err != nil {
  43. return nil, err
  44. }
  45. rev := resp.Header.Revision
  46. val := ""
  47. if len(resp.Kvs) > 0 {
  48. rev = resp.Kvs[0].ModRevision
  49. val = string(resp.Kvs[0].Value)
  50. }
  51. return &RemoteKV{kv: kv, key: key, rev: rev, val: val}, nil
  52. }
  53. func NewUniqueKey(kv v3.KV, prefix string) (*RemoteKV, error) {
  54. return NewUniqueKV(kv, prefix, "", 0)
  55. }
  56. func NewUniqueKV(kv v3.KV, prefix string, val string, leaseID v3.LeaseID) (*RemoteKV, error) {
  57. for {
  58. newKey := fmt.Sprintf("%s/%v", prefix, time.Now().UnixNano())
  59. rev, err := putNewKV(kv, newKey, val, 0)
  60. if err == nil {
  61. return &RemoteKV{kv, newKey, rev, val}, nil
  62. }
  63. if err != ErrKeyExists {
  64. return nil, err
  65. }
  66. }
  67. }
  68. // putNewKV attempts to create the given key, only succeeding if the key did
  69. // not yet exist.
  70. func putNewKV(kv v3.KV, key, val string, leaseID v3.LeaseID) (int64, error) {
  71. cmp := v3.Compare(v3.Version(key), "=", 0)
  72. req := v3.OpPut(key, val, v3.WithLease(leaseID))
  73. txnresp, err := kv.Txn(context.TODO()).If(cmp).Then(req).Commit()
  74. if err != nil {
  75. return 0, err
  76. }
  77. if !txnresp.Succeeded {
  78. return 0, ErrKeyExists
  79. }
  80. return txnresp.Header.Revision, nil
  81. }
  82. // NewSequentialKV allocates a new sequential key-value pair at <prefix>/nnnnn
  83. func NewSequentialKV(kv v3.KV, prefix, val string) (*RemoteKV, error) {
  84. return newSequentialKV(kv, prefix, val, 0)
  85. }
  86. // newSequentialKV allocates a new sequential key <prefix>/nnnnn with a given
  87. // value and lease. Note: a bookkeeping node __<prefix> is also allocated.
  88. func newSequentialKV(kv v3.KV, prefix, val string, leaseID v3.LeaseID) (*RemoteKV, error) {
  89. resp, err := kv.Get(context.TODO(), prefix, v3.WithLastKey()...)
  90. if err != nil {
  91. return nil, err
  92. }
  93. // add 1 to last key, if any
  94. newSeqNum := 0
  95. if len(resp.Kvs) != 0 {
  96. fields := strings.Split(string(resp.Kvs[0].Key), "/")
  97. _, serr := fmt.Sscanf(fields[len(fields)-1], "%d", &newSeqNum)
  98. if serr != nil {
  99. return nil, serr
  100. }
  101. newSeqNum++
  102. }
  103. newKey := fmt.Sprintf("%s/%016d", prefix, newSeqNum)
  104. // base prefix key must be current (i.e., <=) with the server update;
  105. // the base key is important to avoid the following:
  106. // N1: LastKey() == 1, start txn.
  107. // N2: New Key 2, New Key 3, Delete Key 2
  108. // N1: txn succeeds allocating key 2 when it shouldn't
  109. baseKey := "__" + prefix
  110. // current revision might contain modification so +1
  111. cmp := v3.Compare(v3.ModRevision(baseKey), "<", resp.Header.Revision+1)
  112. reqPrefix := v3.OpPut(baseKey, "", v3.WithLease(leaseID))
  113. reqNewKey := v3.OpPut(newKey, val, v3.WithLease(leaseID))
  114. txn := kv.Txn(context.TODO())
  115. txnresp, err := txn.If(cmp).Then(reqPrefix, reqNewKey).Commit()
  116. if err != nil {
  117. return nil, err
  118. }
  119. if !txnresp.Succeeded {
  120. return newSequentialKV(kv, prefix, val, leaseID)
  121. }
  122. return &RemoteKV{kv, newKey, txnresp.Header.Revision, val}, nil
  123. }
  124. func (rk *RemoteKV) Key() string { return rk.key }
  125. func (rk *RemoteKV) Revision() int64 { return rk.rev }
  126. func (rk *RemoteKV) Value() string { return rk.val }
  127. func (rk *RemoteKV) Delete() error {
  128. if rk.kv == nil {
  129. return nil
  130. }
  131. _, err := rk.kv.Delete(context.TODO(), rk.key)
  132. rk.kv = nil
  133. return err
  134. }
  135. func (rk *RemoteKV) Put(val string) error {
  136. _, err := rk.kv.Put(context.TODO(), rk.key, val)
  137. return err
  138. }
  139. // EphemeralKV is a new key associated with a session lease
  140. type EphemeralKV struct{ RemoteKV }
  141. // NewEphemeralKV creates a new key/value pair associated with a session lease
  142. func NewEphemeralKV(client *v3.Client, key, val string) (*EphemeralKV, error) {
  143. s, err := concurrency.NewSession(client)
  144. if err != nil {
  145. return nil, err
  146. }
  147. k, err := NewKV(client, key, val, s.Lease())
  148. if err != nil {
  149. return nil, err
  150. }
  151. return &EphemeralKV{*k}, nil
  152. }
  153. // NewUniqueEphemeralKey creates a new unique valueless key associated with a session lease
  154. func NewUniqueEphemeralKey(client *v3.Client, prefix string) (*EphemeralKV, error) {
  155. return NewUniqueEphemeralKV(client, prefix, "")
  156. }
  157. // NewUniqueEphemeralKV creates a new unique key/value pair associated with a session lease
  158. func NewUniqueEphemeralKV(client *v3.Client, prefix, val string) (ek *EphemeralKV, err error) {
  159. for {
  160. newKey := fmt.Sprintf("%s/%v", prefix, time.Now().UnixNano())
  161. ek, err = NewEphemeralKV(client, newKey, val)
  162. if err == nil || err != ErrKeyExists {
  163. break
  164. }
  165. }
  166. return ek, err
  167. }