keys.go 16 KB

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