keys.go 16 KB

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