keys.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. "fmt"
  18. "net/http"
  19. "net/url"
  20. "path"
  21. "strconv"
  22. "strings"
  23. "time"
  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. // NewKeysAPI builds a KeysAPI that interacts with etcd's key-value
  36. // API over HTTP.
  37. func NewKeysAPI(c Client) KeysAPI {
  38. return NewKeysAPIWithPrefix(c, defaultV2KeysPrefix)
  39. }
  40. // NewKeysAPIWithPrefix acts like NewKeysAPI, but allows the caller
  41. // to provide a custom base URL path. This should only be used in
  42. // very rare cases.
  43. func NewKeysAPIWithPrefix(c Client, p string) KeysAPI {
  44. return &httpKeysAPI{
  45. client: c,
  46. prefix: p,
  47. }
  48. }
  49. type KeysAPI interface {
  50. Set(ctx context.Context, key, value string, opts *SetOptions) (*Response, error)
  51. Create(ctx context.Context, key, value string) (*Response, error)
  52. Update(ctx context.Context, key, value string) (*Response, error)
  53. Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error)
  54. Get(ctx context.Context, key string) (*Response, error)
  55. RGet(ctx context.Context, key string) (*Response, error)
  56. Watcher(key string, opts *WatcherOptions) Watcher
  57. }
  58. type WatcherOptions struct {
  59. // WaitIndex defines the index after-which the Watcher should
  60. // start emitting events. For example, if a value of 5 is
  61. // provided, the first event will have an index >= 6.
  62. //
  63. // Setting WaitIndex to 0 (default) means that the Watcher
  64. // should start watching for events starting at the current
  65. // index, whatever that may be.
  66. WaitIndex uint64
  67. // Recursive specifices whether or not the Watcher should emit
  68. // events that occur in children of the given keyspace. If set
  69. // to false (default), events will be limited to those that
  70. // occur for the exact key.
  71. Recursive bool
  72. }
  73. type SetOptions struct {
  74. // PrevValue specifies what the current value of the Node must
  75. // be in order for the Set operation to succeed.
  76. //
  77. // Leaving this field empty means that the caller wishes to
  78. // ignore the current value of the Node. This cannot be used
  79. // to compare the Node's current value to an empty string.
  80. PrevValue string
  81. // PrevIndex indicates what the current ModifiedIndex of the
  82. // Node must be in order for the Set operation to succeed.
  83. //
  84. // If PrevIndex is set to 0 (default), no comparison is made.
  85. PrevIndex uint64
  86. // PrevExist specifies whether the Node must currently exist
  87. // (PrevExist) or not (PrevNoExist). If the caller does not
  88. // care about existence, set PrevExist to PrevIgnore, or simply
  89. // leave it unset.
  90. PrevExist PrevExistType
  91. // TTL defines a period of time after-which the Node should
  92. // expire and no longer exist. Values <= 0 are ignored. Given
  93. // that the zero-value is ignored, TTL cannot be used to set
  94. // a TTL of 0.
  95. TTL time.Duration
  96. }
  97. type DeleteOptions struct {
  98. // PrevValue specifies what the current value of the Node must
  99. // be in order for the Delete operation to succeed.
  100. //
  101. // Leaving this field empty means that the caller wishes to
  102. // ignore the current value of the Node. This cannot be used
  103. // to compare the Node's current value to an empty string.
  104. PrevValue string
  105. // PrevIndex indicates what the current ModifiedIndex of the
  106. // Node must be in order for the Delete operation to succeed.
  107. //
  108. // If PrevIndex is set to 0 (default), no comparison is made.
  109. PrevIndex uint64
  110. // Recursive defines whether or not all children of the Node
  111. // should be deleted. If set to true, all children of the Node
  112. // identified by the given key will be deleted. If left unset
  113. // or explicitly set to false, only a single Node will be
  114. // deleted.
  115. Recursive bool
  116. }
  117. type Watcher interface {
  118. // Next blocks until an etcd event occurs, then returns a Response
  119. // represeting that event. The behavior of Next depends on the
  120. // WatcherOptions used to construct the Watcher. Next is designed to
  121. // be called repeatedly, each time blocking until a subsequent event
  122. // is available.
  123. //
  124. // If the provided context is cancelled, Next will return a non-nil
  125. // error. Any other failures encountered while waiting for the next
  126. // event (connection issues, deserialization failures, etc) will
  127. // also result in a non-nil error.
  128. Next(context.Context) (*Response, error)
  129. }
  130. type Response struct {
  131. Action string `json:"action"`
  132. Node *Node `json:"node"`
  133. PrevNode *Node `json:"prevNode"`
  134. Index uint64
  135. }
  136. type Node struct {
  137. Key string `json:"key"`
  138. Value string `json:"value"`
  139. Nodes []*Node `json:"nodes"`
  140. ModifiedIndex uint64 `json:"modifiedIndex"`
  141. CreatedIndex uint64 `json:"createdIndex"`
  142. }
  143. func (n *Node) String() string {
  144. return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex)
  145. }
  146. type httpKeysAPI struct {
  147. client httpClient
  148. prefix string
  149. }
  150. func (k *httpKeysAPI) Set(ctx context.Context, key, val string, opts *SetOptions) (*Response, error) {
  151. act := &setAction{
  152. Prefix: k.prefix,
  153. Key: key,
  154. Value: val,
  155. }
  156. if opts != nil {
  157. act.PrevValue = opts.PrevValue
  158. act.PrevIndex = opts.PrevIndex
  159. act.PrevExist = opts.PrevExist
  160. act.TTL = opts.TTL
  161. }
  162. resp, body, err := k.client.Do(ctx, act)
  163. if err != nil {
  164. return nil, err
  165. }
  166. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  167. }
  168. func (k *httpKeysAPI) Create(ctx context.Context, key, val string) (*Response, error) {
  169. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevNoExist})
  170. }
  171. func (k *httpKeysAPI) Update(ctx context.Context, key, val string) (*Response, error) {
  172. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevExist})
  173. }
  174. func (k *httpKeysAPI) Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error) {
  175. act := &deleteAction{
  176. Prefix: k.prefix,
  177. Key: key,
  178. }
  179. if opts != nil {
  180. act.PrevValue = opts.PrevValue
  181. act.PrevIndex = opts.PrevIndex
  182. act.Recursive = opts.Recursive
  183. }
  184. resp, body, err := k.client.Do(ctx, act)
  185. if err != nil {
  186. return nil, err
  187. }
  188. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  189. }
  190. func (k *httpKeysAPI) Get(ctx context.Context, key string) (*Response, error) {
  191. get := &getAction{
  192. Prefix: k.prefix,
  193. Key: key,
  194. Recursive: false,
  195. }
  196. resp, body, err := k.client.Do(ctx, get)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  201. }
  202. func (k *httpKeysAPI) RGet(ctx context.Context, key string) (*Response, error) {
  203. get := &getAction{
  204. Prefix: k.prefix,
  205. Key: key,
  206. Recursive: true,
  207. }
  208. resp, body, err := k.client.Do(ctx, get)
  209. if err != nil {
  210. return nil, err
  211. }
  212. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  213. }
  214. func (k *httpKeysAPI) Watcher(key string, opts *WatcherOptions) Watcher {
  215. act := waitAction{
  216. Prefix: k.prefix,
  217. Key: key,
  218. }
  219. if opts != nil {
  220. act.WaitIndex = opts.WaitIndex
  221. act.Recursive = opts.Recursive
  222. }
  223. return &httpWatcher{
  224. client: k.client,
  225. nextWait: act,
  226. }
  227. }
  228. type httpWatcher struct {
  229. client httpClient
  230. nextWait waitAction
  231. }
  232. func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) {
  233. httpresp, body, err := hw.client.Do(ctx, &hw.nextWait)
  234. if err != nil {
  235. return nil, err
  236. }
  237. resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body)
  238. if err != nil {
  239. return nil, err
  240. }
  241. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  242. return resp, nil
  243. }
  244. // v2KeysURL forms a URL representing the location of a key.
  245. // The endpoint argument represents the base URL of an etcd
  246. // server. The prefix is the path needed to route from the
  247. // provided endpoint's path to the root of the keys API
  248. // (typically "/v2/keys").
  249. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  250. ep.Path = path.Join(ep.Path, prefix, key)
  251. return &ep
  252. }
  253. type getAction struct {
  254. Prefix string
  255. Key string
  256. Recursive bool
  257. }
  258. func (g *getAction) HTTPRequest(ep url.URL) *http.Request {
  259. u := v2KeysURL(ep, g.Prefix, g.Key)
  260. params := u.Query()
  261. params.Set("recursive", strconv.FormatBool(g.Recursive))
  262. u.RawQuery = params.Encode()
  263. req, _ := http.NewRequest("GET", u.String(), nil)
  264. return req
  265. }
  266. type waitAction struct {
  267. Prefix string
  268. Key string
  269. WaitIndex uint64
  270. Recursive bool
  271. }
  272. func (w *waitAction) HTTPRequest(ep url.URL) *http.Request {
  273. u := v2KeysURL(ep, w.Prefix, w.Key)
  274. params := u.Query()
  275. params.Set("wait", "true")
  276. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  277. params.Set("recursive", strconv.FormatBool(w.Recursive))
  278. u.RawQuery = params.Encode()
  279. req, _ := http.NewRequest("GET", u.String(), nil)
  280. return req
  281. }
  282. type setAction struct {
  283. Prefix string
  284. Key string
  285. Value string
  286. PrevValue string
  287. PrevIndex uint64
  288. PrevExist PrevExistType
  289. TTL time.Duration
  290. }
  291. func (a *setAction) HTTPRequest(ep url.URL) *http.Request {
  292. u := v2KeysURL(ep, a.Prefix, a.Key)
  293. params := u.Query()
  294. if a.PrevValue != "" {
  295. params.Set("prevValue", a.PrevValue)
  296. }
  297. if a.PrevIndex != 0 {
  298. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  299. }
  300. if a.PrevExist != PrevIgnore {
  301. params.Set("prevExist", string(a.PrevExist))
  302. }
  303. u.RawQuery = params.Encode()
  304. form := url.Values{}
  305. form.Add("value", a.Value)
  306. if a.TTL > 0 {
  307. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  308. }
  309. body := strings.NewReader(form.Encode())
  310. req, _ := http.NewRequest("PUT", u.String(), body)
  311. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  312. return req
  313. }
  314. type deleteAction struct {
  315. Prefix string
  316. Key string
  317. Value string
  318. PrevValue string
  319. PrevIndex uint64
  320. Recursive bool
  321. }
  322. func (a *deleteAction) HTTPRequest(ep url.URL) *http.Request {
  323. u := v2KeysURL(ep, a.Prefix, a.Key)
  324. params := u.Query()
  325. if a.PrevValue != "" {
  326. params.Set("prevValue", a.PrevValue)
  327. }
  328. if a.PrevIndex != 0 {
  329. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  330. }
  331. if a.Recursive {
  332. params.Set("recursive", "true")
  333. }
  334. u.RawQuery = params.Encode()
  335. req, _ := http.NewRequest("DELETE", u.String(), nil)
  336. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  337. return req
  338. }
  339. func unmarshalHTTPResponse(code int, header http.Header, body []byte) (res *Response, err error) {
  340. switch code {
  341. case http.StatusOK, http.StatusCreated:
  342. res, err = unmarshalSuccessfulResponse(header, body)
  343. default:
  344. err = unmarshalErrorResponse(code)
  345. }
  346. return
  347. }
  348. func unmarshalSuccessfulResponse(header http.Header, body []byte) (*Response, error) {
  349. var res Response
  350. err := json.Unmarshal(body, &res)
  351. if err != nil {
  352. return nil, err
  353. }
  354. if header.Get("X-Etcd-Index") != "" {
  355. res.Index, err = strconv.ParseUint(header.Get("X-Etcd-Index"), 10, 64)
  356. }
  357. if err != nil {
  358. return nil, err
  359. }
  360. return &res, nil
  361. }
  362. func unmarshalErrorResponse(code int) error {
  363. switch code {
  364. case http.StatusNotFound:
  365. return ErrKeyNoExist
  366. case http.StatusPreconditionFailed:
  367. return ErrKeyExists
  368. case http.StatusInternalServerError:
  369. // this isn't necessarily true
  370. return ErrNoLeader
  371. case http.StatusGatewayTimeout:
  372. return ErrTimeout
  373. default:
  374. }
  375. return fmt.Errorf("unrecognized HTTP status code %d", code)
  376. }