keys.go 16 KB

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