keys.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. // Copyright 2015 The etcd Authors
  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. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "go.etcd.io/etcd/pkg/pathutil"
  21. "net/http"
  22. "net/url"
  23. "strconv"
  24. "strings"
  25. "time"
  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. // then 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 specifies 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. // Refresh set to true means a TTL value can be updated
  155. // without firing a watch or changing the node value. A
  156. // value must not be provided when refreshing a key.
  157. Refresh bool
  158. // Dir specifies whether or not this Node should be created as a directory.
  159. Dir bool
  160. // NoValueOnSuccess specifies whether the response contains the current value of the Node.
  161. // If set, the response will only contain the current value when the request fails.
  162. NoValueOnSuccess bool
  163. }
  164. type GetOptions struct {
  165. // Recursive defines whether or not all children of the Node
  166. // should be returned.
  167. Recursive bool
  168. // Sort instructs the server whether or not to sort the Nodes.
  169. // If true, the Nodes are sorted alphabetically by key in
  170. // ascending order (A to z). If false (default), the Nodes will
  171. // not be sorted and the ordering used should not be considered
  172. // predictable.
  173. Sort bool
  174. // Quorum specifies whether it gets the latest committed value that
  175. // has been applied in quorum of members, which ensures external
  176. // consistency (or linearizability).
  177. Quorum bool
  178. }
  179. type DeleteOptions struct {
  180. // PrevValue specifies what the current value of the Node must
  181. // be in order for the Delete operation to succeed.
  182. //
  183. // Leaving this field empty means that the caller wishes to
  184. // ignore the current value of the Node. This cannot be used
  185. // to compare the Node's current value to an empty string.
  186. PrevValue string
  187. // PrevIndex indicates what the current ModifiedIndex of the
  188. // Node must be in order for the Delete operation to succeed.
  189. //
  190. // If PrevIndex is set to 0 (default), no comparison is made.
  191. PrevIndex uint64
  192. // Recursive defines whether or not all children of the Node
  193. // should be deleted. If set to true, all children of the Node
  194. // identified by the given key will be deleted. If left unset
  195. // or explicitly set to false, only a single Node will be
  196. // deleted.
  197. Recursive bool
  198. // Dir specifies whether or not this Node should be removed as a directory.
  199. Dir bool
  200. }
  201. type Watcher interface {
  202. // Next blocks until an etcd event occurs, then returns a Response
  203. // representing that event. The behavior of Next depends on the
  204. // WatcherOptions used to construct the Watcher. Next is designed to
  205. // be called repeatedly, each time blocking until a subsequent event
  206. // is available.
  207. //
  208. // If the provided context is cancelled, Next will return a non-nil
  209. // error. Any other failures encountered while waiting for the next
  210. // event (connection issues, deserialization failures, etc) will
  211. // also result in a non-nil error.
  212. Next(context.Context) (*Response, error)
  213. }
  214. type Response struct {
  215. // Action is the name of the operation that occurred. Possible values
  216. // include get, set, delete, update, create, compareAndSwap,
  217. // compareAndDelete and expire.
  218. Action string `json:"action"`
  219. // Node represents the state of the relevant etcd Node.
  220. Node *Node `json:"node"`
  221. // PrevNode represents the previous state of the Node. PrevNode is non-nil
  222. // only if the Node existed before the action occurred and the action
  223. // caused a change to the Node.
  224. PrevNode *Node `json:"prevNode"`
  225. // Index holds the cluster-level index at the time the Response was generated.
  226. // This index is not tied to the Node(s) contained in this Response.
  227. Index uint64 `json:"-"`
  228. // ClusterID holds the cluster-level ID reported by the server. This
  229. // should be different for different etcd clusters.
  230. ClusterID string `json:"-"`
  231. }
  232. type Node struct {
  233. // Key represents the unique location of this Node (e.g. "/foo/bar").
  234. Key string `json:"key"`
  235. // Dir reports whether node describes a directory.
  236. Dir bool `json:"dir,omitempty"`
  237. // Value is the current data stored on this Node. If this Node
  238. // is a directory, Value will be empty.
  239. Value string `json:"value"`
  240. // Nodes holds the children of this Node, only if this Node is a directory.
  241. // This slice of will be arbitrarily deep (children, grandchildren, great-
  242. // grandchildren, etc.) if a recursive Get or Watch request were made.
  243. Nodes Nodes `json:"nodes"`
  244. // CreatedIndex is the etcd index at-which this Node was created.
  245. CreatedIndex uint64 `json:"createdIndex"`
  246. // ModifiedIndex is the etcd index at-which this Node was last modified.
  247. ModifiedIndex uint64 `json:"modifiedIndex"`
  248. // Expiration is the server side expiration time of the key.
  249. Expiration *time.Time `json:"expiration,omitempty"`
  250. // TTL is the time to live of the key in second.
  251. TTL int64 `json:"ttl,omitempty"`
  252. }
  253. func (n *Node) String() string {
  254. return fmt.Sprintf("{Key: %s, CreatedIndex: %d, ModifiedIndex: %d, TTL: %d}", n.Key, n.CreatedIndex, n.ModifiedIndex, n.TTL)
  255. }
  256. // TTLDuration returns the Node's TTL as a time.Duration object
  257. func (n *Node) TTLDuration() time.Duration {
  258. return time.Duration(n.TTL) * time.Second
  259. }
  260. type Nodes []*Node
  261. // interfaces for sorting
  262. func (ns Nodes) Len() int { return len(ns) }
  263. func (ns Nodes) Less(i, j int) bool { return ns[i].Key < ns[j].Key }
  264. func (ns Nodes) Swap(i, j int) { ns[i], ns[j] = ns[j], ns[i] }
  265. type httpKeysAPI struct {
  266. client httpClient
  267. prefix string
  268. }
  269. func (k *httpKeysAPI) Set(ctx context.Context, key, val string, opts *SetOptions) (*Response, error) {
  270. act := &setAction{
  271. Prefix: k.prefix,
  272. Key: key,
  273. Value: val,
  274. }
  275. if opts != nil {
  276. act.PrevValue = opts.PrevValue
  277. act.PrevIndex = opts.PrevIndex
  278. act.PrevExist = opts.PrevExist
  279. act.TTL = opts.TTL
  280. act.Refresh = opts.Refresh
  281. act.Dir = opts.Dir
  282. act.NoValueOnSuccess = opts.NoValueOnSuccess
  283. }
  284. doCtx := ctx
  285. if act.PrevExist == PrevNoExist {
  286. doCtx = context.WithValue(doCtx, &oneShotCtxValue, &oneShotCtxValue)
  287. }
  288. resp, body, err := k.client.Do(doCtx, act)
  289. if err != nil {
  290. return nil, err
  291. }
  292. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  293. }
  294. func (k *httpKeysAPI) Create(ctx context.Context, key, val string) (*Response, error) {
  295. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevNoExist})
  296. }
  297. func (k *httpKeysAPI) CreateInOrder(ctx context.Context, dir, val string, opts *CreateInOrderOptions) (*Response, error) {
  298. act := &createInOrderAction{
  299. Prefix: k.prefix,
  300. Dir: dir,
  301. Value: val,
  302. }
  303. if opts != nil {
  304. act.TTL = opts.TTL
  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) Update(ctx context.Context, key, val string) (*Response, error) {
  313. return k.Set(ctx, key, val, &SetOptions{PrevExist: PrevExist})
  314. }
  315. func (k *httpKeysAPI) Delete(ctx context.Context, key string, opts *DeleteOptions) (*Response, error) {
  316. act := &deleteAction{
  317. Prefix: k.prefix,
  318. Key: key,
  319. }
  320. if opts != nil {
  321. act.PrevValue = opts.PrevValue
  322. act.PrevIndex = opts.PrevIndex
  323. act.Dir = opts.Dir
  324. act.Recursive = opts.Recursive
  325. }
  326. doCtx := context.WithValue(ctx, &oneShotCtxValue, &oneShotCtxValue)
  327. resp, body, err := k.client.Do(doCtx, act)
  328. if err != nil {
  329. return nil, err
  330. }
  331. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  332. }
  333. func (k *httpKeysAPI) Get(ctx context.Context, key string, opts *GetOptions) (*Response, error) {
  334. act := &getAction{
  335. Prefix: k.prefix,
  336. Key: key,
  337. }
  338. if opts != nil {
  339. act.Recursive = opts.Recursive
  340. act.Sorted = opts.Sort
  341. act.Quorum = opts.Quorum
  342. }
  343. resp, body, err := k.client.Do(ctx, act)
  344. if err != nil {
  345. return nil, err
  346. }
  347. return unmarshalHTTPResponse(resp.StatusCode, resp.Header, body)
  348. }
  349. func (k *httpKeysAPI) Watcher(key string, opts *WatcherOptions) Watcher {
  350. act := waitAction{
  351. Prefix: k.prefix,
  352. Key: key,
  353. }
  354. if opts != nil {
  355. act.Recursive = opts.Recursive
  356. if opts.AfterIndex > 0 {
  357. act.WaitIndex = opts.AfterIndex + 1
  358. }
  359. }
  360. return &httpWatcher{
  361. client: k.client,
  362. nextWait: act,
  363. }
  364. }
  365. type httpWatcher struct {
  366. client httpClient
  367. nextWait waitAction
  368. }
  369. func (hw *httpWatcher) Next(ctx context.Context) (*Response, error) {
  370. for {
  371. httpresp, body, err := hw.client.Do(ctx, &hw.nextWait)
  372. if err != nil {
  373. return nil, err
  374. }
  375. resp, err := unmarshalHTTPResponse(httpresp.StatusCode, httpresp.Header, body)
  376. if err != nil {
  377. if err == ErrEmptyBody {
  378. continue
  379. }
  380. return nil, err
  381. }
  382. hw.nextWait.WaitIndex = resp.Node.ModifiedIndex + 1
  383. return resp, nil
  384. }
  385. }
  386. // v2KeysURL forms a URL representing the location of a key.
  387. // The endpoint argument represents the base URL of an etcd
  388. // server. The prefix is the path needed to route from the
  389. // provided endpoint's path to the root of the keys API
  390. // (typically "/v2/keys").
  391. func v2KeysURL(ep url.URL, prefix, key string) *url.URL {
  392. // We concatenate all parts together manually. We cannot use
  393. // path.Join because it does not reserve trailing slash.
  394. // We call CanonicalURLPath to further cleanup the path.
  395. if prefix != "" && prefix[0] != '/' {
  396. prefix = "/" + prefix
  397. }
  398. if key != "" && key[0] != '/' {
  399. key = "/" + key
  400. }
  401. ep.Path = pathutil.CanonicalURLPath(ep.Path + prefix + key)
  402. return &ep
  403. }
  404. type getAction struct {
  405. Prefix string
  406. Key string
  407. Recursive bool
  408. Sorted bool
  409. Quorum bool
  410. }
  411. func (g *getAction) HTTPRequest(ep url.URL) *http.Request {
  412. u := v2KeysURL(ep, g.Prefix, g.Key)
  413. params := u.Query()
  414. params.Set("recursive", strconv.FormatBool(g.Recursive))
  415. params.Set("sorted", strconv.FormatBool(g.Sorted))
  416. params.Set("quorum", strconv.FormatBool(g.Quorum))
  417. u.RawQuery = params.Encode()
  418. req, _ := http.NewRequest("GET", u.String(), nil)
  419. return req
  420. }
  421. type waitAction struct {
  422. Prefix string
  423. Key string
  424. WaitIndex uint64
  425. Recursive bool
  426. }
  427. func (w *waitAction) HTTPRequest(ep url.URL) *http.Request {
  428. u := v2KeysURL(ep, w.Prefix, w.Key)
  429. params := u.Query()
  430. params.Set("wait", "true")
  431. params.Set("waitIndex", strconv.FormatUint(w.WaitIndex, 10))
  432. params.Set("recursive", strconv.FormatBool(w.Recursive))
  433. u.RawQuery = params.Encode()
  434. req, _ := http.NewRequest("GET", u.String(), nil)
  435. return req
  436. }
  437. type setAction struct {
  438. Prefix string
  439. Key string
  440. Value string
  441. PrevValue string
  442. PrevIndex uint64
  443. PrevExist PrevExistType
  444. TTL time.Duration
  445. Refresh bool
  446. Dir bool
  447. NoValueOnSuccess bool
  448. }
  449. func (a *setAction) HTTPRequest(ep url.URL) *http.Request {
  450. u := v2KeysURL(ep, a.Prefix, a.Key)
  451. params := u.Query()
  452. form := url.Values{}
  453. // we're either creating a directory or setting a key
  454. if a.Dir {
  455. params.Set("dir", strconv.FormatBool(a.Dir))
  456. } else {
  457. // These options are only valid for setting a key
  458. if a.PrevValue != "" {
  459. params.Set("prevValue", a.PrevValue)
  460. }
  461. form.Add("value", a.Value)
  462. }
  463. // Options which apply to both setting a key and creating a dir
  464. if a.PrevIndex != 0 {
  465. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  466. }
  467. if a.PrevExist != PrevIgnore {
  468. params.Set("prevExist", string(a.PrevExist))
  469. }
  470. if a.TTL > 0 {
  471. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  472. }
  473. if a.Refresh {
  474. form.Add("refresh", "true")
  475. }
  476. if a.NoValueOnSuccess {
  477. params.Set("noValueOnSuccess", strconv.FormatBool(a.NoValueOnSuccess))
  478. }
  479. u.RawQuery = params.Encode()
  480. body := strings.NewReader(form.Encode())
  481. req, _ := http.NewRequest("PUT", u.String(), body)
  482. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  483. return req
  484. }
  485. type deleteAction struct {
  486. Prefix string
  487. Key string
  488. PrevValue string
  489. PrevIndex uint64
  490. Dir bool
  491. Recursive bool
  492. }
  493. func (a *deleteAction) HTTPRequest(ep url.URL) *http.Request {
  494. u := v2KeysURL(ep, a.Prefix, a.Key)
  495. params := u.Query()
  496. if a.PrevValue != "" {
  497. params.Set("prevValue", a.PrevValue)
  498. }
  499. if a.PrevIndex != 0 {
  500. params.Set("prevIndex", strconv.FormatUint(a.PrevIndex, 10))
  501. }
  502. if a.Dir {
  503. params.Set("dir", "true")
  504. }
  505. if a.Recursive {
  506. params.Set("recursive", "true")
  507. }
  508. u.RawQuery = params.Encode()
  509. req, _ := http.NewRequest("DELETE", u.String(), nil)
  510. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  511. return req
  512. }
  513. type createInOrderAction struct {
  514. Prefix string
  515. Dir string
  516. Value string
  517. TTL time.Duration
  518. }
  519. func (a *createInOrderAction) HTTPRequest(ep url.URL) *http.Request {
  520. u := v2KeysURL(ep, a.Prefix, a.Dir)
  521. form := url.Values{}
  522. form.Add("value", a.Value)
  523. if a.TTL > 0 {
  524. form.Add("ttl", strconv.FormatUint(uint64(a.TTL.Seconds()), 10))
  525. }
  526. body := strings.NewReader(form.Encode())
  527. req, _ := http.NewRequest("POST", u.String(), body)
  528. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  529. return req
  530. }
  531. func unmarshalHTTPResponse(code int, header http.Header, body []byte) (res *Response, err error) {
  532. switch code {
  533. case http.StatusOK, http.StatusCreated:
  534. if len(body) == 0 {
  535. return nil, ErrEmptyBody
  536. }
  537. res, err = unmarshalSuccessfulKeysResponse(header, body)
  538. default:
  539. err = unmarshalFailedKeysResponse(body)
  540. }
  541. return res, err
  542. }
  543. var jsonIterator = caseSensitiveJsonIterator()
  544. func unmarshalSuccessfulKeysResponse(header http.Header, body []byte) (*Response, error) {
  545. var res Response
  546. err := jsonIterator.Unmarshal(body, &res)
  547. if err != nil {
  548. return nil, ErrInvalidJSON
  549. }
  550. if header.Get("X-Etcd-Index") != "" {
  551. res.Index, err = strconv.ParseUint(header.Get("X-Etcd-Index"), 10, 64)
  552. if err != nil {
  553. return nil, err
  554. }
  555. }
  556. res.ClusterID = header.Get("X-Etcd-Cluster-ID")
  557. return &res, nil
  558. }
  559. func unmarshalFailedKeysResponse(body []byte) error {
  560. var etcdErr Error
  561. if err := json.Unmarshal(body, &etcdErr); err != nil {
  562. return ErrInvalidJSON
  563. }
  564. return etcdErr
  565. }