keys.go 17 KB

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