keys.go 18 KB

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