keys.go 12 KB

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