keys.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package client
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "net/http"
  19. "net/url"
  20. "path"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
  25. )
  26. var (
  27. DefaultV2KeysPrefix = "/v2/keys"
  28. )
  29. var (
  30. ErrUnavailable = errors.New("client: no available etcd endpoints")
  31. ErrNoLeader = errors.New("client: no leader")
  32. ErrKeyNoExist = errors.New("client: key does not exist")
  33. ErrKeyExists = errors.New("client: key already exists")
  34. )
  35. func NewKeysAPI(tr *http.Transport, ep string, to time.Duration) (KeysAPI, error) {
  36. return newHTTPKeysAPIWithPrefix(tr, ep, to, DefaultV2KeysPrefix)
  37. }
  38. func NewDiscoveryKeysAPI(tr *http.Transport, ep string, to time.Duration) (KeysAPI, error) {
  39. return newHTTPKeysAPIWithPrefix(tr, ep, to, "")
  40. }
  41. func newHTTPKeysAPIWithPrefix(tr *http.Transport, ep string, to time.Duration, prefix string) (*httpKeysAPI, error) {
  42. u, err := url.Parse(ep)
  43. if err != nil {
  44. return nil, err
  45. }
  46. c := &httpClient{
  47. transport: tr,
  48. endpoint: *u,
  49. }
  50. kAPI := httpKeysAPI{
  51. client: c,
  52. prefix: prefix,
  53. timeout: to,
  54. }
  55. return &kAPI, nil
  56. }
  57. type KeysAPI interface {
  58. Create(key, value string, ttl time.Duration) (*Response, error)
  59. Get(key string) (*Response, error)
  60. Watch(key string, idx uint64) Watcher
  61. RecursiveWatch(key string, idx uint64) Watcher
  62. }
  63. type Watcher interface {
  64. Next() (*Response, error)
  65. }
  66. type Response struct {
  67. Action string `json:"action"`
  68. Node *Node `json:"node"`
  69. PrevNode *Node `json:"prevNode"`
  70. }
  71. type Nodes []*Node
  72. type Node struct {
  73. Key string `json:"key"`
  74. Value string `json:"value"`
  75. Nodes Nodes `json:"nodes"`
  76. ModifiedIndex uint64 `json:"modifiedIndex"`
  77. CreatedIndex uint64 `json:"createdIndex"`
  78. }
  79. func (n *Node) String() string {
  80. return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex)
  81. }
  82. type httpKeysAPI struct {
  83. client *httpClient
  84. prefix string
  85. timeout time.Duration
  86. }
  87. func (k *httpKeysAPI) Create(key, val string, ttl time.Duration) (*Response, error) {
  88. create := &createAction{
  89. Prefix: k.prefix,
  90. Key: key,
  91. Value: val,
  92. }
  93. if ttl >= 0 {
  94. uttl := uint64(ttl.Seconds())
  95. create.TTL = &uttl
  96. }
  97. ctx, cancel := context.WithTimeout(context.Background(), k.timeout)
  98. code, body, err := k.client.do(ctx, create)
  99. cancel()
  100. if err != nil {
  101. return nil, err
  102. }
  103. return unmarshalHTTPResponse(code, body)
  104. }
  105. func (k *httpKeysAPI) Get(key string) (*Response, error) {
  106. get := &getAction{
  107. Prefix: k.prefix,
  108. Key: key,
  109. Recursive: false,
  110. }
  111. ctx, cancel := context.WithTimeout(context.Background(), k.timeout)
  112. code, body, err := k.client.do(ctx, get)
  113. cancel()
  114. if err != nil {
  115. return nil, err
  116. }
  117. return unmarshalHTTPResponse(code, body)
  118. }
  119. func (k *httpKeysAPI) Watch(key string, idx uint64) Watcher {
  120. return &httpWatcher{
  121. client: k.client,
  122. nextWait: waitAction{
  123. Prefix: k.prefix,
  124. Key: key,
  125. WaitIndex: idx,
  126. Recursive: false,
  127. },
  128. }
  129. }
  130. func (k *httpKeysAPI) RecursiveWatch(key string, idx uint64) Watcher {
  131. return &httpWatcher{
  132. client: k.client,
  133. nextWait: waitAction{
  134. Prefix: k.prefix,
  135. Key: key,
  136. WaitIndex: idx,
  137. Recursive: true,
  138. },
  139. }
  140. }
  141. type httpWatcher struct {
  142. client *httpClient
  143. nextWait waitAction
  144. }
  145. func (hw *httpWatcher) Next() (*Response, error) {
  146. //TODO(bcwaldon): This needs to be cancellable by the calling user
  147. code, body, err := hw.client.do(context.Background(), &hw.nextWait)
  148. if err != nil {
  149. return nil, err
  150. }
  151. resp, err := unmarshalHTTPResponse(code, body)
  152. if err != nil {
  153. return nil, err
  154. }
  155. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  156. return resp, nil
  157. }
  158. // v2KeysURL forms a URL representing the location of a key.
  159. // The endpoint argument represents the base URL of an etcd
  160. // server. The prefix is the path needed to route from the
  161. // provided endpoint's path to the root of the keys API
  162. // (typically "/v2/keys").
  163. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  164. ep.Path = path.Join(ep.Path, prefix, key)
  165. return &ep
  166. }
  167. type getAction struct {
  168. Prefix string
  169. Key string
  170. Recursive bool
  171. }
  172. func (g *getAction) httpRequest(ep url.URL) *http.Request {
  173. u := v2KeysURL(ep, g.Prefix, g.Key)
  174. params := u.Query()
  175. params.Set("recursive", strconv.FormatBool(g.Recursive))
  176. u.RawQuery = params.Encode()
  177. req, _ := http.NewRequest("GET", u.String(), nil)
  178. return req
  179. }
  180. type waitAction struct {
  181. Prefix string
  182. Key string
  183. WaitIndex uint64
  184. Recursive bool
  185. }
  186. func (w *waitAction) httpRequest(ep url.URL) *http.Request {
  187. u := v2KeysURL(ep, w.Prefix, w.Key)
  188. params := u.Query()
  189. params.Set("wait", "true")
  190. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  191. params.Set("recursive", strconv.FormatBool(w.Recursive))
  192. u.RawQuery = params.Encode()
  193. req, _ := http.NewRequest("GET", u.String(), nil)
  194. return req
  195. }
  196. type createAction struct {
  197. Prefix string
  198. Key string
  199. Value string
  200. TTL *uint64
  201. }
  202. func (c *createAction) httpRequest(ep url.URL) *http.Request {
  203. u := v2KeysURL(ep, c.Prefix, c.Key)
  204. params := u.Query()
  205. params.Set("prevExist", "false")
  206. u.RawQuery = params.Encode()
  207. form := url.Values{}
  208. form.Add("value", c.Value)
  209. if c.TTL != nil {
  210. form.Add("ttl", strconv.FormatUint(*c.TTL, 10))
  211. }
  212. body := strings.NewReader(form.Encode())
  213. req, _ := http.NewRequest("PUT", u.String(), body)
  214. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  215. return req
  216. }
  217. func unmarshalHTTPResponse(code int, body []byte) (res *Response, err error) {
  218. switch code {
  219. case http.StatusOK, http.StatusCreated:
  220. res, err = unmarshalSuccessfulResponse(body)
  221. default:
  222. err = unmarshalErrorResponse(code)
  223. }
  224. return
  225. }
  226. func unmarshalSuccessfulResponse(body []byte) (*Response, error) {
  227. var res Response
  228. err := json.Unmarshal(body, &res)
  229. if err != nil {
  230. return nil, err
  231. }
  232. return &res, nil
  233. }
  234. func unmarshalErrorResponse(code int) error {
  235. switch code {
  236. case http.StatusNotFound:
  237. return ErrKeyNoExist
  238. case http.StatusPreconditionFailed:
  239. return ErrKeyExists
  240. case http.StatusInternalServerError:
  241. // this isn't necessarily true
  242. return ErrNoLeader
  243. default:
  244. }
  245. return fmt.Errorf("unrecognized HTTP status code %d", code)
  246. }