keys.go 17 KB

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