keys.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. const (
  27. ErrorCodeKeyNotFound = 100
  28. ErrorCodeTestFailed = 101
  29. ErrorCodeNotFile = 102
  30. ErrorCodeNotDir = 104
  31. ErrorCodeNodeExist = 105
  32. ErrorCodeRootROnly = 107
  33. ErrorCodeDirNotEmpty = 108
  34. ErrorCodePrevValueRequired = 201
  35. ErrorCodeTTLNaN = 202
  36. ErrorCodeIndexNaN = 203
  37. ErrorCodeInvalidField = 209
  38. ErrorCodeInvalidForm = 210
  39. ErrorCodeRaftInternal = 300
  40. ErrorCodeLeaderElect = 301
  41. ErrorCodeWatcherCleared = 400
  42. ErrorCodeEventIndexCleared = 401
  43. )
  44. type Error struct {
  45. Code int `json:"errorCode"`
  46. Message string `json:"message"`
  47. Cause string `json:"cause"`
  48. Index uint64 `json:"index"`
  49. }
  50. func (e Error) Error() string {
  51. return fmt.Sprintf("%v: %v (%v) [%v]", e.Code, e.Message, e.Cause, e.Index)
  52. }
  53. // PrevExistType is used to define an existence condition when setting
  54. // or deleting Nodes.
  55. type PrevExistType string
  56. const (
  57. PrevIgnore = PrevExistType("")
  58. PrevExist = PrevExistType("true")
  59. PrevNoExist = PrevExistType("false")
  60. )
  61. var (
  62. defaultV2KeysPrefix = "/v2/keys"
  63. )
  64. // NewKeysAPI builds a KeysAPI that interacts with etcd's key-value
  65. // API over HTTP.
  66. func NewKeysAPI(c Client) KeysAPI {
  67. return NewKeysAPIWithPrefix(c, defaultV2KeysPrefix)
  68. }
  69. // NewKeysAPIWithPrefix acts like NewKeysAPI, but allows the caller
  70. // to provide a custom base URL path. This should only be used in
  71. // very rare cases.
  72. func NewKeysAPIWithPrefix(c Client, p string) KeysAPI {
  73. return &httpKeysAPI{
  74. client: c,
  75. prefix: p,
  76. }
  77. }
  78. type KeysAPI interface {
  79. // Get retrieves a set of Nodes from etcd
  80. Get(ctx context.Context, key string, opts *GetOptions) (*Response, error)
  81. // Set assigns a new value to a Node identified by a given key. The caller
  82. // may define a set of conditions in the SetOptions.
  83. Set(ctx context.Context, key, value string, opts *SetOptions) (*Response, error)
  84. // Delete removes a Node identified by the given key, optionally destroying
  85. // all of its children as well. The caller may define a set of required
  86. // conditions in an DeleteOptions object.
  87. Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error)
  88. // Create is an alias for Set w/ PrevExist=false
  89. Create(ctx context.Context, key, value string) (*Response, error)
  90. // Update is an alias for Set w/ PrevExist=true
  91. Update(ctx context.Context, key, value string) (*Response, error)
  92. // Watcher builds a new Watcher targeted at a specific Node identified
  93. // by the given key. The Watcher may be configured at creation time
  94. // through a WatcherOptions object. The returned Watcher is designed
  95. // to emit events that happen to a Node, and optionally to its children.
  96. Watcher(key string, opts *WatcherOptions) Watcher
  97. }
  98. type WatcherOptions struct {
  99. // AfterIndex defines the index after-which the Watcher should
  100. // start emitting events. For example, if a value of 5 is
  101. // provided, the first event will have an index >= 6.
  102. //
  103. // Setting AfterIndex to 0 (default) means that the Watcher
  104. // should start watching for events starting at the current
  105. // index, whatever that may be.
  106. AfterIndex uint64
  107. // Recursive specifices whether or not the Watcher should emit
  108. // events that occur in children of the given keyspace. If set
  109. // to false (default), events will be limited to those that
  110. // occur for the exact key.
  111. Recursive bool
  112. }
  113. type SetOptions struct {
  114. // PrevValue specifies what the current value of the Node must
  115. // be in order for the Set operation to succeed.
  116. //
  117. // Leaving this field empty means that the caller wishes to
  118. // ignore the current value of the Node. This cannot be used
  119. // to compare the Node's current value to an empty string.
  120. PrevValue string
  121. // PrevIndex indicates what the current ModifiedIndex of the
  122. // Node must be in order for the Set operation to succeed.
  123. //
  124. // If PrevIndex is set to 0 (default), no comparison is made.
  125. PrevIndex uint64
  126. // PrevExist specifies whether the Node must currently exist
  127. // (PrevExist) or not (PrevNoExist). If the caller does not
  128. // care about existence, set PrevExist to PrevIgnore, or simply
  129. // leave it unset.
  130. PrevExist PrevExistType
  131. // TTL defines a period of time after-which the Node should
  132. // expire and no longer exist. Values <= 0 are ignored. Given
  133. // that the zero-value is ignored, TTL cannot be used to set
  134. // a TTL of 0.
  135. TTL time.Duration
  136. }
  137. type GetOptions struct {
  138. // Recursive defines whether or not all children of the Node
  139. // should be returned.
  140. Recursive bool
  141. // Sort instructs the server whether or not to sort the Nodes.
  142. // If true, the Nodes are sorted alphabetically by key in
  143. // ascending order (A to z). If false (default), the Nodes will
  144. // not be sorted and the ordering used should not be considered
  145. // predictable.
  146. Sort bool
  147. }
  148. type DeleteOptions struct {
  149. // PrevValue specifies what the current value of the Node must
  150. // be in order for the Delete operation to succeed.
  151. //
  152. // Leaving this field empty means that the caller wishes to
  153. // ignore the current value of the Node. This cannot be used
  154. // to compare the Node's current value to an empty string.
  155. PrevValue string
  156. // PrevIndex indicates what the current ModifiedIndex of the
  157. // Node must be in order for the Delete operation to succeed.
  158. //
  159. // If PrevIndex is set to 0 (default), no comparison is made.
  160. PrevIndex uint64
  161. // Recursive defines whether or not all children of the Node
  162. // should be deleted. If set to true, all children of the Node
  163. // identified by the given key will be deleted. If left unset
  164. // or explicitly set to false, only a single Node will be
  165. // deleted.
  166. Recursive bool
  167. }
  168. type Watcher interface {
  169. // Next blocks until an etcd event occurs, then returns a Response
  170. // represeting that event. The behavior of Next depends on the
  171. // WatcherOptions used to construct the Watcher. Next is designed to
  172. // be called repeatedly, each time blocking until a subsequent event
  173. // is available.
  174. //
  175. // If the provided context is cancelled, Next will return a non-nil
  176. // error. Any other failures encountered while waiting for the next
  177. // event (connection issues, deserialization failures, etc) will
  178. // also result in a non-nil error.
  179. Next(context.Context) (*Response, error)
  180. }
  181. type Response struct {
  182. // Action is the name of the operation that occurred. Possible values
  183. // include get, set, delete, update, create, compareAndSwap,
  184. // compareAndDelete and expire.
  185. Action string `json:"action"`
  186. // Node represents the state of the relevant etcd Node.
  187. Node *Node `json:"node"`
  188. // PrevNode represents the previous state of the Node. PrevNode is non-nil
  189. // only if the Node existed before the action occured and the action
  190. // caused a change to the Node.
  191. PrevNode *Node `json:"prevNode"`
  192. // Index holds the cluster-level index at the time the Response was generated.
  193. // This index is not tied to the Node(s) contained in this Response.
  194. Index uint64 `json:"-"`
  195. }
  196. type Node struct {
  197. // Key represents the unique location of this Node (e.g. "/foo/bar").
  198. Key string `json:"key"`
  199. // Value is the current data stored on this Node. If this Node
  200. // is a directory, Value will be empty.
  201. Value string `json:"value"`
  202. // Nodes holds the children of this Node, only if this Node is a directory.
  203. // This slice of will be arbitrarily deep (children, grandchildren, great-
  204. // grandchildren, etc.) if a recursive Get or Watch request were made.
  205. Nodes []*Node `json:"nodes"`
  206. // CreatedIndex is the etcd index at-which this Node was created.
  207. CreatedIndex uint64 `json:"createdIndex"`
  208. // ModifiedIndex is the etcd index at-which this Node was last modified.
  209. ModifiedIndex uint64 `json:"modifiedIndex"`
  210. }
  211. func (n *Node) String() string {
  212. return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex)
  213. }
  214. type httpKeysAPI struct {
  215. client httpClient
  216. prefix string
  217. }
  218. func (k *httpKeysAPI) Set(ctx context.Context, key, val string, opts *SetOptions) (*Response, error) {
  219. act := &setAction{
  220. Prefix: k.prefix,
  221. Key: key,
  222. Value: val,
  223. }
  224. if opts != nil {
  225. act.PrevValue = opts.PrevValue
  226. act.PrevIndex = opts.PrevIndex
  227. act.PrevExist = opts.PrevExist
  228. act.TTL = opts.TTL
  229. }
  230. resp, body, err := k.client.Do(ctx, act)
  231. if err != nil {
  232. return nil, err
  233. }
  234. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  235. }
  236. func (k *httpKeysAPI) Create(ctx context.Context, key, val string) (*Response, error) {
  237. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevNoExist})
  238. }
  239. func (k *httpKeysAPI) Update(ctx context.Context, key, val string) (*Response, error) {
  240. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevExist})
  241. }
  242. func (k *httpKeysAPI) Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error) {
  243. act := &deleteAction{
  244. Prefix: k.prefix,
  245. Key: key,
  246. }
  247. if opts != nil {
  248. act.PrevValue = opts.PrevValue
  249. act.PrevIndex = opts.PrevIndex
  250. act.Recursive = opts.Recursive
  251. }
  252. resp, body, err := k.client.Do(ctx, act)
  253. if err != nil {
  254. return nil, err
  255. }
  256. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  257. }
  258. func (k *httpKeysAPI) Get(ctx context.Context, key string, opts *GetOptions) (*Response, error) {
  259. act := &getAction{
  260. Prefix: k.prefix,
  261. Key: key,
  262. }
  263. if opts != nil {
  264. act.Recursive = opts.Recursive
  265. act.Sorted = opts.Sort
  266. }
  267. resp, body, err := k.client.Do(ctx, act)
  268. if err != nil {
  269. return nil, err
  270. }
  271. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  272. }
  273. func (k *httpKeysAPI) Watcher(key string, opts *WatcherOptions) Watcher {
  274. act := waitAction{
  275. Prefix: k.prefix,
  276. Key: key,
  277. }
  278. if opts != nil {
  279. act.Recursive = opts.Recursive
  280. if opts.AfterIndex > 0 {
  281. act.WaitIndex = opts.AfterIndex + 1
  282. }
  283. }
  284. return &httpWatcher{
  285. client: k.client,
  286. nextWait: act,
  287. }
  288. }
  289. type httpWatcher struct {
  290. client httpClient
  291. nextWait waitAction
  292. }
  293. func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) {
  294. httpresp, body, err := hw.client.Do(ctx, &hw.nextWait)
  295. if err != nil {
  296. return nil, err
  297. }
  298. resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body)
  299. if err != nil {
  300. return nil, err
  301. }
  302. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  303. return resp, nil
  304. }
  305. // v2KeysURL forms a URL representing the location of a key.
  306. // The endpoint argument represents the base URL of an etcd
  307. // server. The prefix is the path needed to route from the
  308. // provided endpoint's path to the root of the keys API
  309. // (typically "/v2/keys").
  310. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  311. ep.Path = path.Join(ep.Path, prefix, key)
  312. return &ep
  313. }
  314. type getAction struct {
  315. Prefix string
  316. Key string
  317. Recursive bool
  318. Sorted bool
  319. }
  320. func (g *getAction) HTTPRequest(ep url.URL) *http.Request {
  321. u := v2KeysURL(ep, g.Prefix, g.Key)
  322. params := u.Query()
  323. params.Set("recursive", strconv.FormatBool(g.Recursive))
  324. params.Set("sorted", strconv.FormatBool(g.Sorted))
  325. u.RawQuery = params.Encode()
  326. req, _ := http.NewRequest("GET", u.String(), nil)
  327. return req
  328. }
  329. type waitAction struct {
  330. Prefix string
  331. Key string
  332. WaitIndex uint64
  333. Recursive bool
  334. }
  335. func (w *waitAction) HTTPRequest(ep url.URL) *http.Request {
  336. u := v2KeysURL(ep, w.Prefix, w.Key)
  337. params := u.Query()
  338. params.Set("wait", "true")
  339. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  340. params.Set("recursive", strconv.FormatBool(w.Recursive))
  341. u.RawQuery = params.Encode()
  342. req, _ := http.NewRequest("GET", u.String(), nil)
  343. return req
  344. }
  345. type setAction struct {
  346. Prefix string
  347. Key string
  348. Value string
  349. PrevValue string
  350. PrevIndex uint64
  351. PrevExist PrevExistType
  352. TTL time.Duration
  353. }
  354. func (a *setAction) HTTPRequest(ep url.URL) *http.Request {
  355. u := v2KeysURL(ep, a.Prefix, a.Key)
  356. params := u.Query()
  357. if a.PrevValue != "" {
  358. params.Set("prevValue", a.PrevValue)
  359. }
  360. if a.PrevIndex != 0 {
  361. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  362. }
  363. if a.PrevExist != PrevIgnore {
  364. params.Set("prevExist", string(a.PrevExist))
  365. }
  366. u.RawQuery = params.Encode()
  367. form := url.Values{}
  368. form.Add("value", a.Value)
  369. if a.TTL > 0 {
  370. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  371. }
  372. body := strings.NewReader(form.Encode())
  373. req, _ := http.NewRequest("PUT", u.String(), body)
  374. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  375. return req
  376. }
  377. type deleteAction struct {
  378. Prefix string
  379. Key string
  380. Value string
  381. PrevValue string
  382. PrevIndex uint64
  383. Recursive bool
  384. }
  385. func (a *deleteAction) HTTPRequest(ep url.URL) *http.Request {
  386. u := v2KeysURL(ep, a.Prefix, a.Key)
  387. params := u.Query()
  388. if a.PrevValue != "" {
  389. params.Set("prevValue", a.PrevValue)
  390. }
  391. if a.PrevIndex != 0 {
  392. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  393. }
  394. if a.Recursive {
  395. params.Set("recursive", "true")
  396. }
  397. u.RawQuery = params.Encode()
  398. req, _ := http.NewRequest("DELETE", u.String(), nil)
  399. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  400. return req
  401. }
  402. func unmarshalHTTPResponse(code int, header http.Header, body []byte) (res *Response, err error) {
  403. switch code {
  404. case http.StatusOK, http.StatusCreated:
  405. res, err = unmarshalSuccessfulKeysResponse(header, body)
  406. default:
  407. err = unmarshalFailedKeysResponse(body)
  408. }
  409. return
  410. }
  411. func unmarshalSuccessfulKeysResponse(header http.Header, body []byte) (*Response, error) {
  412. var res Response
  413. err := json.Unmarshal(body, &res)
  414. if err != nil {
  415. return nil, err
  416. }
  417. if header.Get("X-Etcd-Index") != "" {
  418. res.Index, err = strconv.ParseUint(header.Get("X-Etcd-Index"), 10, 64)
  419. if err != nil {
  420. return nil, err
  421. }
  422. }
  423. return &res, nil
  424. }
  425. func unmarshalFailedKeysResponse(body []byte) error {
  426. var etcdErr Error
  427. if err := json.Unmarshal(body, &etcdErr); err != nil {
  428. return err
  429. }
  430. return etcdErr
  431. }