keys.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 client
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "net/http"
  20. "net/url"
  21. "path"
  22. "strconv"
  23. "strings"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  25. )
  26. type PrevExistType string
  27. const (
  28. PrevIgnore = PrevExistType("")
  29. PrevExist = PrevExistType("true")
  30. PrevNoExist = PrevExistType("false")
  31. )
  32. var (
  33. DefaultV2KeysPrefix = "/v2/keys"
  34. )
  35. var (
  36. ErrUnavailable = errors.New("client: no available etcd endpoints")
  37. ErrNoLeader = errors.New("client: no leader")
  38. ErrKeyNoExist = errors.New("client: key does not exist")
  39. ErrKeyExists = errors.New("client: key already exists")
  40. )
  41. func NewKeysAPI(c HTTPClient) KeysAPI {
  42. return &httpKeysAPI{
  43. client: c,
  44. prefix: DefaultV2KeysPrefix,
  45. }
  46. }
  47. func NewDiscoveryKeysAPI(c HTTPClient) KeysAPI {
  48. return &httpKeysAPI{
  49. client: c,
  50. prefix: "",
  51. }
  52. }
  53. type KeysAPI interface {
  54. Set(ctx context.Context, key, value string, opts SetOptions) (*Response, error)
  55. Create(ctx context.Context, key, value string) (*Response, error)
  56. Update(ctx context.Context, key, value string) (*Response, error)
  57. Get(ctx context.Context, key string) (*Response, error)
  58. RGet(ctx context.Context, key string) (*Response, error)
  59. Watch(key string, idx uint64) Watcher
  60. RWatch(key string, idx uint64) Watcher
  61. }
  62. type SetOptions struct {
  63. PrevExist PrevExistType
  64. }
  65. type Watcher interface {
  66. Next(context.Context) (*Response, error)
  67. }
  68. type Response struct {
  69. Action string `json:"action"`
  70. Node *Node `json:"node"`
  71. PrevNode *Node `json:"prevNode"`
  72. Index uint64
  73. }
  74. type Nodes []*Node
  75. type Node struct {
  76. Key string `json:"key"`
  77. Value string `json:"value"`
  78. Nodes Nodes `json:"nodes"`
  79. ModifiedIndex uint64 `json:"modifiedIndex"`
  80. CreatedIndex uint64 `json:"createdIndex"`
  81. }
  82. func (n *Node) String() string {
  83. return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex)
  84. }
  85. type httpKeysAPI struct {
  86. client HTTPClient
  87. prefix string
  88. }
  89. func (k *httpKeysAPI) Set(ctx context.Context, key, val string, opts SetOptions) (*Response, error) {
  90. act := &setAction{
  91. Prefix: k.prefix,
  92. Key: key,
  93. Value: val,
  94. Options: opts,
  95. }
  96. resp, body, err := k.client.Do(ctx, act)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  101. }
  102. func (k *httpKeysAPI) Create(ctx context.Context, key, val string) (*Response, error) {
  103. return k.Set(ctx, key, val, SetOptions{PrevExist: PrevNoExist})
  104. }
  105. func (k *httpKeysAPI) Update(ctx context.Context, key, val string) (*Response, error) {
  106. return k.Set(ctx, key, val, SetOptions{PrevExist: PrevExist})
  107. }
  108. func (k *httpKeysAPI) Get(ctx context.Context, key string) (*Response, error) {
  109. get := &getAction{
  110. Prefix: k.prefix,
  111. Key: key,
  112. Recursive: false,
  113. }
  114. resp, body, err := k.client.Do(ctx, get)
  115. if err != nil {
  116. return nil, err
  117. }
  118. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  119. }
  120. func (k *httpKeysAPI) RGet(ctx context.Context, key string) (*Response, error) {
  121. get := &getAction{
  122. Prefix: k.prefix,
  123. Key: key,
  124. Recursive: true,
  125. }
  126. resp, body, err := k.client.Do(ctx, get)
  127. if err != nil {
  128. return nil, err
  129. }
  130. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  131. }
  132. func (k *httpKeysAPI) Watch(key string, idx uint64) Watcher {
  133. return &httpWatcher{
  134. client: k.client,
  135. nextWait: waitAction{
  136. Prefix: k.prefix,
  137. Key: key,
  138. WaitIndex: idx,
  139. Recursive: false,
  140. },
  141. }
  142. }
  143. func (k *httpKeysAPI) RWatch(key string, idx uint64) Watcher {
  144. return &httpWatcher{
  145. client: k.client,
  146. nextWait: waitAction{
  147. Prefix: k.prefix,
  148. Key: key,
  149. WaitIndex: idx,
  150. Recursive: true,
  151. },
  152. }
  153. }
  154. type httpWatcher struct {
  155. client HTTPClient
  156. nextWait waitAction
  157. }
  158. func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) {
  159. httpresp, body, err := hw.client.Do(ctx, &hw.nextWait)
  160. if err != nil {
  161. return nil, err
  162. }
  163. resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body)
  164. if err != nil {
  165. return nil, err
  166. }
  167. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  168. return resp, nil
  169. }
  170. // v2KeysURL forms a URL representing the location of a key.
  171. // The endpoint argument represents the base URL of an etcd
  172. // server. The prefix is the path needed to route from the
  173. // provided endpoint's path to the root of the keys API
  174. // (typically "/v2/keys").
  175. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  176. ep.Path = path.Join(ep.Path, prefix, key)
  177. return &ep
  178. }
  179. type getAction struct {
  180. Prefix string
  181. Key string
  182. Recursive bool
  183. }
  184. func (g *getAction) HTTPRequest(ep url.URL) *http.Request {
  185. u := v2KeysURL(ep, g.Prefix, g.Key)
  186. params := u.Query()
  187. params.Set("recursive", strconv.FormatBool(g.Recursive))
  188. u.RawQuery = params.Encode()
  189. req, _ := http.NewRequest("GET", u.String(), nil)
  190. return req
  191. }
  192. type waitAction struct {
  193. Prefix string
  194. Key string
  195. WaitIndex uint64
  196. Recursive bool
  197. }
  198. func (w *waitAction) HTTPRequest(ep url.URL) *http.Request {
  199. u := v2KeysURL(ep, w.Prefix, w.Key)
  200. params := u.Query()
  201. params.Set("wait", "true")
  202. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  203. params.Set("recursive", strconv.FormatBool(w.Recursive))
  204. u.RawQuery = params.Encode()
  205. req, _ := http.NewRequest("GET", u.String(), nil)
  206. return req
  207. }
  208. type setAction struct {
  209. Prefix string
  210. Key string
  211. Value string
  212. Options SetOptions
  213. }
  214. func (a *setAction) HTTPRequest(ep url.URL) *http.Request {
  215. u := v2KeysURL(ep, a.Prefix, a.Key)
  216. params := u.Query()
  217. if a.Options.PrevExist != PrevIgnore {
  218. params.Set("prevExist", string(a.Options.PrevExist))
  219. }
  220. u.RawQuery = params.Encode()
  221. form := url.Values{}
  222. form.Add("value", a.Value)
  223. body := strings.NewReader(form.Encode())
  224. req, _ := http.NewRequest("PUT", u.String(), body)
  225. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  226. return req
  227. }
  228. func unmarshalHTTPResponse(code int, header http.Header, body []byte) (res *Response, err error) {
  229. switch code {
  230. case http.StatusOK, http.StatusCreated:
  231. res, err = unmarshalSuccessfulResponse(header, body)
  232. default:
  233. err = unmarshalErrorResponse(code)
  234. }
  235. return
  236. }
  237. func unmarshalSuccessfulResponse(header http.Header, body []byte) (*Response, error) {
  238. var res Response
  239. err := json.Unmarshal(body, &res)
  240. if err != nil {
  241. return nil, err
  242. }
  243. if header.Get("X-Etcd-Index") != "" {
  244. res.Index, err = strconv.ParseUint(header.Get("X-Etcd-Index"), 10, 64)
  245. }
  246. if err != nil {
  247. return nil, err
  248. }
  249. return &res, nil
  250. }
  251. func unmarshalErrorResponse(code int) error {
  252. switch code {
  253. case http.StatusNotFound:
  254. return ErrKeyNoExist
  255. case http.StatusPreconditionFailed:
  256. return ErrKeyExists
  257. case http.StatusInternalServerError:
  258. // this isn't necessarily true
  259. return ErrNoLeader
  260. case http.StatusGatewayTimeout:
  261. return ErrTimeout
  262. default:
  263. }
  264. return fmt.Errorf("unrecognized HTTP status code %d", code)
  265. }