keys.go 17 KB

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