keys.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. If SetOptions.Dir=true
  83. // than value is ignored.
  84. Set(ctx context.Context, key, value string, opts *SetOptions) (*Response, error)
  85. // Delete removes a Node identified by the given key, optionally destroying
  86. // all of its children as well. The caller may define a set of required
  87. // conditions in an DeleteOptions object.
  88. Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error)
  89. // Create is an alias for Set w/ PrevExist=false
  90. Create(ctx context.Context, key, value string) (*Response, error)
  91. // CreateInOrder is used to atomically create in-order keys within the given directory.
  92. CreateInOrder(ctx context.Context, dir, value string, opts *CreateInOrderOptions) (*Response, error)
  93. // Update is an alias for Set w/ PrevExist=true
  94. Update(ctx context.Context, key, value string) (*Response, error)
  95. // Watcher builds a new Watcher targeted at a specific Node identified
  96. // by the given key. The Watcher may be configured at creation time
  97. // through a WatcherOptions object. The returned Watcher is designed
  98. // to emit events that happen to a Node, and optionally to its children.
  99. Watcher(key string, opts *WatcherOptions) Watcher
  100. }
  101. type WatcherOptions struct {
  102. // AfterIndex defines the index after-which the Watcher should
  103. // start emitting events. For example, if a value of 5 is
  104. // provided, the first event will have an index >= 6.
  105. //
  106. // Setting AfterIndex to 0 (default) means that the Watcher
  107. // should start watching for events starting at the current
  108. // index, whatever that may be.
  109. AfterIndex uint64
  110. // Recursive specifices whether or not the Watcher should emit
  111. // events that occur in children of the given keyspace. If set
  112. // to false (default), events will be limited to those that
  113. // occur for the exact key.
  114. Recursive bool
  115. }
  116. type CreateInOrderOptions struct {
  117. // TTL defines a period of time after-which the Node should
  118. // expire and no longer exist. Values <= 0 are ignored. Given
  119. // that the zero-value is ignored, TTL cannot be used to set
  120. // a TTL of 0.
  121. TTL time.Duration
  122. }
  123. type SetOptions struct {
  124. // PrevValue specifies what the current value of the Node must
  125. // be in order for the Set operation to succeed.
  126. //
  127. // Leaving this field empty means that the caller wishes to
  128. // ignore the current value of the Node. This cannot be used
  129. // to compare the Node's current value to an empty string.
  130. //
  131. // PrevValue is ignored if Dir=true
  132. PrevValue string
  133. // PrevIndex indicates what the current ModifiedIndex of the
  134. // Node must be in order for the Set operation to succeed.
  135. //
  136. // If PrevIndex is set to 0 (default), no comparison is made.
  137. PrevIndex uint64
  138. // PrevExist specifies whether the Node must currently exist
  139. // (PrevExist) or not (PrevNoExist). If the caller does not
  140. // care about existence, set PrevExist to PrevIgnore, or simply
  141. // leave it unset.
  142. PrevExist PrevExistType
  143. // TTL defines a period of time after-which the Node should
  144. // expire and no longer exist. Values <= 0 are ignored. Given
  145. // that the zero-value is ignored, TTL cannot be used to set
  146. // a TTL of 0.
  147. TTL time.Duration
  148. // Dir specifies whether or not this Node should be created as a directory.
  149. Dir bool
  150. }
  151. type GetOptions struct {
  152. // Recursive defines whether or not all children of the Node
  153. // should be returned.
  154. Recursive bool
  155. // Sort instructs the server whether or not to sort the Nodes.
  156. // If true, the Nodes are sorted alphabetically by key in
  157. // ascending order (A to z). If false (default), the Nodes will
  158. // not be sorted and the ordering used should not be considered
  159. // predictable.
  160. Sort bool
  161. }
  162. type DeleteOptions struct {
  163. // PrevValue specifies what the current value of the Node must
  164. // be in order for the Delete operation to succeed.
  165. //
  166. // Leaving this field empty means that the caller wishes to
  167. // ignore the current value of the Node. This cannot be used
  168. // to compare the Node's current value to an empty string.
  169. PrevValue string
  170. // PrevIndex indicates what the current ModifiedIndex of the
  171. // Node must be in order for the Delete operation to succeed.
  172. //
  173. // If PrevIndex is set to 0 (default), no comparison is made.
  174. PrevIndex uint64
  175. // Recursive defines whether or not all children of the Node
  176. // should be deleted. If set to true, all children of the Node
  177. // identified by the given key will be deleted. If left unset
  178. // or explicitly set to false, only a single Node will be
  179. // deleted.
  180. Recursive bool
  181. // Dir specifies whether or not this Node should be removed as a directory.
  182. Dir bool
  183. }
  184. type Watcher interface {
  185. // Next blocks until an etcd event occurs, then returns a Response
  186. // represeting that event. The behavior of Next depends on the
  187. // WatcherOptions used to construct the Watcher. Next is designed to
  188. // be called repeatedly, each time blocking until a subsequent event
  189. // is available.
  190. //
  191. // If the provided context is cancelled, Next will return a non-nil
  192. // error. Any other failures encountered while waiting for the next
  193. // event (connection issues, deserialization failures, etc) will
  194. // also result in a non-nil error.
  195. Next(context.Context) (*Response, error)
  196. }
  197. type Response struct {
  198. // Action is the name of the operation that occurred. Possible values
  199. // include get, set, delete, update, create, compareAndSwap,
  200. // compareAndDelete and expire.
  201. Action string `json:"action"`
  202. // Node represents the state of the relevant etcd Node.
  203. Node *Node `json:"node"`
  204. // PrevNode represents the previous state of the Node. PrevNode is non-nil
  205. // only if the Node existed before the action occured and the action
  206. // caused a change to the Node.
  207. PrevNode *Node `json:"prevNode"`
  208. // Index holds the cluster-level index at the time the Response was generated.
  209. // This index is not tied to the Node(s) contained in this Response.
  210. Index uint64 `json:"-"`
  211. }
  212. type Node struct {
  213. // Key represents the unique location of this Node (e.g. "/foo/bar").
  214. Key string `json:"key"`
  215. // Dir reports whether node describes a directory.
  216. Dir bool `json:"dir,omitempty"`
  217. // Value is the current data stored on this Node. If this Node
  218. // is a directory, Value will be empty.
  219. Value string `json:"value"`
  220. // Nodes holds the children of this Node, only if this Node is a directory.
  221. // This slice of will be arbitrarily deep (children, grandchildren, great-
  222. // grandchildren, etc.) if a recursive Get or Watch request were made.
  223. Nodes []*Node `json:"nodes"`
  224. // CreatedIndex is the etcd index at-which this Node was created.
  225. CreatedIndex uint64 `json:"createdIndex"`
  226. // ModifiedIndex is the etcd index at-which this Node was last modified.
  227. ModifiedIndex uint64 `json:"modifiedIndex"`
  228. // Expiration is the server side expiration time of the key.
  229. Expiration *time.Time `json:"expiration,omitempty"`
  230. // TTL is the time to live of the key in second.
  231. TTL int64 `json:"ttl,omitempty"`
  232. }
  233. func (n *Node) String() string {
  234. return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d, TTL: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex, n.TTL)
  235. }
  236. // TTLDuration returns the Node's TTL as a time.Duration object
  237. func (n *Node) TTLDuration() time.Duration {
  238. return time.Duration(n.TTL) * time.Second
  239. }
  240. type httpKeysAPI struct {
  241. client httpClient
  242. prefix string
  243. }
  244. func (k *httpKeysAPI) Set(ctx context.Context, key, val string, opts *SetOptions) (*Response, error) {
  245. act := &setAction{
  246. Prefix: k.prefix,
  247. Key: key,
  248. Value: val,
  249. }
  250. if opts != nil {
  251. act.PrevValue = opts.PrevValue
  252. act.PrevIndex = opts.PrevIndex
  253. act.PrevExist = opts.PrevExist
  254. act.TTL = opts.TTL
  255. act.Dir = opts.Dir
  256. }
  257. resp, body, err := k.client.Do(ctx, act)
  258. if err != nil {
  259. return nil, err
  260. }
  261. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  262. }
  263. func (k *httpKeysAPI) Create(ctx context.Context, key, val string) (*Response, error) {
  264. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevNoExist})
  265. }
  266. func (k *httpKeysAPI) CreateInOrder(ctx context.Context, dir, val string, opts *CreateInOrderOptions) (*Response, error) {
  267. act := &createInOrderAction{
  268. Prefix: k.prefix,
  269. Dir: dir,
  270. Value: val,
  271. }
  272. if opts != nil {
  273. act.TTL = opts.TTL
  274. }
  275. resp, body, err := k.client.Do(ctx, act)
  276. if err != nil {
  277. return nil, err
  278. }
  279. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  280. }
  281. func (k *httpKeysAPI) Update(ctx context.Context, key, val string) (*Response, error) {
  282. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevExist})
  283. }
  284. func (k *httpKeysAPI) Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error) {
  285. act := &deleteAction{
  286. Prefix: k.prefix,
  287. Key: key,
  288. }
  289. if opts != nil {
  290. act.PrevValue = opts.PrevValue
  291. act.PrevIndex = opts.PrevIndex
  292. act.Dir = opts.Dir
  293. act.Recursive = opts.Recursive
  294. }
  295. resp, body, err := k.client.Do(ctx, act)
  296. if err != nil {
  297. return nil, err
  298. }
  299. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  300. }
  301. func (k *httpKeysAPI) Get(ctx context.Context, key string, opts *GetOptions) (*Response, error) {
  302. act := &getAction{
  303. Prefix: k.prefix,
  304. Key: key,
  305. }
  306. if opts != nil {
  307. act.Recursive = opts.Recursive
  308. act.Sorted = opts.Sort
  309. }
  310. resp, body, err := k.client.Do(ctx, act)
  311. if err != nil {
  312. return nil, err
  313. }
  314. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  315. }
  316. func (k *httpKeysAPI) Watcher(key string, opts *WatcherOptions) Watcher {
  317. act := waitAction{
  318. Prefix: k.prefix,
  319. Key: key,
  320. }
  321. if opts != nil {
  322. act.Recursive = opts.Recursive
  323. if opts.AfterIndex > 0 {
  324. act.WaitIndex = opts.AfterIndex + 1
  325. }
  326. }
  327. return &httpWatcher{
  328. client: k.client,
  329. nextWait: act,
  330. }
  331. }
  332. type httpWatcher struct {
  333. client httpClient
  334. nextWait waitAction
  335. }
  336. func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) {
  337. httpresp, body, err := hw.client.Do(ctx, &hw.nextWait)
  338. if err != nil {
  339. return nil, err
  340. }
  341. resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body)
  342. if err != nil {
  343. return nil, err
  344. }
  345. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  346. return resp, nil
  347. }
  348. // v2KeysURL forms a URL representing the location of a key.
  349. // The endpoint argument represents the base URL of an etcd
  350. // server. The prefix is the path needed to route from the
  351. // provided endpoint's path to the root of the keys API
  352. // (typically "/v2/keys").
  353. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  354. ep.Path = path.Join(ep.Path, prefix, key)
  355. return &ep
  356. }
  357. type getAction struct {
  358. Prefix string
  359. Key string
  360. Recursive bool
  361. Sorted bool
  362. }
  363. func (g *getAction) HTTPRequest(ep url.URL) *http.Request {
  364. u := v2KeysURL(ep, g.Prefix, g.Key)
  365. params := u.Query()
  366. params.Set("recursive", strconv.FormatBool(g.Recursive))
  367. params.Set("sorted", strconv.FormatBool(g.Sorted))
  368. u.RawQuery = params.Encode()
  369. req, _ := http.NewRequest("GET", u.String(), nil)
  370. return req
  371. }
  372. type waitAction struct {
  373. Prefix string
  374. Key string
  375. WaitIndex uint64
  376. Recursive bool
  377. }
  378. func (w *waitAction) HTTPRequest(ep url.URL) *http.Request {
  379. u := v2KeysURL(ep, w.Prefix, w.Key)
  380. params := u.Query()
  381. params.Set("wait", "true")
  382. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  383. params.Set("recursive", strconv.FormatBool(w.Recursive))
  384. u.RawQuery = params.Encode()
  385. req, _ := http.NewRequest("GET", u.String(), nil)
  386. return req
  387. }
  388. type setAction struct {
  389. Prefix string
  390. Key string
  391. Value string
  392. PrevValue string
  393. PrevIndex uint64
  394. PrevExist PrevExistType
  395. TTL time.Duration
  396. Dir bool
  397. }
  398. func (a *setAction) HTTPRequest(ep url.URL) *http.Request {
  399. u := v2KeysURL(ep, a.Prefix, a.Key)
  400. params := u.Query()
  401. form := url.Values{}
  402. // we're either creating a directory or setting a key
  403. if a.Dir {
  404. params.Set("dir", strconv.FormatBool(a.Dir))
  405. } else {
  406. // These options are only valid for setting a key
  407. if a.PrevValue != "" {
  408. params.Set("prevValue", a.PrevValue)
  409. }
  410. form.Add("value", a.Value)
  411. }
  412. // Options which apply to both setting a key and creating a dir
  413. if a.PrevIndex != 0 {
  414. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  415. }
  416. if a.PrevExist != PrevIgnore {
  417. params.Set("prevExist", string(a.PrevExist))
  418. }
  419. if a.TTL > 0 {
  420. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  421. }
  422. u.RawQuery = params.Encode()
  423. body := strings.NewReader(form.Encode())
  424. req, _ := http.NewRequest("PUT", u.String(), body)
  425. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  426. return req
  427. }
  428. type deleteAction struct {
  429. Prefix string
  430. Key string
  431. PrevValue string
  432. PrevIndex uint64
  433. Dir bool
  434. Recursive bool
  435. }
  436. func (a *deleteAction) HTTPRequest(ep url.URL) *http.Request {
  437. u := v2KeysURL(ep, a.Prefix, a.Key)
  438. params := u.Query()
  439. if a.PrevValue != "" {
  440. params.Set("prevValue", a.PrevValue)
  441. }
  442. if a.PrevIndex != 0 {
  443. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  444. }
  445. if a.Dir {
  446. params.Set("dir", "true")
  447. }
  448. if a.Recursive {
  449. params.Set("recursive", "true")
  450. }
  451. u.RawQuery = params.Encode()
  452. req, _ := http.NewRequest("DELETE", u.String(), nil)
  453. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  454. return req
  455. }
  456. type createInOrderAction struct {
  457. Prefix string
  458. Dir string
  459. Value string
  460. TTL time.Duration
  461. }
  462. func (a *createInOrderAction) HTTPRequest(ep url.URL) *http.Request {
  463. u := v2KeysURL(ep, a.Prefix, a.Dir)
  464. form := url.Values{}
  465. form.Add("value", a.Value)
  466. if a.TTL > 0 {
  467. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  468. }
  469. body := strings.NewReader(form.Encode())
  470. req, _ := http.NewRequest("POST", u.String(), body)
  471. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  472. return req
  473. }
  474. func unmarshalHTTPResponse(code int, header http.Header, body []byte) (res *Response, err error) {
  475. switch code {
  476. case http.StatusOK, http.StatusCreated:
  477. res, err = unmarshalSuccessfulKeysResponse(header, body)
  478. default:
  479. err = unmarshalFailedKeysResponse(body)
  480. }
  481. return
  482. }
  483. func unmarshalSuccessfulKeysResponse(header http.Header, body []byte) (*Response, error) {
  484. var res Response
  485. err := json.Unmarshal(body, &res)
  486. if err != nil {
  487. return nil, err
  488. }
  489. if header.Get("X-Etcd-Index") != "" {
  490. res.Index, err = strconv.ParseUint(header.Get("X-Etcd-Index"), 10, 64)
  491. if err != nil {
  492. return nil, err
  493. }
  494. }
  495. return &res, nil
  496. }
  497. func unmarshalFailedKeysResponse(body []byte) error {
  498. var etcdErr Error
  499. if err := json.Unmarshal(body, &etcdErr); err != nil {
  500. return err
  501. }
  502. return etcdErr
  503. }