keys.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. timeout: to,
  50. }
  51. kAPI := httpKeysAPI{
  52. client: c,
  53. prefix: prefix,
  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. }
  86. func (k *httpKeysAPI) Create(key, val string, ttl time.Duration) (*Response, error) {
  87. create := &createAction{
  88. Prefix: k.prefix,
  89. Key: key,
  90. Value: val,
  91. }
  92. if ttl >= 0 {
  93. uttl := uint64(ttl.Seconds())
  94. create.TTL = &uttl
  95. }
  96. code, body, err := k.client.doWithTimeout(create)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return unmarshalHTTPResponse(code, body)
  101. }
  102. func (k *httpKeysAPI) Get(key string) (*Response, error) {
  103. get := &getAction{
  104. Prefix: k.prefix,
  105. Key: key,
  106. Recursive: false,
  107. }
  108. code, body, err := k.client.doWithTimeout(get)
  109. if err != nil {
  110. return nil, err
  111. }
  112. return unmarshalHTTPResponse(code, body)
  113. }
  114. func (k *httpKeysAPI) Watch(key string, idx uint64) Watcher {
  115. return &httpWatcher{
  116. client: k.client,
  117. nextWait: waitAction{
  118. Prefix: k.prefix,
  119. Key: key,
  120. WaitIndex: idx,
  121. Recursive: false,
  122. },
  123. }
  124. }
  125. func (k *httpKeysAPI) RecursiveWatch(key string, idx uint64) Watcher {
  126. return &httpWatcher{
  127. client: k.client,
  128. nextWait: waitAction{
  129. Prefix: k.prefix,
  130. Key: key,
  131. WaitIndex: idx,
  132. Recursive: true,
  133. },
  134. }
  135. }
  136. type httpWatcher struct {
  137. client *httpClient
  138. nextWait waitAction
  139. }
  140. func (hw *httpWatcher) Next() (*Response, error) {
  141. //TODO(bcwaldon): This needs to be cancellable by the calling user
  142. code, body, err := hw.client.do(context.Background(), &hw.nextWait)
  143. if err != nil {
  144. return nil, err
  145. }
  146. resp, err := unmarshalHTTPResponse(code, body)
  147. if err != nil {
  148. return nil, err
  149. }
  150. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  151. return resp, nil
  152. }
  153. // v2KeysURL forms a URL representing the location of a key.
  154. // The endpoint argument represents the base URL of an etcd
  155. // server. The prefix is the path needed to route from the
  156. // provided endpoint's path to the root of the keys API
  157. // (typically "/v2/keys").
  158. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  159. ep.Path = path.Join(ep.Path, prefix, key)
  160. return &ep
  161. }
  162. type getAction struct {
  163. Prefix string
  164. Key string
  165. Recursive bool
  166. }
  167. func (g *getAction) httpRequest(ep url.URL) *http.Request {
  168. u := v2KeysURL(ep, g.Prefix, g.Key)
  169. params := u.Query()
  170. params.Set("recursive", strconv.FormatBool(g.Recursive))
  171. u.RawQuery = params.Encode()
  172. req, _ := http.NewRequest("GET", u.String(), nil)
  173. return req
  174. }
  175. type waitAction struct {
  176. Prefix string
  177. Key string
  178. WaitIndex uint64
  179. Recursive bool
  180. }
  181. func (w *waitAction) httpRequest(ep url.URL) *http.Request {
  182. u := v2KeysURL(ep, w.Prefix, w.Key)
  183. params := u.Query()
  184. params.Set("wait", "true")
  185. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  186. params.Set("recursive", strconv.FormatBool(w.Recursive))
  187. u.RawQuery = params.Encode()
  188. req, _ := http.NewRequest("GET", u.String(), nil)
  189. return req
  190. }
  191. type createAction struct {
  192. Prefix string
  193. Key string
  194. Value string
  195. TTL *uint64
  196. }
  197. func (c *createAction) httpRequest(ep url.URL) *http.Request {
  198. u := v2KeysURL(ep, c.Prefix, c.Key)
  199. params := u.Query()
  200. params.Set("prevExist", "false")
  201. u.RawQuery = params.Encode()
  202. form := url.Values{}
  203. form.Add("value", c.Value)
  204. if c.TTL != nil {
  205. form.Add("ttl", strconv.FormatUint(*c.TTL, 10))
  206. }
  207. body := strings.NewReader(form.Encode())
  208. req, _ := http.NewRequest("PUT", u.String(), body)
  209. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  210. return req
  211. }
  212. func unmarshalHTTPResponse(code int, body []byte) (res *Response, err error) {
  213. switch code {
  214. case http.StatusOK, http.StatusCreated:
  215. res, err = unmarshalSuccessfulResponse(body)
  216. default:
  217. err = unmarshalErrorResponse(code)
  218. }
  219. return
  220. }
  221. func unmarshalSuccessfulResponse(body []byte) (*Response, error) {
  222. var res Response
  223. err := json.Unmarshal(body, &res)
  224. if err != nil {
  225. return nil, err
  226. }
  227. return &res, nil
  228. }
  229. func unmarshalErrorResponse(code int) error {
  230. switch code {
  231. case http.StatusNotFound:
  232. return ErrKeyNoExist
  233. case http.StatusPreconditionFailed:
  234. return ErrKeyExists
  235. case http.StatusInternalServerError:
  236. // this isn't necessarily true
  237. return ErrNoLeader
  238. default:
  239. }
  240. return fmt.Errorf("unrecognized HTTP status code %d", code)
  241. }